@jiabaida/tools 1.0.6 → 1.0.8
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/BleCmdAnalysis/readAndSetParam.js +1 -1
- package/dist/cjs/core/OtaUpgrade.js +1 -1
- package/dist/cjs/core/Queue.js +1 -0
- package/dist/cjs/core/mqttServer.js +1 -0
- package/dist/cjs/core/rsaEncrypt.js +1 -0
- package/dist/cjs/core/tcpServer.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/BleCmdAnalysis/readAndSetParam.js +1 -1
- package/dist/esm/core/OtaUpgrade.js +1 -1
- package/dist/esm/core/Queue.js +1 -0
- package/dist/esm/core/mqttServer.js +1 -0
- package/dist/esm/core/rsaEncrypt.js +1 -0
- package/dist/esm/core/tcpServer.js +1 -0
- package/dist/esm/index.js +1 -1
- package/package.json +4 -3
- package/src/core/BleApiManager.js +3 -1
- package/src/core/BleCmdAnalysis/BaseParamProtocol.js +71 -12
- package/src/core/BleCmdAnalysis/BleCmdAnalysis.js +3 -2
- package/src/core/BleCmdAnalysis/BleCmdDD.js +72 -13
- package/src/core/BleCmdAnalysis/BleCmdDDA4.js +74 -11
- package/src/core/BleCmdAnalysis/index.js +6 -5
- package/src/core/BleCmdAnalysis/readAndSetParam.js +97 -8
- package/src/core/OtaUpgrade.js +8 -2
- package/src/core/Queue.js +34 -0
- package/src/core/mqttServer.js +28 -9
- package/src/core/rsaEncrypt.js +1 -1
- package/src/core/tcpServer.js +303 -0
- package/src/index.js +5 -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",{isAndroid:isAndroid,isIOS:isIOS}=commonfun.getOS(),bluetoothAdapterState=vue.ref({available:!1,discovering:!1});exports.isInit=!1;const checkBluetoothStatus=async(successCallback=()=>{})=>new Promise((resolve,reject)=>{uni.openBluetoothAdapter({success:async res=>{successCallback&&successCallback(res),resolve(res)},fail:err=>{console.log("openBluetoothAdapter fail4-----",err),err&&3==err?.errno&&reject({code:105,message:"请授权微信位置信息和蓝牙权限"}),err&&103==err?.errno&&reject({code:106,message:"请授权蓝牙和位置权限,并重启小程序"}),reject({code:102,message:"当前手机蓝牙不可用,请检查手机蓝牙状态"})}})}),checkLocationStatus=async(successCallback=()=>{})=>{const timeoutPromise=new Promise((resolve,reject)=>{setTimeout(()=>{reject({code:101,message:"网络信号差或连接异常,请检查网络情况"})},1e4)}),locationPromise=new Promise((resolve,reject)=>{uni.getLocation({type:"wgs84",success:res=>{console.log("位置信息-----------",res),resolve(res)},fail:err=>{console.log("位置信息err",err),err&&103==err?.errno&&reject({code:103,message:"请授权小程序位置信息权限, 并重启小程序。"}),err&&2==err?.errCode&&reject({code:101,message:"网络信号差或连接异常,请检查网络情况"}),reject({code:104,message:"请授权微信位置信息权限, 并重启小程序。"})}})});return Promise.race([locationPromise,timeoutPromise]).then(async res=>await checkBluetoothStatus(successCallback))},getBluetoothPermission=async(successCallback=()=>{})=>{try{return isAndroid?await checkLocationStatus(successCallback):await checkBluetoothStatus(successCallback)}catch(error){throw console.error("初始化蓝牙失败:",error),error}},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);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})(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.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(()=>{try{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
|
+
"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)&&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
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var BleDataProcess=require("../BleDataProcess.js"),baseParamsJson=require("../dataJson/baseParamsJson.js"),BleCmdDD=require("./BleCmdDD.js"),readAndSetParam=require("./readAndSetParam.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);let normCap=null;if(datas.normCap&&datas.normCap.length>=4){console.log("normCap原始数据: ",datas.normCap);const lowBytes=datas.normCap.slice(0,2),lowValue=lowBytes[0]<<8|lowBytes[1];console.log("normCap lowValue: ",lowValue);const highBytes=datas.normCap.slice(2,4),highValue=highBytes[0]<<8|highBytes[1];console.log("normCap highValue: ",highValue);const totalValue=highValue<<16|lowValue;console.log("normCap totalValue: ",totalValue),normCap=Number((.01*totalValue).toFixed(2)),console.log("normCap最终值: ",normCap)}else if(datas.normCap&&datas.normCap.length>=2){const lowBytes=datas.normCap.slice(0,2),lowValue=lowBytes[0]<<8|lowBytes[1];normCap=Number((.01*lowValue).toFixed(2))}const cycleCap=format(datas.cycleCap,.01,0,2);let fullCap=null;if(datas.fullCap&&datas.fullCap.length>=4){console.log("fullCap原始数据: ",datas.fullCap);const lowBytes=datas.fullCap.slice(0,2),lowValue=lowBytes[0]<<8|lowBytes[1];console.log("fullCap lowValue: ",lowValue);const highBytes=datas.fullCap.slice(2,4),highValue=highBytes[0]<<8|highBytes[1];console.log("fullCap highValue: ",highValue);const totalValue=highValue<<16|lowValue;console.log("fullCap totalValue: ",totalValue),fullCap=Number((.01*totalValue).toFixed(2)),console.log("fullCap最终值: ",fullCap)}else if(datas.fullCap&&datas.fullCap.length>=2){const lowBytes=datas.fullCap.slice(0,2),lowValue=lowBytes[0]<<8|lowBytes[1];fullCap=Number((.01*lowValue).toFixed(2))}return{normCap:normCap,cycleCap:cycleCap,fullCap:fullCap}},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 normCapLow=await readAndSetParam.getSysParamCmd(chipType,deviceId,{paramNo:0,paramLength:2}),normCapHigh=await readAndSetParam.getSysParamCmd(chipType,deviceId,{paramNo:155,paramLength:2});console.log("normCapLow: ",normCapLow,"normCapHigh: ",normCapHigh),datasInfo2.normCap=[...normCapLow?.slice(0,2)||[],...normCapHigh?.slice(0,2)||[]];const cycleCapData=await readAndSetParam.getSysParamCmd(chipType,deviceId,baseParamsJson.capInfoJson[1]);datasInfo2.cycleCap=cycleCapData?.slice(0,2);const fullCapLow=await readAndSetParam.getSysParamCmd(chipType,deviceId,{paramNo:112,paramLength:2}),fullCapHigh=await readAndSetParam.getSysParamCmd(chipType,deviceId,{paramNo:156,paramLength:2});console.log("fullCapLow: ",fullCapLow,"fullCapHigh: ",fullCapHigh),datasInfo2.fullCap=[...fullCapLow?.slice(0,2)||[],...fullCapHigh?.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(),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;
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var BleDataProcess=require("../BleDataProcess.js"),BleCmdAnalysis=require("./BleCmdAnalysis.js"),BleCmdFFAA=require("./BleCmdFFAA.js"),readAndSetParam=require("./readAndSetParam.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})),hasProtocol=data[3]+7>=humidityIndex+11+3+1,protocolVersion=data[humidityIndex+11];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,hasProtocol:hasProtocol,protocolVersion:protocolVersion}},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=>{try{const startTime=+new Date;let acStatus=!1;const mosRes=await readAndSetParam.controlSwitch(deviceId,"0x00",!0,!0),disChargMOSRes=mosRes?.dataStr,disChargEndTime=+new Date,activeHex=await getDD5AFBAsync(deviceId,"0x05","0x01"),activeResult=resolveBaseDD(activeHex);console.log("激活指令结果: ",{activeHex:activeHex,activeResult:activeResult});const activeRes=activeResult?.dataStr;let endTime=+new Date,baseInfo=null,voltageInfo=null,steps=[];if("00"==activeResult?.status)steps.push(4),acStatus=!0;else if("81"==activeResult?.status||"84"==activeResult?.status)"00"==mosRes?.status?(acStatus=!0,steps.push(5)):(acStatus=!1,steps.push(10));else if("82"==activeResult?.status||"83"==activeResult?.status)acStatus=!1,steps.push(6);else if(!activeResult||null==activeResult){await BleDataProcess.sleep(300);const baseInfo=await getDDA503Async(deviceId);baseInfo?.dischargeSwitch?(acStatus=!0,steps.push(7)):(acStatus=!1,steps.push(8)),endTime=+new Date}return{disChargMOSRes:disChargMOSRes,activeHex:activeHex,activeRes:activeRes,baseInfo:baseInfo,voltageInfo:voltageInfo,startTime:startTime,disChargEndTime:disChargEndTime,endTime:endTime,acStatus:acStatus,steps:steps}}catch(error){return console.log("🚀 ~ BleApiManager ~ activateAsync ~ error:",error),null}},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=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},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});var BleDataProcess=require("../BleDataProcess.js"),BleCmdDD=require("./BleCmdDD.js");const readParamCmd=(chipType,deviceId,paramInfo,needFactoryMode=!0)=>(console.log("chipType: ",chipType),new Promise(async(resolve,reject)=>{const{address:address=0,length:length=1,oldAddress:oldAddress="0x1f"}=paramInfo,hexAddress=BleDataProcess.decimalToTwoByteHexArray(address),hexLength=BleDataProcess.decimalToHex(length),handleRead=async(readFunction,index)=>{try{const hex=await readFunction();if(4==index&&needFactoryMode&&await BleCmdDD.readExistFactory(deviceId),!hex)return void resolve(null);const data=hex.slice(index,-3);console.log("data: 读参数",data),resolve(data||null)}catch(error){console.error("读取参数出错: ",error),reject(error)}};try{if(chipType)await handleRead(async()=>await BleCmdDD.getDDA5FAAsync(deviceId,hexAddress,hexLength),7);else{if(!oldAddress)return resolve(null);needFactoryMode&&await BleCmdDD.enterFactory(deviceId),await handleRead(async()=>await BleCmdDD.getDDA5OldAsync(deviceId,oldAddress),4)}}catch(error){console.error("读取参数出错---: ",error),reject(error)}})),setParamCmd=(chipType,deviceId,paramInfoArray)=>{console.log("chipType: 芯片",chipType);const paramsToProcess=Array.isArray(paramInfoArray)?paramInfoArray:[paramInfoArray];return new Promise(async(resolve,reject)=>{try{await BleCmdDD.enterFactory(deviceId);const results=[];for(let i=0;i<paramsToProcess.length;i++){const paramInfo=paramsToProcess[i],{address:address,length:length,values:values,oldAddress:oldAddress}=paramInfo,hexAddress=BleDataProcess.decimalToTwoByteHexArray(address),hexLength=BleDataProcess.decimalToHex(length);let hex;if(hex=chipType?await BleCmdDD.setDDA5FAAsync(deviceId,hexAddress,hexLength,values):await BleCmdDD.setDDA5OldAsync(deviceId,oldAddress,values),console.log(`data: 写入第${i+1}个参数结果`,hex),!hex)throw new Error(`设置第${i+1}个参数失败`);results.push(hex)}await BleCmdDD.existFactory(deviceId),resolve(results)}catch(error){console.error("设置参数出错: ",error);try{await BleCmdDD.existFactory(deviceId)}catch(exitError){console.error("退出工厂模式失败: ",exitError)}reject(error)}})};exports.getSysParamCmd=async(chipType,deviceId,paramInfo,needFactoryMode=!0)=>{try{console.log("paramInfo: ",paramInfo);const paramObj={address:paramInfo.paramNo,length:paramInfo.paramLength/2,oldAddress:paramInfo.oldParamNo};let data=await readParamCmd(chipType,deviceId,paramObj,needFactoryMode);return data||null}catch(error){throw console.error("error: 读系统参数报错 getSysParamCmd",error),error}},exports.readParamCmd=readParamCmd,exports.setCapacityParamCmd=(chipType,deviceId,paramInfo)=>(console.log("chipType: 芯片",chipType),new Promise(async(resolve,reject)=>{const{values:values}=paramInfo,circular={address:1,oldAddress:"0x11",values:.8*values,length:1},full={address:112,oldAddress:"0x10",values:values,length:1},handleSet=async(setFunction,index)=>{try{const hex=await setFunction();return console.log("data: 写入参数结果",hex),hex||void reject("设置参数失败")}catch(error){console.error("设置参数出错: ",error),reject(error)}},handleParam=async paramObj=>{const{paramNo:paramNo,oldParamNo:oldParamNo,paramLength:paramLength}=paramObj,value=Math.round(Number(paramObj.values)/paramInfo.divisor);console.log("value: ",value);const hexValues=BleDataProcess.decimalToTwoByteHexArray(value),hexAddress=BleDataProcess.decimalToTwoByteHexArray(paramNo),hexLength=BleDataProcess.decimalToHex(paramLength/2);return chipType?await handleSet(()=>BleCmdDD.setDDA5FAAsync(deviceId,hexAddress,hexLength,hexValues)):await handleSet(()=>BleCmdDD.setDDA5OldAsync(deviceId,oldParamNo,hexValues))};try{await BleCmdDD.enterFactory(deviceId);const paramInfoHex=await handleParam(paramInfo);await handleParam(circular);if(chipType){await handleParam(full)}await BleCmdDD.existFactory(deviceId),paramInfoHex&&resolve(paramInfoHex)}catch(error){reject(error)}})),exports.setParamCmd=setParamCmd,exports.setSysParamCmd=async(chipType,deviceId,paramInfoArray)=>{try{console.log("paramInfoArray: ",paramInfoArray);const paramsToProcess=Array.isArray(paramInfoArray)?paramInfoArray:[paramInfoArray],paramObjs=[];for(const paramInfo of paramsToProcess){let value=
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var BleDataProcess=require("../BleDataProcess.js"),BleCmdDD=require("./BleCmdDD.js");const readParamCmd=(chipType,deviceId,paramInfo,needFactoryMode=!0)=>(console.log("chipType: ",chipType),new Promise(async(resolve,reject)=>{const{address:address=0,length:length=1,oldAddress:oldAddress="0x1f"}=paramInfo,hexAddress=BleDataProcess.decimalToTwoByteHexArray(address),hexLength=BleDataProcess.decimalToHex(length),handleRead=async(readFunction,index)=>{try{const hex=await readFunction();if(4==index&&needFactoryMode&&await BleCmdDD.readExistFactory(deviceId),!hex)return void resolve(null);const data=hex.slice(index,-3);console.log("data: 读参数",data),resolve(data||null)}catch(error){console.error("读取参数出错: ",error),reject(error)}};try{if(chipType)await handleRead(async()=>await BleCmdDD.getDDA5FAAsync(deviceId,hexAddress,hexLength),7);else{if(!oldAddress)return resolve(null);needFactoryMode&&await BleCmdDD.enterFactory(deviceId),await handleRead(async()=>await BleCmdDD.getDDA5OldAsync(deviceId,oldAddress),4)}}catch(error){console.error("读取参数出错---: ",error),reject(error)}})),setParamCmd=async(chipType,deviceId,paramInfoArray)=>{console.log("chipType: 芯片",chipType);const paramsToProcess=Array.isArray(paramInfoArray)?paramInfoArray:[paramInfoArray];return new Promise(async(resolve,reject)=>{try{await BleCmdDD.enterFactory(deviceId);const results=[];for(let i=0;i<paramsToProcess.length;i++){const paramInfo=paramsToProcess[i],{address:address,length:length,values:values,oldAddress:oldAddress}=paramInfo,hexAddress=BleDataProcess.decimalToTwoByteHexArray(address),hexLength=BleDataProcess.decimalToHex(length);let hex;if(hex=chipType?await BleCmdDD.setDDA5FAAsync(deviceId,hexAddress,hexLength,values):await BleCmdDD.setDDA5OldAsync(deviceId,oldAddress,values),console.log(`data: 写入第${i+1}个参数结果`,hex),!hex)throw new Error(`设置第${i+1}个参数失败`);results.push(hex)}await BleCmdDD.existFactory(deviceId),resolve(results)}catch(error){console.error("设置参数出错: ",error);try{await BleCmdDD.existFactory(deviceId)}catch(exitError){console.error("退出工厂模式失败: ",exitError)}reject(error)}})},getE1Cmd=(typeCmd,currentSwitch,anotherSwitch)=>{let cmd="0x00";return"0x00"===typeCmd?cmd=currentSwitch&&anotherSwitch?"0x00":currentSwitch&&!anotherSwitch?"0x01":!currentSwitch&&anotherSwitch?"0x02":"0x03":"0x01"===typeCmd&&(cmd=currentSwitch&&anotherSwitch?"0x00":!currentSwitch&&anotherSwitch?"0x01":currentSwitch&&!anotherSwitch?"0x02":"0x03"),cmd};exports.controlSwitch=async(deviceId,typeCmd,currentSwitch,anotherSwitch)=>{const hex=await BleCmdDD.getDD5AFBAsync(deviceId,typeCmd,currentSwitch?"0x00":"0x01"),mosRes=BleCmdDD.resolveBaseDD(hex);console.log("hex: ",hex);let dataRes=mosRes;if(!mosRes||"00"!=mosRes?.status){const cmd=getE1Cmd(typeCmd,currentSwitch,anotherSwitch),e1hex=await BleCmdDD.getDD5AE1Async(deviceId,cmd);dataRes=BleCmdDD.resolveBaseDD(e1hex)}return dataRes},exports.getE1Cmd=getE1Cmd,exports.getSysParamCmd=async(chipType,deviceId,paramInfo,needFactoryMode=!0)=>{try{console.log("paramInfo: ",paramInfo);const paramObj={address:paramInfo.paramNo,length:paramInfo.paramLength/2,oldAddress:paramInfo.oldParamNo};let data=await readParamCmd(chipType,deviceId,paramObj,needFactoryMode);return data||null}catch(error){throw console.error("error: 读系统参数报错 getSysParamCmd",error),error}},exports.readParamCmd=readParamCmd,exports.setCapacityParamCmd=(chipType,deviceId,paramInfo)=>(console.log("chipType: 芯片",chipType),new Promise(async(resolve,reject)=>{const{values:values}=paramInfo,circular={address:1,oldAddress:"0x11",values:.8*values,length:1},full={address:112,oldAddress:"0x10",values:values,length:1},handleSet=async(setFunction,index)=>{try{const hex=await setFunction();return console.log("data: 写入参数结果",hex),hex||void reject("设置参数失败")}catch(error){console.error("设置参数出错: ",error),reject(error)}},handleParam=async paramObj=>{const{paramNo:paramNo,oldParamNo:oldParamNo,paramLength:paramLength}=paramObj,value=Math.round(Number(paramObj.values)/paramInfo.divisor);console.log("value: ",value);const hexValues=BleDataProcess.decimalToTwoByteHexArray(value),hexAddress=BleDataProcess.decimalToTwoByteHexArray(paramNo),hexLength=BleDataProcess.decimalToHex(paramLength/2);return chipType?await handleSet(()=>BleCmdDD.setDDA5FAAsync(deviceId,hexAddress,hexLength,hexValues)):await handleSet(()=>BleCmdDD.setDDA5OldAsync(deviceId,oldParamNo,hexValues))};try{await BleCmdDD.enterFactory(deviceId);const paramInfoHex=await handleParam(paramInfo);await handleParam(circular);if(chipType){await handleParam(full)}await BleCmdDD.existFactory(deviceId),paramInfoHex&&resolve(paramInfoHex)}catch(error){reject(error)}})),exports.setParamCmd=setParamCmd,exports.setSysParamCmd=async(chipType,deviceId,paramInfoArray,macAddr,blueConnect=!0)=>{try{console.log("paramInfoArray: ",paramInfoArray);const paramsToProcess=Array.isArray(paramInfoArray)?paramInfoArray:[paramInfoArray],paramObjs=[];for(const paramInfo of paramsToProcess){let value=Number(paramInfo?.paramValue||paramInfo.newValue)/Number(paramInfo?.divisor||1);console.log("value: ",value),paramInfo.isTemp&&blueConnect&&(value=2731+10*Number(paramInfo.newValue)),value=Math.round(value);let valuesHexs=[];blueConnect&&(valuesHexs=BleDataProcess.decimalToTwoByteHexArray(value),console.log("valuesHexs: ",valuesHexs)),paramObjs.push({address:paramInfo.paramNo,length:paramInfo.paramLength/2,values:valuesHexs,oldAddress:paramInfo.oldParamNo,newValue:value})}console.log("chipType: 芯片",chipType),await setParamCmd(chipType,deviceId,paramObjs)}catch(error){throw console.error("error: 写系统参数报错 setSysParamCmd",error),error}};
|
|
@@ -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: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
|
|
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:()=>{console.error("写入失败: ",pkg),this.fail("写入失败")}})}})}};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("升级失败"))}async transferFirmwareFile(){let nextTime=this.finishedTimes+1;if(nextTime>this.totalTimes){const pkg=[0];await Transfer.BLE.sendDelay(20),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);await Transfer.BLE.sendDelay(20),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;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";var Queue$1=class{constructor(){this._items=[]}enqueue(item){this._items.push(item)}dequeue(){return this._items.shift()}head(){return this._items[0]}tail(){return this._items[this._items.length-1]}isEmpty(){return!this._items.length}size(){return this._items.length}clear(){this._items=[]}};module.exports=Queue$1;
|
|
@@ -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,store:store=null}){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,this.$store=store}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,this.$store?.commit("setMqttClient",this.mqttClient),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,this.$store?.commit("setMqttPublish",!1),uni.removeStorageSync&&uni.removeStorageSync(`${deviceId}_mqttPublish`))}catch(error){console.error(error)}}closeMqttByDeviceId(deviceId){const client=this.mqttClient[`${deviceId}_mqtt`];client&&client.end(()=>{this.mqttClient[`${deviceId}_mqtt`]=null,console.log(`MQTT 连接已关闭,设备ID: ${deviceId}`)})}handleMqttClose(client,res){console.log("MQTT 连接关闭",res,client),client.end(()=>{this.mqttClient[`${client.options.deviceId}_mqtt`]=null,this.$store?.commit("setMqttClient",this.mqttClient)})}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,this.$store?.commit("setMqttPublish",!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.$store?.commit("setMqttPublish",!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,this.$store?.commit("setMqttPublish",!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)};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var vue=require("vue"),BleCmdDD=require("./BleCmdAnalysis/BleCmdDD.js"),BleCmdFFAA=require("./BleCmdAnalysis/BleCmdFFAA.js"),BleCmdHVES=require("./BleCmdAnalysis/BleCmdHVES.js"),BleDataProcess=require("./BleDataProcess.js"),Queue=require("./Queue.js"),Transfer=require("./Transfer.js");const tcpSend=vue.reactive({isSending:!1,isLast:!1,code:null,hasHeartbeat:!1,tcpClose:!1,devices:{}}),messageQueue=new Queue;let timer=null;const tcpServer={version:"2.8.2",socketOpen:!1,macAddr:"",txnNo:"",baseDelay:1e3,maxDelay:6e4,retryCount:0,url:{address:"cloud.jiabaida.com",port:10241},url1:{address:"192.168.80.36",port:10240},timers:{},heartBeatTimers:{},tcpSockets:{},isRetryings:{},socketOpens:{},async initTCPConnection(macAddr,deviceId){return console.log("macAddr: init-------tcp",macAddr,deviceId),new Promise((resolve,reject)=>{try{tcpSend.devices[macAddr]={macAddr:macAddr,deviceId:deviceId},this.tcpSockets[`${deviceId}_socket`]=wx.createTCPSocket(),console.log("this.tcpSockets[`${deviceId}_socket`]: ",this.tcpSockets[`${deviceId}_socket`]),this.tcpSockets[`${deviceId}_socket`].connect(this.url),this.tcpSockets[`${deviceId}_socket`].onConnect(()=>{this.listenerConnect(macAddr,deviceId),resolve(!0)}),this.tcpSockets[`${deviceId}_socket`].onMessage(message=>{console.log("接收到消息:",message);const intArr=Array.prototype.map.call(new Uint8Array(message.message),function(bit){return bit});let valueString=String.fromCharCode(...intArr);console.log(valueString,"valueString"),this.processMessageAsync(valueString)}),this.tcpSockets[`${deviceId}_socket`].onError(error=>{this.listenerError(macAddr,deviceId,error),reject(error)}),this.tcpSockets[`${deviceId}_socket`].onClose(this.listenerClose(deviceId))}catch(error){console.error("error: tcp连接失败",error),reject(error)}})},listenerConnect(macAddr,deviceId){this.socketOpens[`open_${deviceId}`]=!0,this.isRetryings[`retry_${deviceId}`]=!1,console.log("TCP 连接已建立"),clearInterval(this.timers[`timer_${deviceId}`]),this.timers[`timer_${deviceId}`]=null,this.sendHeartbeat(macAddr,deviceId)},listenerError(macAddr,deviceId,error){this.socketOpens[`open_${deviceId}`]=!1,console.log("TCP 连接错误:",deviceId,error),this.stopHeartBeat(deviceId),this.isRetryings[`retry_${deviceId}`]||(this.retryCount=0,this.reConnect(macAddr,deviceId,!0))},listenerClose(deviceId){this.socketOpens[`open_${deviceId}`]=!1,console.log("TCP 连接已关闭")},closeTcpSocket(deviceId){try{clearInterval(this.timers[`timer_${deviceId}`]),this.timers[`timer_${deviceId}`]=null,this.tcpSockets[`${deviceId}_socket`]&&(this.socketOpens[`open_${deviceId}`]=!1,this.stopHeartBeat(deviceId),this.tcpSockets[`${deviceId}_socket`].offMessage(),this.tcpSockets[`${deviceId}_socket`].offConnect(),this.tcpSockets[`${deviceId}_socket`].offClose(),this.tcpSockets[`${deviceId}_socket`].offError(),this.tcpSockets[`${deviceId}_socket`].close(),this.tcpSockets[`${deviceId}_socket`]=null)}catch(error){console.error("error: closeTcpSocket",error)}},async reConnect(macAddr,deviceId,closeSocket=!1){console.log("重连 this.macAddr",macAddr),this.isRetryings[`retry_${deviceId}`]=!0,closeSocket&&this.tcpSockets[`${deviceId}_socket`].close(),this.tcpSockets[`${deviceId}_socket`].connect(this.url);const delay=Math.min(this.baseDelay*Math.pow(2,this.retryCount),this.maxDelay);console.log(`准备 ${delay}ms 后重试...`),this.timers[`timer_${deviceId}`]=setTimeout(()=>{this.reConnect(macAddr,deviceId)},delay),this.retryCount++},sendHeartbeat(macAddr,deviceId){const heartbeatMsg={command:96,data:{token:uni.getStorageSync("token").replace("Bearer ",""),appVersion:"xiaoxiang:"+this.version,macAddr:macAddr},txnNo:+new Date,isAnonymous:0};console.log("heartbeatMsg: ",heartbeatMsg),tcpSend.hasHeartbeat=!1,this.tcpSockets[`${deviceId}_socket`].write(JSON.stringify(heartbeatMsg)),this.heartBeatTimers[`heartTimer_${deviceId}`]=setInterval(()=>{heartbeatMsg.txnNo=+new Date,tcpSend.hasHeartbeat=!1,this.tcpSockets[`${deviceId}_socket`].write(JSON.stringify(heartbeatMsg))},3e4)},stopHeartBeat(deviceId){this.heartBeatTimers[`heartTimer_${deviceId}`]&&(clearInterval(this.heartBeatTimers[`heartTimer_${deviceId}`]),this.heartBeatTimers[`heartTimer_${deviceId}`]=null)},sendReportData(data){const reportData={command:999,data:{value:data.value,cmdCode:"jbd0F",bluetoothName:data.bluetoothName},macAddr:data.macAddr,txnNo:+new Date};console.log(reportData,"reportData111上报基础数据"),this.tcpSockets[`${data.deviceId}_socket`].write(JSON.stringify(reportData))},sendWriteReportData(data,deviceId){console.warn("执行后上报数据data: ",data);const reportData={command:121,data:{macAddr:this.macAddr,content:data},txnNo:this.txnNo};this.tcpSockets[`${deviceId}_socket`].write(JSON.stringify(reportData)),tcpSend.isLast&&(tcpSend.isSending=!1)},processQueue(){tcpSend.isSending||this.processNextMessage()},async processNextMessage(){if(messageQueue.isEmpty())await BleDataProcess.sleep(300),tcpSend.isSending=!1;else{const message=messageQueue.dequeue();this.processMessageAsync(message).then(()=>{this.processNextMessage()})}},async processMessageAsync(message){return clearTimeout(timer),new Promise(async resolve=>{try{console.log("Message processed:",message);let msgObj=JSON.parse(message);if(console.warn("----------msgObj后台下发的指令: -----------",msgObj),120==msgObj.command){let value=msgObj.data.content;if(!value)return;let resultArray=value.match(/.{1,2}/g);console.log("resultArray: ",resultArray),this.macAddr=msgObj.data.macAddr;let deviceId=null;for(let key in tcpSend.devices)tcpSend.devices[key].macAddr==this.macAddr&&(deviceId=tcpSend.devices[key].deviceId);console.log("deviceId: ",deviceId),this.txnNo=msgObj.txnNo,tcpSend.isLast=msgObj.isLast,tcpSend.isSending=!0,tcpSend.code=resultArray[2];let length=resultArray.length;const buffer=new ArrayBuffer(length),dataView=new DataView(buffer);resultArray.forEach((el,index)=>{dataView.setUint8(index,"0x"+el)}),console.log(buffer,"读取指令-----------------------");let res=null;res="FF"===resultArray[0]?.toUpperCase()&&"AA"===resultArray[1]?.toUpperCase()?await BleCmdFFAA.set_PlanCMD_FFAA(deviceId,resultArray.join("")):"78"===resultArray[1]?.toUpperCase()||"50"===resultArray[1]?.toUpperCase()?await BleCmdHVES.getCMDESInfoAsync(deviceId,resultArray.join("")):await BleCmdDD.set_PlanCMD_DD(deviceId,resultArray.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()==tcpSend?.code?.toUpperCase()&&this.sendWriteReportData(content,deviceId)}else 97==msgObj.command&&(tcpSend.hasHeartbeat=!0);timer=setTimeout(()=>{tcpSend.isSending=!1},3e4),resolve(!0)}catch(error){console.log("error: ",error)}})}};exports.tcpSend=tcpSend,exports.tcpServer=tcpServer;
|
package/dist/cjs/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var array=require("./core/array.js"),BleApiManager=require("./core/BleApiManager.js"),commonfun=require("./core/commonfun.js"),keyAndPwdManager=require("./core/keyAndPwdManager.js"),OtaUpgrade=require("./core/OtaUpgrade.js"),TelinkApi=require("./core/TelinkApi.js"),Transfer=require("./core/Transfer.js"),BleDataProcess=require("./core/BleDataProcess.js"),BleCmdAnalysis=require("./core/BleCmdAnalysis/BleCmdAnalysis.js"),BleCmdFFAA=require("./core/BleCmdAnalysis/BleCmdFFAA.js"),BleCmdDD=require("./core/BleCmdAnalysis/BleCmdDD.js"),readAndSetParam=require("./core/BleCmdAnalysis/readAndSetParam.js"),BaseParamProtocol=require("./core/BleCmdAnalysis/BaseParamProtocol.js"),BleCmdHVES=require("./core/BleCmdAnalysis/BleCmdHVES.js"),ESHostProtocol=require("./core/BleCmdAnalysis/ESHostProtocol.js"),baseParamsJson=require("./core/dataJson/baseParamsJson.js");exports.chunk=array.chunk,exports.unique=array.unique,exports.checkBluetoothStatus=BleApiManager.checkBluetoothStatus,exports.checkLocationStatus=BleApiManager.checkLocationStatus,exports.connectAsync=BleApiManager.connectAsync,exports.createBLEConnection=BleApiManager.createBLEConnection,exports.disConnect=BleApiManager.disConnect,exports.foundScanDevice=BleApiManager.foundScanDevice,exports.getBLEDeviceCharacteristics=BleApiManager.getBLEDeviceCharacteristics,exports.getBLEDeviceServices=BleApiManager.getBLEDeviceServices,exports.getBluetoothAdapterState=BleApiManager.getBluetoothAdapterState,exports.getBluetoothPermission=BleApiManager.getBluetoothPermission,exports.initBle=BleApiManager.initBle,Object.defineProperty(exports,"isInit",{enumerable:!0,get:function(){return BleApiManager.isInit}}),exports.notify=BleApiManager.notify,exports.onBLECharacteristicValueChange=BleApiManager.onBLECharacteristicValueChange,exports.onBLEConnectionStateChange=BleApiManager.onBLEConnectionStateChange,exports.onBleChangedConnectionState=BleApiManager.onBleChangedConnectionState,exports.onBluetoothAdapterStateChange=BleApiManager.onBluetoothAdapterStateChange,exports.onBluetoothDeviceFound=BleApiManager.onBluetoothDeviceFound,exports.onFoundDevice=BleApiManager.onFoundDevice,exports.scanHandle=BleApiManager.scanHandle,exports.startDevicesDiscovery=BleApiManager.startDevicesDiscovery,exports.stopBluetoothDevicesDiscovery=BleApiManager.stopBluetoothDevicesDiscovery,exports.eventBus=commonfun.eventBus,exports.formatTimeHHmm=commonfun.formatTimeHHmm,exports.getOS=commonfun.getOS,exports.getPlatform=commonfun.getPlatform,exports.inArray=commonfun.inArray,exports.isEmpty=commonfun.isEmpty,exports.isNotEmpty=commonfun.isNotEmpty,exports.ALLOWED_MAC_PREFIX=keyAndPwdManager.ALLOWED_MAC_PREFIX,exports.APP_KEY_STATUS=keyAndPwdManager.APP_KEY_STATUS,exports.extractModuleInfo=keyAndPwdManager.extractModuleInfo,exports.getRandomNum=keyAndPwdManager.getRandomNum,exports.getTypeBuyCmd=keyAndPwdManager.getTypeBuyCmd,exports.handleNewAppKey=keyAndPwdManager.handleNewAppKey,exports.handleOldAppKey=keyAndPwdManager.handleOldAppKey,exports.sendAppKey=keyAndPwdManager.sendAppKey,exports.sendEnableOrVerifyKey=keyAndPwdManager.sendEnableOrVerifyKey,exports.sendOldAppKey=keyAndPwdManager.sendOldAppKey,exports.sendVerifyPwd=keyAndPwdManager.sendVerifyPwd,exports.sendWrite1LevelPwd=keyAndPwdManager.sendWrite1LevelPwd,exports.verify3LevelPassword=keyAndPwdManager.verify3LevelPassword,exports.verifyMacAddrAndKey=keyAndPwdManager.verifyMacAddrAndKey,exports.OTAUpgrade=OtaUpgrade.OTAUpgrade,exports.TelinkApi=TelinkApi.TelinkApi,exports.BLE=Transfer.BLE,exports.Logger=Transfer.Logger,exports.Observer=Transfer.Observer,exports.Transfer=Transfer.Transfer,exports.ab2decimalArr=BleDataProcess.ab2decimalArr,exports.ab2hex=BleDataProcess.ab2hex,exports.arrayBufferToHexArray=BleDataProcess.arrayBufferToHexArray,exports.base64ToHexArray=BleDataProcess.base64ToHexArray,exports.checkSum=BleDataProcess.checkSum,exports.crc16modbus=BleDataProcess.crc16modbus,exports.crcCheckSum=BleDataProcess.crcCheckSum,exports.decimalToHex=BleDataProcess.decimalToHex,exports.decimalToHex0x=BleDataProcess.decimalToHex0x,exports.decimalToTwoByteHexArray=BleDataProcess.decimalToTwoByteHexArray,exports.extractBits=BleDataProcess.extractBits,exports.fromBCD=BleDataProcess.fromBCD,exports.generateCheckSum=BleDataProcess.generateCheckSum,exports.generateCrc16modbusCheck=BleDataProcess.generateCrc16modbusCheck,exports.generateCrcCheckSum=BleDataProcess.generateCrcCheckSum,exports.getParamBaseValue=BleDataProcess.getParamBaseValue,exports.hex2Ascii=BleDataProcess.hex2Ascii,exports.hex2Binary=BleDataProcess.hex2Binary,exports.hex2string=BleDataProcess.hex2string,exports.hexArr2Assic=BleDataProcess.hexArr2Assic,exports.hexArr2ab=BleDataProcess.hexArr2ab,exports.hexArr2string=BleDataProcess.hexArr2string,exports.hexArrayToModuleArrayBuffer=BleDataProcess.hexArrayToModuleArrayBuffer,exports.hexStrAscii=BleDataProcess.hexStrAscii,exports.hexStringToBinary=BleDataProcess.hexStringToBinary,exports.hexToDecimal=BleDataProcess.hexToDecimal,exports.isWithin30Minutes=BleDataProcess.isWithin30Minutes,exports.parseDateTime=BleDataProcess.parseDateTime,exports.sleep=BleDataProcess.sleep,exports.string2hexArr=BleDataProcess.string2hexArr,exports.stringToTwoHexArray=BleDataProcess.stringToTwoHexArray,exports.toBCD=BleDataProcess.toBCD,exports.getData=BleCmdAnalysis.getData,exports.setMTUAsync=BleCmdAnalysis.setMTUAsync,exports.clearPrimaryKey=BleCmdFFAA.clearPrimaryKey,exports.getBluetoothName=BleCmdFFAA.getBluetoothName,exports.getBroadcastDataCmd=BleCmdFFAA.getBroadcastDataCmd,exports.getFFAA03Async=BleCmdFFAA.getFFAA03Async,exports.getFFAA17Async=BleCmdFFAA.getFFAA17Async,exports.getFFAA25Async=BleCmdFFAA.getFFAA25Async,exports.getFFAA26Async=BleCmdFFAA.getFFAA26Async,exports.getFFAA80Async=BleCmdFFAA.getFFAA80Async,exports.getFFAAKeyAsync=BleCmdFFAA.getFFAAKeyAsync,exports.getWiFiIP=BleCmdFFAA.getWiFiIP,exports.resetFactoryData=BleCmdFFAA.resetFactoryData,exports.resetSecondaryKey=BleCmdFFAA.resetSecondaryKey,exports.resolveFFAA25=BleCmdFFAA.resolveFFAA25,exports.resolveFFAA26=BleCmdFFAA.resolveFFAA26,exports.resolveFFAA80=BleCmdFFAA.resolveFFAA80,exports.resolveFFAAKey=BleCmdFFAA.resolveFFAAKey,exports.setBluetoothName=BleCmdFFAA.setBluetoothName,exports.setWiFi=BleCmdFFAA.setWiFi,exports.setWiFiSta=BleCmdFFAA.setWiFiSta,exports.set_PlanCMD_FFAA=BleCmdFFAA.set_PlanCMD_FFAA,exports.set_PlanCMD_FFAA80=BleCmdFFAA.set_PlanCMD_FFAA80,exports.activateAsync=BleCmdDD.activateAsync,exports.enterFactory=BleCmdDD.enterFactory,exports.existFactory=BleCmdDD.existFactory,exports.get3B3CAsync=BleCmdDD.get3B3CAsync,exports.get3B3CInfo=BleCmdDD.get3B3CInfo,exports.getChipTypeAsync=BleCmdDD.getChipTypeAsync,exports.getDD5A0AAsync=BleCmdDD.getDD5A0AAsync,exports.getDD5A0EAsync=BleCmdDD.getDD5A0EAsync,exports.getDD5A17Async=BleCmdDD.getDD5A17Async,exports.getDD5AAllAsync=BleCmdDD.getDD5AAllAsync,exports.getDD5AE0Async=BleCmdDD.getDD5AE0Async,exports.getDD5AE1Async=BleCmdDD.getDD5AE1Async,exports.getDD5AE4Async=BleCmdDD.getDD5AE4Async,exports.getDD5AFAAsync=BleCmdDD.getDD5AFAAsync,exports.getDD5AFBAsync=BleCmdDD.getDD5AFBAsync,exports.getDDA4F0Async=BleCmdDD.getDDA4F0Async,exports.getDDA503Async=BleCmdDD.getDDA503Async,exports.getDDA504Async=BleCmdDD.getDDA504Async,exports.getDDA505Async=BleCmdDD.getDDA505Async,exports.getDDA506Async=BleCmdDD.getDDA506Async,exports.getDDA507Async=BleCmdDD.getDDA507Async,exports.getDDA508Async=BleCmdDD.getDDA508Async,exports.getDDA5DCAsync=BleCmdDD.getDDA5DCAsync,exports.getDDA5FAAsync=BleCmdDD.getDDA5FAAsync,exports.getDDA5OldAsync=BleCmdDD.getDDA5OldAsync,exports.getProtectCountCmd=BleCmdDD.getProtectCountCmd,exports.readExistFactory=BleCmdDD.readExistFactory,exports.resetCapacity=BleCmdDD.resetCapacity,exports.resolve3B3C=BleCmdDD.resolve3B3C,exports.resolveBMSCmd=BleCmdDD.resolveBMSCmd,exports.resolveBaseDD=BleCmdDD.resolveBaseDD,exports.resolveDD5A0A=BleCmdDD.resolveDD5A0A,exports.resolveDDA4F0=BleCmdDD.resolveDDA4F0,exports.resolveDDA500=BleCmdDD.resolveDDA500,exports.resolveDDA503=BleCmdDD.resolveDDA503,exports.resolveDDA504=BleCmdDD.resolveDDA504,exports.resolveDDA505=BleCmdDD.resolveDDA505,exports.resolveDDA506=BleCmdDD.resolveDDA506,exports.resolveDDA508=BleCmdDD.resolveDDA508,exports.resolveDDA5DC=BleCmdDD.resolveDDA5DC,exports.resolveDDA5FA=BleCmdDD.resolveDDA5FA,exports.resolveProtections=BleCmdDD.resolveProtections,exports.sendBMSAsync=BleCmdDD.sendBMSAsync,exports.setDD5AE3sync=BleCmdDD.setDD5AE3sync,exports.setDDA5FAAsync=BleCmdDD.setDDA5FAAsync,exports.setDDA5OldAsync=BleCmdDD.setDDA5OldAsync,exports.set_PlanCMD_3B3C=BleCmdDD.set_PlanCMD_3B3C,exports.set_PlanCMD_DD=BleCmdDD.set_PlanCMD_DD,exports.getSysParamCmd=readAndSetParam.getSysParamCmd,exports.readParamCmd=readAndSetParam.readParamCmd,exports.setCapacityParamCmd=readAndSetParam.setCapacityParamCmd,exports.setParamCmd=readAndSetParam.setParamCmd,exports.setSysParamCmd=readAndSetParam.setSysParamCmd,exports.getBaseInfo=BaseParamProtocol.getBaseInfo,exports.getBaseParams=BaseParamProtocol.getBaseParams,exports.getResistance=BaseParamProtocol.getResistance,exports.getCMDESInfoAsync=BleCmdHVES.getCMDESInfoAsync,exports.getHVESInfoAsync=BleCmdHVES.getHVESInfoAsync,exports.resolveHVESBMUInfo=BleCmdHVES.resolveHVESBMUInfo,exports.resolveHVESBaseInfo=BleCmdHVES.resolveHVESBaseInfo,exports.resolveHVESCalibrationC1Info=BleCmdHVES.resolveHVESCalibrationC1Info,exports.resolveHVESCalibrationC2Info=BleCmdHVES.resolveHVESCalibrationC2Info,exports.resolveHVESCalibrationConfigInfo=BleCmdHVES.resolveHVESCalibrationConfigInfo,exports.resolveHVESCalibrationInfo=BleCmdHVES.resolveHVESCalibrationInfo,exports.resolveHVESCtInfo=BleCmdHVES.resolveHVESCtInfo,exports.resolveHVESDisCtInfo=BleCmdHVES.resolveHVESDisCtInfo,exports.resolveHVESElectrodeHTInfo=BleCmdHVES.resolveHVESElectrodeHTInfo,exports.resolveHVESEtInfo=BleCmdHVES.resolveHVESEtInfo,exports.resolveHVESInsulationLRInfo=BleCmdHVES.resolveHVESInsulationLRInfo,exports.resolveHVESLSocInfo=BleCmdHVES.resolveHVESLSocInfo,exports.resolveHVESMonoVolInfo=BleCmdHVES.resolveHVESMonoVolInfo,exports.resolveHVESOeInfo=BleCmdHVES.resolveHVESOeInfo,exports.resolveHVESOtRisingInfo=BleCmdHVES.resolveHVESOtRisingInfo,exports.resolveHVESOtrInfo=BleCmdHVES.resolveHVESOtrInfo,exports.resolveHVESOvrInfo=BleCmdHVES.resolveHVESOvrInfo,exports.resolveHVESPackInfo=BleCmdHVES.resolveHVESPackInfo,exports.resolveHVESParamsInfo=BleCmdHVES.resolveHVESParamsInfo,exports.resolveHVESSumInfo=BleCmdHVES.resolveHVESSumInfo,exports.resolveHVESSumVolInfo=BleCmdHVES.resolveHVESSumVolInfo,exports.resolveHVESVersionInfo=BleCmdHVES.resolveHVESVersionInfo,exports.HostProtocol=ESHostProtocol.HostProtocol,exports.batteryInfoJson=baseParamsJson.batteryInfoJson,exports.capInfoJson=baseParamsJson.capInfoJson,exports.capVolInfoJson=baseParamsJson.capVolInfoJson,exports.currentInfoJson=baseParamsJson.currentInfoJson,exports.equalizerFunJson=baseParamsJson.equalizerFunJson,exports.funcAndTempFuncJson=baseParamsJson.funcAndTempFuncJson,exports.funcJson=baseParamsJson.funcJson,exports.systemJson=baseParamsJson.systemJson,exports.tempFuncJson=baseParamsJson.tempFuncJson,exports.tempInfoJson=baseParamsJson.tempInfoJson,exports.voltageInfoJson=baseParamsJson.voltageInfoJson;
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var array=require("./core/array.js"),BleApiManager=require("./core/BleApiManager.js"),BleDataProcess=require("./core/BleDataProcess.js"),commonfun=require("./core/commonfun.js"),keyAndPwdManager=require("./core/keyAndPwdManager.js"),mqttServer=require("./core/mqttServer.js"),OtaUpgrade=require("./core/OtaUpgrade.js"),rsaEncrypt=require("./core/rsaEncrypt.js"),tcpServer=require("./core/tcpServer.js"),TelinkApi=require("./core/TelinkApi.js"),Transfer=require("./core/Transfer.js"),BaseParamProtocol=require("./core/BleCmdAnalysis/BaseParamProtocol.js"),BleCmdAnalysis=require("./core/BleCmdAnalysis/BleCmdAnalysis.js"),BleCmdDD=require("./core/BleCmdAnalysis/BleCmdDD.js"),BleCmdDDA4=require("./core/BleCmdAnalysis/BleCmdDDA4.js"),BleCmdFFAA=require("./core/BleCmdAnalysis/BleCmdFFAA.js"),BleCmdHVES=require("./core/BleCmdAnalysis/BleCmdHVES.js"),ESHostProtocol=require("./core/BleCmdAnalysis/ESHostProtocol.js"),readAndSetParam=require("./core/BleCmdAnalysis/readAndSetParam.js"),baseParamsJson=require("./core/dataJson/baseParamsJson.js");exports.chunk=array.chunk,exports.unique=array.unique,exports.checkBluetoothStatus=BleApiManager.checkBluetoothStatus,exports.checkLocationStatus=BleApiManager.checkLocationStatus,exports.connectAsync=BleApiManager.connectAsync,exports.createBLEConnection=BleApiManager.createBLEConnection,exports.disConnect=BleApiManager.disConnect,exports.enhanceDevice=BleApiManager.enhanceDevice,exports.foundScanDevice=BleApiManager.foundScanDevice,exports.getBLEDeviceCharacteristics=BleApiManager.getBLEDeviceCharacteristics,exports.getBLEDeviceServices=BleApiManager.getBLEDeviceServices,exports.getBluetoothAdapterState=BleApiManager.getBluetoothAdapterState,exports.getBluetoothPermission=BleApiManager.getBluetoothPermission,exports.initBle=BleApiManager.initBle,Object.defineProperty(exports,"isInit",{enumerable:!0,get:function(){return BleApiManager.isInit}}),exports.notify=BleApiManager.notify,exports.onBLECharacteristicValueChange=BleApiManager.onBLECharacteristicValueChange,exports.onBLEConnectionStateChange=BleApiManager.onBLEConnectionStateChange,exports.onBleChangedConnectionState=BleApiManager.onBleChangedConnectionState,exports.onBluetoothAdapterStateChange=BleApiManager.onBluetoothAdapterStateChange,exports.onBluetoothDeviceFound=BleApiManager.onBluetoothDeviceFound,exports.onFoundDevice=BleApiManager.onFoundDevice,exports.scanHandle=BleApiManager.scanHandle,exports.startDevicesDiscovery=BleApiManager.startDevicesDiscovery,exports.stopBluetoothDevicesDiscovery=BleApiManager.stopBluetoothDevicesDiscovery,exports.ab2decimalArr=BleDataProcess.ab2decimalArr,exports.ab2hex=BleDataProcess.ab2hex,exports.arrayBufferToHexArray=BleDataProcess.arrayBufferToHexArray,exports.base64ToHexArray=BleDataProcess.base64ToHexArray,exports.checkSum=BleDataProcess.checkSum,exports.crc16modbus=BleDataProcess.crc16modbus,exports.crcCheckSum=BleDataProcess.crcCheckSum,exports.decimalToHex=BleDataProcess.decimalToHex,exports.decimalToHex0x=BleDataProcess.decimalToHex0x,exports.decimalToTwoByteHexArray=BleDataProcess.decimalToTwoByteHexArray,exports.extractBits=BleDataProcess.extractBits,exports.fromBCD=BleDataProcess.fromBCD,exports.generateCheckSum=BleDataProcess.generateCheckSum,exports.generateCrc16modbusCheck=BleDataProcess.generateCrc16modbusCheck,exports.generateCrcCheckSum=BleDataProcess.generateCrcCheckSum,exports.getParamBaseValue=BleDataProcess.getParamBaseValue,exports.hex2Ascii=BleDataProcess.hex2Ascii,exports.hex2Binary=BleDataProcess.hex2Binary,exports.hex2string=BleDataProcess.hex2string,exports.hexArr2Assic=BleDataProcess.hexArr2Assic,exports.hexArr2ab=BleDataProcess.hexArr2ab,exports.hexArr2string=BleDataProcess.hexArr2string,exports.hexArrayToModuleArrayBuffer=BleDataProcess.hexArrayToModuleArrayBuffer,exports.hexStrAscii=BleDataProcess.hexStrAscii,exports.hexStringToBinary=BleDataProcess.hexStringToBinary,exports.hexToDecimal=BleDataProcess.hexToDecimal,exports.isWithin30Minutes=BleDataProcess.isWithin30Minutes,exports.parseDateTime=BleDataProcess.parseDateTime,exports.sleep=BleDataProcess.sleep,exports.string2hexArr=BleDataProcess.string2hexArr,exports.stringToTwoHexArray=BleDataProcess.stringToTwoHexArray,exports.toBCD=BleDataProcess.toBCD,exports.eventBus=commonfun.eventBus,exports.formatTimeHHmm=commonfun.formatTimeHHmm,exports.getOS=commonfun.getOS,exports.getPlatform=commonfun.getPlatform,exports.inArray=commonfun.inArray,exports.isEmpty=commonfun.isEmpty,exports.isNotEmpty=commonfun.isNotEmpty,exports.ALLOWED_MAC_PREFIX=keyAndPwdManager.ALLOWED_MAC_PREFIX,exports.APP_KEY_STATUS=keyAndPwdManager.APP_KEY_STATUS,exports.extractModuleInfo=keyAndPwdManager.extractModuleInfo,exports.getRandomNum=keyAndPwdManager.getRandomNum,exports.getTypeBuyCmd=keyAndPwdManager.getTypeBuyCmd,exports.handleNewAppKey=keyAndPwdManager.handleNewAppKey,exports.handleOldAppKey=keyAndPwdManager.handleOldAppKey,exports.sendAppKey=keyAndPwdManager.sendAppKey,exports.sendEnableOrVerifyKey=keyAndPwdManager.sendEnableOrVerifyKey,exports.sendOldAppKey=keyAndPwdManager.sendOldAppKey,exports.sendVerifyPwd=keyAndPwdManager.sendVerifyPwd,exports.sendWrite1LevelPwd=keyAndPwdManager.sendWrite1LevelPwd,exports.verify3LevelPassword=keyAndPwdManager.verify3LevelPassword,exports.verifyMacAddrAndKey=keyAndPwdManager.verifyMacAddrAndKey,exports.MqttServer=mqttServer.MqttServer,exports.OTAUpgrade=OtaUpgrade.OTAUpgrade,exports.decrypt=rsaEncrypt.decrypt,exports.decrypt2=rsaEncrypt.decrypt2,exports.decryptUsername=rsaEncrypt.decryptUsername,exports.encrypt=rsaEncrypt.encrypt,exports.tcpSend=tcpServer.tcpSend,exports.tcpServer=tcpServer.tcpServer,exports.TelinkApi=TelinkApi.TelinkApi,exports.BLE=Transfer.BLE,exports.Logger=Transfer.Logger,exports.Observer=Transfer.Observer,exports.Transfer=Transfer.Transfer,exports.getBaseInfo=BaseParamProtocol.getBaseInfo,exports.getBaseParams=BaseParamProtocol.getBaseParams,exports.getResistance=BaseParamProtocol.getResistance,exports.getData=BleCmdAnalysis.getData,exports.setMTUAsync=BleCmdAnalysis.setMTUAsync,exports.activateAsync=BleCmdDD.activateAsync,exports.enterFactory=BleCmdDD.enterFactory,exports.existFactory=BleCmdDD.existFactory,exports.get3B3CAsync=BleCmdDD.get3B3CAsync,exports.get3B3CInfo=BleCmdDD.get3B3CInfo,exports.getChipTypeAsync=BleCmdDD.getChipTypeAsync,exports.getDD5A0AAsync=BleCmdDD.getDD5A0AAsync,exports.getDD5A0EAsync=BleCmdDD.getDD5A0EAsync,exports.getDD5A17Async=BleCmdDD.getDD5A17Async,exports.getDD5AAllAsync=BleCmdDD.getDD5AAllAsync,exports.getDD5AE0Async=BleCmdDD.getDD5AE0Async,exports.getDD5AE1Async=BleCmdDD.getDD5AE1Async,exports.getDD5AE4Async=BleCmdDD.getDD5AE4Async,exports.getDD5AFAAsync=BleCmdDD.getDD5AFAAsync,exports.getDD5AFBAsync=BleCmdDD.getDD5AFBAsync,exports.getDDA4F0Async=BleCmdDD.getDDA4F0Async,exports.getDDA503Async=BleCmdDD.getDDA503Async,exports.getDDA504Async=BleCmdDD.getDDA504Async,exports.getDDA505Async=BleCmdDD.getDDA505Async,exports.getDDA506Async=BleCmdDD.getDDA506Async,exports.getDDA507Async=BleCmdDD.getDDA507Async,exports.getDDA508Async=BleCmdDD.getDDA508Async,exports.getDDA5DCAsync=BleCmdDD.getDDA5DCAsync,exports.getDDA5FAAsync=BleCmdDD.getDDA5FAAsync,exports.getDDA5OldAsync=BleCmdDD.getDDA5OldAsync,exports.getProtectCountCmd=BleCmdDD.getProtectCountCmd,exports.readExistFactory=BleCmdDD.readExistFactory,exports.resetCapacity=BleCmdDD.resetCapacity,exports.resolve3B3C=BleCmdDD.resolve3B3C,exports.resolveBMSCmd=BleCmdDD.resolveBMSCmd,exports.resolveBaseDD=BleCmdDD.resolveBaseDD,exports.resolveDD5A0A=BleCmdDD.resolveDD5A0A,exports.resolveDDA4F0=BleCmdDD.resolveDDA4F0,exports.resolveDDA500=BleCmdDD.resolveDDA500,exports.resolveDDA503=BleCmdDD.resolveDDA503,exports.resolveDDA504=BleCmdDD.resolveDDA504,exports.resolveDDA505=BleCmdDD.resolveDDA505,exports.resolveDDA506=BleCmdDD.resolveDDA506,exports.resolveDDA508=BleCmdDD.resolveDDA508,exports.resolveDDA5DC=BleCmdDD.resolveDDA5DC,exports.resolveDDA5FA=BleCmdDD.resolveDDA5FA,exports.resolveProtections=BleCmdDD.resolveProtections,exports.sendBMSAsync=BleCmdDD.sendBMSAsync,exports.setDD5AE3sync=BleCmdDD.setDD5AE3sync,exports.setDDA5FAAsync=BleCmdDD.setDDA5FAAsync,exports.setDDA5OldAsync=BleCmdDD.setDDA5OldAsync,exports.set_PlanCMD_3B3C=BleCmdDD.set_PlanCMD_3B3C,exports.set_PlanCMD_DD=BleCmdDD.set_PlanCMD_DD,exports.getDDA420Async=BleCmdDDA4.getDDA420Async,exports.getDDA421Async=BleCmdDDA4.getDDA421Async,exports.getDDA422Async=BleCmdDDA4.getDDA422Async,exports.getDDA423Async=BleCmdDDA4.getDDA423Async,exports.getDDA425Async=BleCmdDDA4.getDDA425Async,exports.getDDA426Async=BleCmdDDA4.getDDA426Async,exports.getDDA427Async=BleCmdDDA4.getDDA427Async,exports.getDDA429Async=BleCmdDDA4.getDDA429Async,exports.resolveDDA420=BleCmdDDA4.resolveDDA420,exports.resolveDDA421=BleCmdDDA4.resolveDDA421,exports.resolveDDA422=BleCmdDDA4.resolveDDA422,exports.resolveDDA423=BleCmdDDA4.resolveDDA423,exports.resolveDDA425=BleCmdDDA4.resolveDDA425,exports.resolveDDA426=BleCmdDDA4.resolveDDA426,exports.resolveDDA427=BleCmdDDA4.resolveDDA427,exports.resolveDDA429=BleCmdDDA4.resolveDDA429,exports.clearPrimaryKey=BleCmdFFAA.clearPrimaryKey,exports.getBluetoothName=BleCmdFFAA.getBluetoothName,exports.getBroadcastDataCmd=BleCmdFFAA.getBroadcastDataCmd,exports.getFFAA03Async=BleCmdFFAA.getFFAA03Async,exports.getFFAA17Async=BleCmdFFAA.getFFAA17Async,exports.getFFAA25Async=BleCmdFFAA.getFFAA25Async,exports.getFFAA26Async=BleCmdFFAA.getFFAA26Async,exports.getFFAA80Async=BleCmdFFAA.getFFAA80Async,exports.getFFAAKeyAsync=BleCmdFFAA.getFFAAKeyAsync,exports.getWiFiIP=BleCmdFFAA.getWiFiIP,exports.resetFactoryData=BleCmdFFAA.resetFactoryData,exports.resetSecondaryKey=BleCmdFFAA.resetSecondaryKey,exports.resolveFFAA25=BleCmdFFAA.resolveFFAA25,exports.resolveFFAA26=BleCmdFFAA.resolveFFAA26,exports.resolveFFAA80=BleCmdFFAA.resolveFFAA80,exports.resolveFFAAKey=BleCmdFFAA.resolveFFAAKey,exports.setBluetoothName=BleCmdFFAA.setBluetoothName,exports.setWiFi=BleCmdFFAA.setWiFi,exports.setWiFiSta=BleCmdFFAA.setWiFiSta,exports.set_PlanCMD_FFAA=BleCmdFFAA.set_PlanCMD_FFAA,exports.set_PlanCMD_FFAA80=BleCmdFFAA.set_PlanCMD_FFAA80,exports.getCMDESInfoAsync=BleCmdHVES.getCMDESInfoAsync,exports.getHVESInfoAsync=BleCmdHVES.getHVESInfoAsync,exports.resolveHVESBMUInfo=BleCmdHVES.resolveHVESBMUInfo,exports.resolveHVESBaseInfo=BleCmdHVES.resolveHVESBaseInfo,exports.resolveHVESCalibrationC1Info=BleCmdHVES.resolveHVESCalibrationC1Info,exports.resolveHVESCalibrationC2Info=BleCmdHVES.resolveHVESCalibrationC2Info,exports.resolveHVESCalibrationConfigInfo=BleCmdHVES.resolveHVESCalibrationConfigInfo,exports.resolveHVESCalibrationInfo=BleCmdHVES.resolveHVESCalibrationInfo,exports.resolveHVESCtInfo=BleCmdHVES.resolveHVESCtInfo,exports.resolveHVESDisCtInfo=BleCmdHVES.resolveHVESDisCtInfo,exports.resolveHVESElectrodeHTInfo=BleCmdHVES.resolveHVESElectrodeHTInfo,exports.resolveHVESEtInfo=BleCmdHVES.resolveHVESEtInfo,exports.resolveHVESInsulationLRInfo=BleCmdHVES.resolveHVESInsulationLRInfo,exports.resolveHVESLSocInfo=BleCmdHVES.resolveHVESLSocInfo,exports.resolveHVESMonoVolInfo=BleCmdHVES.resolveHVESMonoVolInfo,exports.resolveHVESOeInfo=BleCmdHVES.resolveHVESOeInfo,exports.resolveHVESOtRisingInfo=BleCmdHVES.resolveHVESOtRisingInfo,exports.resolveHVESOtrInfo=BleCmdHVES.resolveHVESOtrInfo,exports.resolveHVESOvrInfo=BleCmdHVES.resolveHVESOvrInfo,exports.resolveHVESPackInfo=BleCmdHVES.resolveHVESPackInfo,exports.resolveHVESParamsInfo=BleCmdHVES.resolveHVESParamsInfo,exports.resolveHVESSumInfo=BleCmdHVES.resolveHVESSumInfo,exports.resolveHVESSumVolInfo=BleCmdHVES.resolveHVESSumVolInfo,exports.resolveHVESVersionInfo=BleCmdHVES.resolveHVESVersionInfo,exports.HostProtocol=ESHostProtocol.HostProtocol,exports.controlSwitch=readAndSetParam.controlSwitch,exports.getE1Cmd=readAndSetParam.getE1Cmd,exports.getSysParamCmd=readAndSetParam.getSysParamCmd,exports.readParamCmd=readAndSetParam.readParamCmd,exports.setCapacityParamCmd=readAndSetParam.setCapacityParamCmd,exports.setParamCmd=readAndSetParam.setParamCmd,exports.setSysParamCmd=readAndSetParam.setSysParamCmd,exports.batteryInfoJson=baseParamsJson.batteryInfoJson,exports.capInfoJson=baseParamsJson.capInfoJson,exports.capVolInfoJson=baseParamsJson.capVolInfoJson,exports.currentInfoJson=baseParamsJson.currentInfoJson,exports.equalizerFunJson=baseParamsJson.equalizerFunJson,exports.funcAndTempFuncJson=baseParamsJson.funcAndTempFuncJson,exports.funcJson=baseParamsJson.funcJson,exports.systemJson=baseParamsJson.systemJson,exports.tempFuncJson=baseParamsJson.tempFuncJson,exports.tempInfoJson=baseParamsJson.tempInfoJson,exports.voltageInfoJson=baseParamsJson.voltageInfoJson;
|