@jiabaida/tools 1.1.0 → 1.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var vue=require("vue"),BleDataProcess=require("./BleDataProcess.js"),commonfun=require("./commonfun.js"),tcpServer=require("./tcpServer.js"),mqttServer=require("./mqttServer.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),characteristic.connected||(mqttServer.mqttServer.closeMqttByDeviceId(characteristic.deviceId),tcpServer.tcpServer.closeTcpSocket(characteristic.deviceId))})},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},10,300,"获取蓝牙服务"),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},10,300,"获取蓝牙特征值"),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 new Promise(resolve=>setTimeout(resolve,800)),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"],autoZoom:!1,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"),tcpServer=require("./tcpServer.js"),mqttServer=require("./mqttServer.js");const serviceId="0000FF00-0000-1000-8000-00805F9B34FB",{isAndroid:isAndroid,isIOS:isIOS}=commonfun.getOS(),bluetoothAdapterState=vue.ref({available:!1,discovering:!1}),platform=commonfun.getPlatform();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),characteristic.connected||("mp-weixin"===platform?tcpServer.tcpServer.closeTcpSocket(characteristic.deviceId):mqttServer.mqttServer.closeMqttByDeviceId(characteristic.deviceId))})},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},10,300,"获取蓝牙服务"),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},10,300,"获取蓝牙特征值"),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})}),bluetoothScanHandle=(retult,historyConnectedList=[],connectFn=device=>{},failScanFn=err=>{})=>{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)}},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.bluetoothScanHandle=bluetoothScanHandle,exports.checkBluetoothStatus=checkBluetoothStatus,exports.checkLocationStatus=checkLocationStatus,exports.connectAsync=async(deviceId,timeout=1e4)=>new Promise(async(resolve,reject)=>{try{await createBLEConnection(deviceId,timeout),await new Promise(resolve=>setTimeout(resolve,800)),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"],autoZoom:!1,success:async({result:result})=>{bluetoothScanHandle(result,historyConnectedList,connectFn,failScanFn)},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 BleDataProcess=require("../BleDataProcess.js"),commonfun=require("../commonfun.js"),mqttServer=require("../mqttServer.js");const BLE_COMMAND_QUEUE=new Map,BLE_COMMAND_RUNNING=new Set,runNextBleCommand=async queueKey=>{if(BLE_COMMAND_RUNNING.has(queueKey))return;const queue=BLE_COMMAND_QUEUE.get(queueKey)||[];if(0===queue.length)return void BLE_COMMAND_QUEUE.delete(queueKey);BLE_COMMAND_RUNNING.add(queueKey);const currentTask=queue[0];try{const result=await currentTask.task();currentTask.resolve(result)}catch(error){currentTask.reject(error)}finally{const currentQueue=BLE_COMMAND_QUEUE.get(queueKey)||[];currentQueue.shift(),BLE_COMMAND_RUNNING.delete(queueKey),0===currentQueue.length?BLE_COMMAND_QUEUE.delete(queueKey):runNextBleCommand(queueKey)}};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((deviceId,task)=>{const queueKey=deviceId||"__default__";return new Promise((resolve,reject)=>{const queue=BLE_COMMAND_QUEUE.get(queueKey)||[];queue.push({task:task,resolve:resolve,reject:reject}),BLE_COMMAND_QUEUE.set(queueKey,queue),runNextBleCommand(queueKey)})})(deviceId,()=>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);if(console.log("数据包验证结果:",{verified:verified}),verified){responsed=!0,cleanup();const value=[...pkg].map(o=>`00${o.toString(16)}`.slice(-2)).join(""),cmdCode=mqttServer.mqttServer.currentCommand;value&&cmdCode&&(0===mqttServer.mqttServer.setPassthroughType&&mqttServer.mqttServer.publishPassthroughHandle({value:value,cmdCode:cmdCode},deviceId),mqttServer.mqttServer.setPassthroughType=0),resolve([...pkg])}else 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"),mqttServer=require("../mqttServer.js");const BLE_COMMAND_QUEUE=new Map,BLE_COMMAND_RUNNING=new Set,platform=commonfun.getPlatform(),runNextBleCommand=async queueKey=>{if(BLE_COMMAND_RUNNING.has(queueKey))return;const queue=BLE_COMMAND_QUEUE.get(queueKey)||[];if(0===queue.length)return void BLE_COMMAND_QUEUE.delete(queueKey);BLE_COMMAND_RUNNING.add(queueKey);const currentTask=queue[0];try{const result=await currentTask.task();currentTask.resolve(result)}catch(error){currentTask.reject(error)}finally{const currentQueue=BLE_COMMAND_QUEUE.get(queueKey)||[];currentQueue.shift(),BLE_COMMAND_RUNNING.delete(queueKey),0===currentQueue.length?BLE_COMMAND_QUEUE.delete(queueKey):runNextBleCommand(queueKey)}};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((deviceId,task)=>{const queueKey=deviceId||"__default__";return new Promise((resolve,reject)=>{const queue=BLE_COMMAND_QUEUE.get(queueKey)||[];queue.push({task:task,resolve:resolve,reject:reject}),BLE_COMMAND_QUEUE.set(queueKey,queue),runNextBleCommand(queueKey)})})(deviceId,()=>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);if(console.log("数据包验证结果:",{verified:verified}),verified){if(responsed=!0,cleanup(),"mp-weixin"!==platform){const value=[...pkg].map(o=>`00${o.toString(16)}`.slice(-2)).join(""),cmdCode=mqttServer.mqttServer.currentCommand;value&&cmdCode&&(0===mqttServer.mqttServer.setPassthroughType&&mqttServer.mqttServer.publishPassthroughHandle({value:value,cmdCode:cmdCode},deviceId),mqttServer.mqttServer.setPassthroughType=0)}resolve([...pkg])}else 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"),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;){if(content.length<2){console.warn("Content too short to parse, remaining:",content);break}const len=Math.min(content[1]+2,content.length),[v1,v2,...v]=content.splice(0,len);if(v.length===v2){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))}else console.warn(`Data length mismatch for type ${v1}: expected ${v2}, got ${v.length}`)}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,eqCurr: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;try{if(!deviceId)throw new Error("deviceId required");const _ffaa_80=await BleCmdFFAA.getFFAA80Async(deviceId,"AT^VERSION?");console.warn("Report-3B3C _ffaa_80 ",{_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,reportData.bmsVersion=_3b3c?.sofewareV;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.decimalToHex0x(_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;){if(content.length<2){console.warn("Content too short to parse, remaining:",content);break}const len=Math.min(content[1]+2,content.length),[v1,v2,...v]=content.splice(0,len);if(v.length===v2){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))}else console.warn(`Data length mismatch for type ${v1}: expected ${v2}, got ${v.length}`)}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;try{if(!deviceId)throw new Error("deviceId required");const _ffaa_80=await BleCmdFFAA.getFFAA80Async(deviceId,"AT^VERSION?");console.warn("Report-3B3C _ffaa_80 ",{_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,reportData.bmsVersion=_3b3c?.sofewareV;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.decimalToHex0x(_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 +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.decimalToHex0x(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.warn("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={paramNo:1,oldParamNo:"0x11",values:.8*values,paramLength:2},full={paramNo:112,oldParamNo:"0x10",values:values,paramLength:2},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))},handleCapacityParam=async(paramObj,lowParamNo,highParamNo)=>{const value=Math.round(Number(paramObj.values)/paramInfo.divisor);console.log(`容量参数value (paramNo ${lowParamNo}):`,value);const lowValue=65535&value,highValue=value>>16&65535,lowBytes=BleDataProcess.decimalToTwoByteHexArray(lowValue),lowAddress=BleDataProcess.decimalToTwoByteHexArray(lowParamNo),hexLength=BleDataProcess.decimalToHex(1),lowHex=await handleSet(async()=>await BleCmdDD.setDDA5FAAsync(deviceId,lowAddress,hexLength,lowBytes)),highBytes=BleDataProcess.decimalToTwoByteHexArray(highValue),highAddress=BleDataProcess.decimalToTwoByteHexArray(highParamNo),highHex=await handleSet(async()=>await BleCmdDD.setDDA5FAAsync(deviceId,highAddress,hexLength,highBytes));return lowHex&&highHex};try{let paramInfoHex;await BleCmdDD.enterFactory(deviceId),paramInfoHex=chipType?await handleCapacityParam(paramInfo,0,155):await handleParam(paramInfo);await handleParam(circular);if(chipType){await handleCapacityParam(full,112,156)}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=Number(paramInfo?.paramValue||paramInfo.newValue)/Number(paramInfo?.divisor||1);console.log("value: ",value),paramInfo.isTemp&&(value=2731+10*Number(paramInfo.newValue)),value=Math.round(value);let valuesHexs=[];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
+ "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.decimalToHex0x(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.warn("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={paramNo:1,oldParamNo:"0x11",values:.8*values,paramLength:2},full={paramNo:112,oldParamNo:"0x10",values:values,paramLength:2},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))},handleCapacityParam=async(paramObj,lowParamNo,highParamNo)=>{const value=Math.round(Number(paramObj.values)/paramInfo.divisor);console.log(`容量参数value (paramNo ${lowParamNo}):`,value);const lowValue=65535&value,highValue=value>>16&65535,lowBytes=BleDataProcess.decimalToTwoByteHexArray(lowValue),lowAddress=BleDataProcess.decimalToTwoByteHexArray(lowParamNo),hexLength=BleDataProcess.decimalToHex(1),lowHex=await handleSet(async()=>await BleCmdDD.setDDA5FAAsync(deviceId,lowAddress,hexLength,lowBytes)),highBytes=BleDataProcess.decimalToTwoByteHexArray(highValue),highAddress=BleDataProcess.decimalToTwoByteHexArray(highParamNo),highHex=await handleSet(async()=>await BleCmdDD.setDDA5FAAsync(deviceId,highAddress,hexLength,highBytes));return lowHex&&highHex};try{let paramInfoHex;await BleCmdDD.enterFactory(deviceId),paramInfoHex=chipType?await handleCapacityParam(paramInfo,0,155):await handleParam(paramInfo);const circularValue=Math.round(Number(circular.values)/paramInfo.divisor);if(0===(circularValue>>16&65535)){await handleParam(circular)}else{await handleParam({...circular,values:655.35})}if(chipType){await handleCapacityParam(full,112,156)}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=Number(paramInfo?.paramValue||paramInfo.newValue)/Number(paramInfo?.divisor||1);console.log("value: ",value),paramInfo.isTemp&&(value=2731+10*Number(paramInfo.newValue)),value=Math.round(value);let valuesHexs=[];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:()=>{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(this.delay),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(this.delay),Transfer.BLE.transferFirmwareFileCmd(this.deviceId,index.concat(pkg),!1,this.fail.bind(this)),console.log("[OTA]",`S50-${this.finishedTimes}/${this.totalTimes}`)}this.onProgress&&this.onProgress({type:"upgrade",percent:Math.floor(100*this.finishedTimes/this.totalTimes)})}async startOTA(){Transfer.BLE.writeATCmd(this.otaStart,this.deviceId,this.fail.bind(this))}fail(msg){this.succeed=!1,this.onError&&this.onError(msg)}sleep(n=50){return new Promise(r=>setTimeout(()=>r(!0),n))}}exports.OTAUpgrade=OTAUpgrade,exports.default=OTAUpgrade;
1
+ "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(){if(this.finishedTimes+1>this.totalTimes+1){const pkg=[0];await Transfer.BLE.sendDelay(this.delay),Transfer.BLE.transferFirmwareFileCmd(this.deviceId,pkg,!0,this.fail.bind(this)),console.log("[OTA]","=== Send 51 ===",this.finishedTimes,this.totalTimes,pkg)}else if(0===this.finishedTimes){const emptyPkg=[0,0];console.log("[OTA]","=== Send empty package first ==="),await Transfer.BLE.sendDelay(this.delay),Transfer.BLE.transferFirmwareFileCmd(this.deviceId,emptyPkg,!1,this.fail.bind(this))}else{const dataIndex=this.finishedTimes-1,pkg=this.fileHexArray.slice(dataIndex*max,(dataIndex+1)*max),index=Transfer.Transfer.decimalToTwoByteHexArray(this.finishedTimes);console.log("[OTA]",`S50-${this.finishedTimes}/${this.totalTimes}`),await Transfer.BLE.sendDelay(this.delay),Transfer.BLE.transferFirmwareFileCmd(this.deviceId,index.concat(pkg),!1,this.fail.bind(this))}this.onProgress&&this.onProgress({type:"upgrade",percent:Math.floor(100*this.finishedTimes/this.totalTimes)})}async startOTA(){Transfer.BLE.writeATCmd(this.otaStart,this.deviceId,this.fail.bind(this))}fail(msg){this.succeed=!1,this.onError&&this.onError(msg)}sleep(n=50){return new Promise(r=>setTimeout(()=>r(!0),n))}}exports.OTAUpgrade=OTAUpgrade,exports.default=OTAUpgrade;
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var 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);class MqttServer{constructor(options={}){const{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}=options;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,this.setPassthroughType=1,this.currentCommand="",this.verify3LevelPasswordFn=async(deviceObj,ciphertext)=>{}}initData(options={}){const{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,verify3LevelPasswordFn:verify3LevelPasswordFn=async()=>{}}=options;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,this.verify3LevelPasswordFn=verify3LevelPasswordFn}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,deviceObj),this.publishInOrder(client,deviceObj).then(()=>this.subscribeInOrder(client))}storeMqttClient(client,deviceObj){this.mqttClient[`${client.options.deviceId}_mqtt`]=client,this.mqttClient[`${client.options.deviceId}_mqtt`].deviceObj=deviceObj,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 deviceObj=this.mqttClient[`${client.options.deviceId}_mqtt`]?.deviceObj||{};await this.verify3LevelPasswordFn(deviceObj,deviceObj.macAddr);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()&&"50"!==resultArray[1]?.toUpperCase()||(this.currentCommand=resultArray.slice(0,4).map(o=>`0x${o}`));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):(console.log("resultArray",resultArray),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`];console.log("closeMqttByDeviceId",this.mqttClient,client),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})}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&&(console.log("publishHandle",client,msg,this.publishObj),client.publish(`/${this.publishObj.productKey}/${this.publishObj.clientId}/plat/passthrough/reply`,msg,()=>{console.log("发布回复主题完成",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;this.setPassthroughType=1,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("")),console.log("res",res);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,this.mqttCode),code.toUpperCase()==this.mqttCode.toUpperCase()&&this.publishHandle(res?.dataStr),this.timer=setTimeout(()=>{this.mqttPublish=!1,this.$store?.commit("setMqttPublish",!1)},3e4)}}const mqttServer=new MqttServer;exports.MqttServer=MqttServer,exports.mqttServer=mqttServer;
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);class MqttServer{constructor(options={}){const{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}=options;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,this.setPassthroughType=1,this.currentCommand="",this.verify3LevelPasswordFn=async(deviceObj,ciphertext)=>{}}initData(options={}){const{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,verify3LevelPasswordFn:verify3LevelPasswordFn=async()=>{}}=options;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,this.verify3LevelPasswordFn=verify3LevelPasswordFn}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,deviceObj),this.publishInOrder(client,deviceObj).then(()=>this.subscribeInOrder(client))}storeMqttClient(client,deviceObj){this.mqttClient[`${client.options.deviceId}_mqtt`]=client,this.mqttClient[`${client.options.deviceId}_mqtt`].deviceObj=deviceObj,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 deviceObj=this.mqttClient[`${client.options.deviceId}_mqtt`]?.deviceObj||{};await this.verify3LevelPasswordFn(deviceObj,deviceObj.macAddr);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()&&"50"!==resultArray[1]?.toUpperCase()||(this.currentCommand=resultArray.slice(0,4).map(o=>`0x${o}`));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):(console.log("resultArray",resultArray),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?.setMqttPublish(!1),uni.removeStorageSync&&uni.removeStorageSync(`${deviceId}_mqttPublish`))}catch(error){console.error(error)}}closeMqttByDeviceId(deviceId){const client=this.mqttClient[`${deviceId}_mqtt`];console.log("closeMqttByDeviceId",this.mqttClient,client),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})}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&&(console.log("publishHandle",client,msg,this.publishObj),client.publish(`/${this.publishObj.productKey}/${this.publishObj.clientId}/plat/passthrough/reply`,msg,()=>{console.log("发布回复主题完成",msg)})),this.publishObj.isLast&&(await BleDataProcess.sleep(300),this.mqttPublish=!1,this.$store?.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?.setMqttPublish(!0),this.mqttCode=values[2];let res=null;this.setPassthroughType=1,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("")),console.log("res",res);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,this.mqttCode),code.toUpperCase()==this.mqttCode.toUpperCase()&&this.publishHandle(res?.dataStr),this.timer=setTimeout(()=>{this.mqttPublish=!1,this.$store?.setMqttPublish(!1)},3e4)}}const mqttServer=new MqttServer;exports.MqttServer=MqttServer,exports.mqttServer=mqttServer;
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"),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.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;
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.bluetoothScanHandle=BleApiManager.bluetoothScanHandle,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.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;
@@ -1 +1 @@
1
- import{ref}from"vue";import{ab2decimalArr,hexToDecimal}from"./BleDataProcess.js";import{getOS,eventBus}from"./commonfun.js";import{tcpServer}from"./tcpServer.js";import{mqttServer}from"./mqttServer.js";const serviceId="0000FF00-0000-1000-8000-00805F9B34FB",{isAndroid:isAndroid,isIOS:isIOS}=getOS(),bluetoothAdapterState=ref({available:!1,discovering:!1});var 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?hexToDecimal(socHex):"",productType=advHex.slice(18,20);let protocolVersion=advHex.slice(20,22);if(protocolVersion){const v=hexToDecimal(protocolVersion);macAddr.startsWith("A5:C2")&&v<=35&&(protocolVersion="01")}const appkeyStatus=advHex.slice(22,24),tempVoltage=advHex.slice(24,26),voltage=tempVoltage||0==tempVoltage?hexToDecimal(tempVoltage):"",tempCurrent=advHex.slice(26,28),current=tempCurrent||0==tempCurrent?hexToDecimal(tempCurrent):"",broadcastLen=advHex.length/2,isNewAppKey=advHex.length>=24;device={...device,macAddr:macAddr,moduleType:moduleType,soc:soc,productType:productType,advHex:advHex,protocolVersion:protocolVersion,appkeyStatus:appkeyStatus,broadcastLen:broadcastLen,isNewAppKey:isNewAppKey,voltage:voltage,current:current}}return device},checkBluetoothStatus=async(successCallback=()=>{})=>new Promise((resolve,reject)=>{uni.openBluetoothAdapter({success:async res=>{successCallback&&successCallback(res),resolve(res)},fail:err=>{console.log("openBluetoothAdapter fail4-----",err),err&&3==err?.errno&&reject({code:105,message:"请授权微信位置信息和蓝牙权限"}),err&&103==err?.errno&&reject({code:106,message:"请授权蓝牙和位置权限,并重启小程序"}),reject({code:102,message:"当前手机蓝牙不可用,请检查手机蓝牙状态"})}})}),checkLocationStatus=async(successCallback=()=>{})=>{const timeoutPromise=new Promise((resolve,reject)=>{setTimeout(()=>{reject({code:101,message:"网络信号差或连接异常,请检查网络情况"})},1e4)}),locationPromise=new Promise((resolve,reject)=>{uni.getLocation({type:"wgs84",success:res=>{console.log("位置信息-----------",res),resolve(res)},fail:err=>{console.log("位置信息err",err),err&&103==err?.errno&&reject({code:103,message:"请授权小程序位置信息权限, 并重启小程序。"}),err&&2==err?.errCode&&reject({code:101,message:"网络信号差或连接异常,请检查网络情况"}),reject({code:104,message:"请授权微信位置信息权限, 并重启小程序。"})}})});return Promise.race([locationPromise,timeoutPromise]).then(async res=>await checkBluetoothStatus(successCallback))},getBluetoothPermission=async(successCallback=()=>{})=>{try{return isAndroid?await checkLocationStatus(successCallback):await checkBluetoothStatus(successCallback)}catch(error){throw console.error("初始化蓝牙失败:",error),error}},initBle=async()=>await getBluetoothPermission(()=>{console.log("初始化蓝牙成功initBluetoothSuccessCb1");try{if(isInit)return;onBluetoothDeviceFound(),onBLECharacteristicValueChange(),onBLEConnectionStateChange(),onBluetoothAdapterStateChange(),isInit=!0}catch(error){throw error}}),getBluetoothAdapterState=async()=>new Promise((resolve,reject)=>{uni.getBluetoothAdapterState({success:res=>{console.log("getBluetoothAdapterState success",res),resolve(res)},fail:err=>{console.log("getBluetoothAdapterState fail",err),reject(err)}})}),startDevicesDiscovery=async(allowDuplicatesKey=!0)=>new Promise((resolve,reject)=>{bluetoothAdapterState.value.discovering?reject(new Error("蓝牙设备搜索已在进行中")):uni.startBluetoothDevicesDiscovery({services:[serviceId],allowDuplicatesKey:allowDuplicatesKey,success:async res=>{console.log("广播设备 success",res),resolve(res)},fail:err=>{console.log("广播设备 fail",err),reject(err)}})}),stopBluetoothDevicesDiscovery=async()=>(bluetoothAdapterState.value={available:bluetoothAdapterState.value.available,discovering:!1},new Promise((resolve,reject)=>{uni.stopBluetoothDevicesDiscovery({success:res=>{console.log("停止广播设备 success",res),resolve(res)},fail:err=>{console.log("停止广播设备 fail",err),reject(err)},complete:res=>{console.log("停止广播设备 取消订阅"),eventBus.off("setBluetoothDeviceFound")}})})),onBluetoothDeviceFound=async()=>{uni.onBluetoothDeviceFound(characteristic=>{console.log("setBluetoothDeviceFound",characteristic);const device=enhanceDevice(characteristic.devices[0]);device&&eventBus.emit("setBluetoothDeviceFound",device)})},onFoundDevice=callback=>{eventBus.on("setBluetoothDeviceFound",callback)},onBluetoothAdapterStateChange=async()=>{uni.onBluetoothAdapterStateChange(res=>{console.log("onBluetoothAdapterStateChange监听蓝牙适配器变化",res),bluetoothAdapterState.value=res})},onBLECharacteristicValueChange=async()=>{uni.onBLECharacteristicValueChange(characteristic=>{const decimalArr=ab2decimalArr(characteristic.value);console.warn("decimalArr: 监听到的回复-------------------",decimalArr),eventBus.emit("setBleChangedCharacteristicValue",characteristic)})},onBLEConnectionStateChange=async()=>{uni.onBLEConnectionStateChange(characteristic=>{console.log("onBLEConnectionStateChange",characteristic),eventBus.emit("setBleChangedConnectionState",characteristic),characteristic.connected||(mqttServer.closeMqttByDeviceId(characteristic.deviceId),tcpServer.closeTcpSocket(characteristic.deviceId))})},onBleChangedConnectionState=callback=>{eventBus.on("setBleChangedConnectionState",callback)},createBLEConnection=async(deviceId,timeout=1e4)=>new Promise((resolve,reject)=>{console.log(deviceId,"点击的设备信息"),uni.createBLEConnection({deviceId:deviceId,timeout:timeout,success:res=>{console.log(res,"连接成功"),resolve(!0)},fail:err=>{console.log(err,"Connection"),-1==(err.code||err.errCode)?resolve(!0):reject(err)}})}),withRetry=async(asyncOperation,maxRetries=20,retryInterval=100,type)=>new Promise((resolve,reject)=>{let retryCount=0;const attempt=async()=>{try{const result=await asyncOperation();resolve(result)}catch(error){if(retryCount>=maxRetries)return void reject(new Error(`${type}失败,${error.message} (已重试${maxRetries}次)`));retryCount++,console.warn(`${type}失败,第${retryCount}次重试:`,error.message),setTimeout(attempt,retryInterval)}};attempt()}),getBLEDeviceServices=deviceId=>withRetry(async()=>{const res=await new Promise((resolve,reject)=>{uni.getBLEDeviceServices({deviceId:deviceId,success:resolve,fail:reject})});if(console.log("获取蓝牙服务成功:",res),0===res.services.length)throw new Error("未找到蓝牙服务");return await getBLEDeviceCharacteristics(deviceId),res.services},10,300,"获取蓝牙服务"),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},10,300,"获取蓝牙特征值"),notify=async deviceId=>new Promise((resolve,reject)=>{uni.notifyBLECharacteristicValueChange({deviceId:deviceId,serviceId:serviceId,characteristicId:"0000FF01-0000-1000-8000-00805F9B34FB",state:!0,success:res=>{console.log("订阅===========",res),resolve(res)},fail:reject})}),disConnect=deviceId=>new Promise((resolve,reject)=>{uni.closeBLEConnection({deviceId:deviceId,success:res=>{resolve(res),console.log(res,"断开连接成功")},fail:err=>{reject(err),console.log(err,"err 断开连接")}})}),connectAsync=async(deviceId,timeout=1e4)=>new Promise(async(resolve,reject)=>{try{await createBLEConnection(deviceId,timeout),await new Promise(resolve=>setTimeout(resolve,800)),await getBLEDeviceServices(deviceId),await notify(deviceId),resolve(!0)}catch(error){console.log("error: ",error),reject(error)}}),scanHandle=(historyConnectedList=[],connectFn=device=>{},failScanFn=err=>{})=>{uni.scanCode({scanType:["barCode","qrCode"],autoZoom:!1,success:async({result:result})=>{console.log("扫描内容: "+result);let searchKey=result;try{const formatMacAddress=mac=>mac.replace(/(.{2})/g,"$1:").slice(0,-1).toUpperCase();let isMac=!1;result.includes("?qrCodeInfo=")?(searchKey=result.split("?qrCodeInfo=")[1],searchKey.includes(":")?(searchKey=searchKey.slice(-17).toUpperCase(),isMac=!0):(searchKey=searchKey.slice(-12),searchKey=formatMacAddress(searchKey),isMac=!0)):17===result.length&&result.includes(":")?(searchKey=result.toUpperCase(),isMac=!0):12===result.length&&(searchKey=formatMacAddress(result),isMac=!0);const matchedHistoryDevice=historyConnectedList.find(item=>item.macAddr==searchKey);if(matchedHistoryDevice)return void connectFn(matchedHistoryDevice);isAndroid&&isMac?connectFn({deviceId:searchKey,macAddr:searchKey,name:searchKey}):foundScanDevice(searchKey,connectFn)}catch(error){console.log(error)}},complete:err=>{},fail:err=>{console.log("scanCode err",err),failScanFn(err)}})},foundScanDevice=async(result,connectFn)=>{const deviceList=[];await startDevicesDiscovery(isIOS),onFoundDevice(device=>{deviceList.push(device);const findDevice=device.macAddr===result||device.name===result;findDevice?(scanTimeout&&(clearTimeout(scanTimeout),scanTimeout=null),uni.stopBluetoothDevicesDiscovery(),connectFn(findDevice)):console.log("未找到设备,继续搜索中...")});let scanTimeout=setTimeout(async()=>{try{console.log("stopBluetoothDevicesDiscovery",deviceList),uni.stopBluetoothDevicesDiscovery();const findDevice=deviceList.find(device=>device.macAddr===result||device.name===result);connectFn(findDevice)}finally{}},5e3)};export{checkBluetoothStatus,checkLocationStatus,connectAsync,createBLEConnection,disConnect,enhanceDevice,foundScanDevice,getBLEDeviceCharacteristics,getBLEDeviceServices,getBluetoothAdapterState,getBluetoothPermission,initBle,isInit,notify,onBLECharacteristicValueChange,onBLEConnectionStateChange,onBleChangedConnectionState,onBluetoothAdapterStateChange,onBluetoothDeviceFound,onFoundDevice,scanHandle,startDevicesDiscovery,stopBluetoothDevicesDiscovery};
1
+ import{ref}from"vue";import{ab2decimalArr,hexToDecimal}from"./BleDataProcess.js";import{getOS,getPlatform,eventBus}from"./commonfun.js";import{tcpServer}from"./tcpServer.js";import{mqttServer}from"./mqttServer.js";const serviceId="0000FF00-0000-1000-8000-00805F9B34FB",{isAndroid:isAndroid,isIOS:isIOS}=getOS(),bluetoothAdapterState=ref({available:!1,discovering:!1}),platform=getPlatform();var 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?hexToDecimal(socHex):"",productType=advHex.slice(18,20);let protocolVersion=advHex.slice(20,22);if(protocolVersion){const v=hexToDecimal(protocolVersion);macAddr.startsWith("A5:C2")&&v<=35&&(protocolVersion="01")}const appkeyStatus=advHex.slice(22,24),tempVoltage=advHex.slice(24,26),voltage=tempVoltage||0==tempVoltage?hexToDecimal(tempVoltage):"",tempCurrent=advHex.slice(26,28),current=tempCurrent||0==tempCurrent?hexToDecimal(tempCurrent):"",broadcastLen=advHex.length/2,isNewAppKey=advHex.length>=24;device={...device,macAddr:macAddr,moduleType:moduleType,soc:soc,productType:productType,advHex:advHex,protocolVersion:protocolVersion,appkeyStatus:appkeyStatus,broadcastLen:broadcastLen,isNewAppKey:isNewAppKey,voltage:voltage,current:current}}return device},checkBluetoothStatus=async(successCallback=()=>{})=>new Promise((resolve,reject)=>{uni.openBluetoothAdapter({success:async res=>{successCallback&&successCallback(res),resolve(res)},fail:err=>{console.log("openBluetoothAdapter fail4-----",err),err&&3==err?.errno&&reject({code:105,message:"请授权微信位置信息和蓝牙权限"}),err&&103==err?.errno&&reject({code:106,message:"请授权蓝牙和位置权限,并重启小程序"}),reject({code:102,message:"当前手机蓝牙不可用,请检查手机蓝牙状态"})}})}),checkLocationStatus=async(successCallback=()=>{})=>{const timeoutPromise=new Promise((resolve,reject)=>{setTimeout(()=>{reject({code:101,message:"网络信号差或连接异常,请检查网络情况"})},1e4)}),locationPromise=new Promise((resolve,reject)=>{uni.getLocation({type:"wgs84",success:res=>{console.log("位置信息-----------",res),resolve(res)},fail:err=>{console.log("位置信息err",err),err&&103==err?.errno&&reject({code:103,message:"请授权小程序位置信息权限, 并重启小程序。"}),err&&2==err?.errCode&&reject({code:101,message:"网络信号差或连接异常,请检查网络情况"}),reject({code:104,message:"请授权微信位置信息权限, 并重启小程序。"})}})});return Promise.race([locationPromise,timeoutPromise]).then(async res=>await checkBluetoothStatus(successCallback))},getBluetoothPermission=async(successCallback=()=>{})=>{try{return isAndroid?await checkLocationStatus(successCallback):await checkBluetoothStatus(successCallback)}catch(error){throw console.error("初始化蓝牙失败:",error),error}},initBle=async()=>await getBluetoothPermission(()=>{console.log("初始化蓝牙成功initBluetoothSuccessCb1");try{if(isInit)return;onBluetoothDeviceFound(),onBLECharacteristicValueChange(),onBLEConnectionStateChange(),onBluetoothAdapterStateChange(),isInit=!0}catch(error){throw error}}),getBluetoothAdapterState=async()=>new Promise((resolve,reject)=>{uni.getBluetoothAdapterState({success:res=>{console.log("getBluetoothAdapterState success",res),resolve(res)},fail:err=>{console.log("getBluetoothAdapterState fail",err),reject(err)}})}),startDevicesDiscovery=async(allowDuplicatesKey=!0)=>new Promise((resolve,reject)=>{bluetoothAdapterState.value.discovering?reject(new Error("蓝牙设备搜索已在进行中")):uni.startBluetoothDevicesDiscovery({services:[serviceId],allowDuplicatesKey:allowDuplicatesKey,success:async res=>{console.log("广播设备 success",res),resolve(res)},fail:err=>{console.log("广播设备 fail",err),reject(err)}})}),stopBluetoothDevicesDiscovery=async()=>(bluetoothAdapterState.value={available:bluetoothAdapterState.value.available,discovering:!1},new Promise((resolve,reject)=>{uni.stopBluetoothDevicesDiscovery({success:res=>{console.log("停止广播设备 success",res),resolve(res)},fail:err=>{console.log("停止广播设备 fail",err),reject(err)},complete:res=>{console.log("停止广播设备 取消订阅"),eventBus.off("setBluetoothDeviceFound")}})})),onBluetoothDeviceFound=async()=>{uni.onBluetoothDeviceFound(characteristic=>{console.log("setBluetoothDeviceFound",characteristic);const device=enhanceDevice(characteristic.devices[0]);device&&eventBus.emit("setBluetoothDeviceFound",device)})},onFoundDevice=callback=>{eventBus.on("setBluetoothDeviceFound",callback)},onBluetoothAdapterStateChange=async()=>{uni.onBluetoothAdapterStateChange(res=>{console.log("onBluetoothAdapterStateChange监听蓝牙适配器变化",res),bluetoothAdapterState.value=res})},onBLECharacteristicValueChange=async()=>{uni.onBLECharacteristicValueChange(characteristic=>{const decimalArr=ab2decimalArr(characteristic.value);console.warn("decimalArr: 监听到的回复-------------------",decimalArr),eventBus.emit("setBleChangedCharacteristicValue",characteristic)})},onBLEConnectionStateChange=async()=>{uni.onBLEConnectionStateChange(characteristic=>{console.log("onBLEConnectionStateChange",characteristic),eventBus.emit("setBleChangedConnectionState",characteristic),characteristic.connected||("mp-weixin"===platform?tcpServer.closeTcpSocket(characteristic.deviceId):mqttServer.closeMqttByDeviceId(characteristic.deviceId))})},onBleChangedConnectionState=callback=>{eventBus.on("setBleChangedConnectionState",callback)},createBLEConnection=async(deviceId,timeout=1e4)=>new Promise((resolve,reject)=>{console.log(deviceId,"点击的设备信息"),uni.createBLEConnection({deviceId:deviceId,timeout:timeout,success:res=>{console.log(res,"连接成功"),resolve(!0)},fail:err=>{console.log(err,"Connection"),-1==(err.code||err.errCode)?resolve(!0):reject(err)}})}),withRetry=async(asyncOperation,maxRetries=20,retryInterval=100,type)=>new Promise((resolve,reject)=>{let retryCount=0;const attempt=async()=>{try{const result=await asyncOperation();resolve(result)}catch(error){if(retryCount>=maxRetries)return void reject(new Error(`${type}失败,${error.message} (已重试${maxRetries}次)`));retryCount++,console.warn(`${type}失败,第${retryCount}次重试:`,error.message),setTimeout(attempt,retryInterval)}};attempt()}),getBLEDeviceServices=deviceId=>withRetry(async()=>{const res=await new Promise((resolve,reject)=>{uni.getBLEDeviceServices({deviceId:deviceId,success:resolve,fail:reject})});if(console.log("获取蓝牙服务成功:",res),0===res.services.length)throw new Error("未找到蓝牙服务");return await getBLEDeviceCharacteristics(deviceId),res.services},10,300,"获取蓝牙服务"),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},10,300,"获取蓝牙特征值"),notify=async deviceId=>new Promise((resolve,reject)=>{uni.notifyBLECharacteristicValueChange({deviceId:deviceId,serviceId:serviceId,characteristicId:"0000FF01-0000-1000-8000-00805F9B34FB",state:!0,success:res=>{console.log("订阅===========",res),resolve(res)},fail:reject})}),disConnect=deviceId=>new Promise((resolve,reject)=>{uni.closeBLEConnection({deviceId:deviceId,success:res=>{resolve(res),console.log(res,"断开连接成功")},fail:err=>{reject(err),console.log(err,"err 断开连接")}})}),connectAsync=async(deviceId,timeout=1e4)=>new Promise(async(resolve,reject)=>{try{await createBLEConnection(deviceId,timeout),await new Promise(resolve=>setTimeout(resolve,800)),await getBLEDeviceServices(deviceId),await notify(deviceId),resolve(!0)}catch(error){console.log("error: ",error),reject(error)}}),scanHandle=(historyConnectedList=[],connectFn=device=>{},failScanFn=err=>{})=>{uni.scanCode({scanType:["barCode","qrCode"],autoZoom:!1,success:async({result:result})=>{bluetoothScanHandle(result,historyConnectedList,connectFn,failScanFn)},complete:err=>{},fail:err=>{console.log("scanCode err",err),failScanFn(err)}})},bluetoothScanHandle=(retult,historyConnectedList=[],connectFn=device=>{},failScanFn=err=>{})=>{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)}},foundScanDevice=async(result,connectFn)=>{const deviceList=[];await startDevicesDiscovery(isIOS),onFoundDevice(device=>{deviceList.push(device);const findDevice=device.macAddr===result||device.name===result;findDevice?(scanTimeout&&(clearTimeout(scanTimeout),scanTimeout=null),uni.stopBluetoothDevicesDiscovery(),connectFn(findDevice)):console.log("未找到设备,继续搜索中...")});let scanTimeout=setTimeout(async()=>{try{console.log("stopBluetoothDevicesDiscovery",deviceList),uni.stopBluetoothDevicesDiscovery();const findDevice=deviceList.find(device=>device.macAddr===result||device.name===result);connectFn(findDevice)}finally{}},5e3)};export{bluetoothScanHandle,checkBluetoothStatus,checkLocationStatus,connectAsync,createBLEConnection,disConnect,enhanceDevice,foundScanDevice,getBLEDeviceCharacteristics,getBLEDeviceServices,getBluetoothAdapterState,getBluetoothPermission,initBle,isInit,notify,onBLECharacteristicValueChange,onBLEConnectionStateChange,onBleChangedConnectionState,onBluetoothAdapterStateChange,onBluetoothDeviceFound,onFoundDevice,scanHandle,startDevicesDiscovery,stopBluetoothDevicesDiscovery};
@@ -1 +1 @@
1
- import{hexArr2ab,ab2decimalArr,hexArr2string,sleep}from"../BleDataProcess.js";import{getOS,eventBus,getPlatform}from"../commonfun.js";import{mqttServer}from"../mqttServer.js";const BLE_COMMAND_QUEUE=new Map,BLE_COMMAND_RUNNING=new Set,runNextBleCommand=async queueKey=>{if(BLE_COMMAND_RUNNING.has(queueKey))return;const queue=BLE_COMMAND_QUEUE.get(queueKey)||[];if(0===queue.length)return void BLE_COMMAND_QUEUE.delete(queueKey);BLE_COMMAND_RUNNING.add(queueKey);const currentTask=queue[0];try{const result=await currentTask.task();currentTask.resolve(result)}catch(error){currentTask.reject(error)}finally{const currentQueue=BLE_COMMAND_QUEUE.get(queueKey)||[];currentQueue.shift(),BLE_COMMAND_RUNNING.delete(queueKey),0===currentQueue.length?BLE_COMMAND_QUEUE.delete(queueKey):runNextBleCommand(queueKey)}};async function _writeAsync(deviceId,value){return console.log("deviceId, value: ",deviceId,value),!(!deviceId||!value)&&new Promise(resolve=>{const{isAndroid:isAndroid,isIOS:isIOS}=getOS(),platform=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)})}const 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((deviceId,task)=>{const queueKey=deviceId||"__default__";return new Promise((resolve,reject)=>{const queue=BLE_COMMAND_QUEUE.get(queueKey)||[];queue.push({task:task,resolve:resolve,reject:reject}),BLE_COMMAND_QUEUE.set(queueKey,queue),runNextBleCommand(queueKey)})})(deviceId,()=>new Promise((resolve,reject)=>{let isCompleted=!1,timeoutId=null,responsed=!1,len=null,pkg=[];const cmdContent=hexArr2ab(command),cleanup=()=>{isCompleted||(isCompleted=!0,clearTimeout(timeoutId),eventBus.off("setBleChangedCharacteristicValue",dataHandler))},dataHandler=payload=>{if(!payload||payload.deviceId!==deviceId||!payload.value)return;const hexArr=ab2decimalArr(payload.value);if(console.log("hexArr: ",hexArr),console.warn(tag,"接收到数据:",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);if(console.log("数据包验证结果:",{verified:verified}),verified){responsed=!0,cleanup();const value=[...pkg].map(o=>`00${o.toString(16)}`.slice(-2)).join(""),cmdCode=mqttServer.currentCommand;value&&cmdCode&&(0===mqttServer.setPassthroughType&&mqttServer.publishPassthroughHandle({value:value,cmdCode:cmdCode},deviceId),mqttServer.setPassthroughType=0),resolve([...pkg])}else 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 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 sleep(retryInterval),!responsed&&attempt<maxRetries?(console.log(tag,`未收到响应,准备第${attempt+1}次重试`),writeToDevice(attempt+1)):responsed||(console.warn(tag,`达到最大重试次数(${maxRetries}),未收到响应`),cleanup(),resolve(null))}catch(error){console.error(tag,"写入过程发生错误:",error),cleanup(),reject(error)}};timeoutId=setTimeout(()=>{console.warn(tag,"操作超时"),cleanup(),resolve(null)},(maxRetries+2)*retryInterval),eventBus.on("setBleChangedCharacteristicValue",dataHandler),writeToDevice().catch(error=>{cleanup(),reject(error)})}))},setMTUAsync=(deviceId,mtu=512,delay=2500)=>new Promise((resolve,reject)=>{try{if(getOS().isIOS)return resolve(!0);setTimeout(async()=>{await uni.setBLEMTU({deviceId:deviceId,mtu:mtu}),resolve(!0)},delay)}catch(error){console.error(error),reject(error)}});export{getData,setMTUAsync};
1
+ import{hexArr2ab,ab2decimalArr,hexArr2string,sleep}from"../BleDataProcess.js";import{getPlatform,getOS,eventBus}from"../commonfun.js";import{mqttServer}from"../mqttServer.js";const BLE_COMMAND_QUEUE=new Map,BLE_COMMAND_RUNNING=new Set,platform=getPlatform(),runNextBleCommand=async queueKey=>{if(BLE_COMMAND_RUNNING.has(queueKey))return;const queue=BLE_COMMAND_QUEUE.get(queueKey)||[];if(0===queue.length)return void BLE_COMMAND_QUEUE.delete(queueKey);BLE_COMMAND_RUNNING.add(queueKey);const currentTask=queue[0];try{const result=await currentTask.task();currentTask.resolve(result)}catch(error){currentTask.reject(error)}finally{const currentQueue=BLE_COMMAND_QUEUE.get(queueKey)||[];currentQueue.shift(),BLE_COMMAND_RUNNING.delete(queueKey),0===currentQueue.length?BLE_COMMAND_QUEUE.delete(queueKey):runNextBleCommand(queueKey)}};async function _writeAsync(deviceId,value){return console.log("deviceId, value: ",deviceId,value),!(!deviceId||!value)&&new Promise(resolve=>{const{isAndroid:isAndroid,isIOS:isIOS}=getOS(),platform=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)})}const 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((deviceId,task)=>{const queueKey=deviceId||"__default__";return new Promise((resolve,reject)=>{const queue=BLE_COMMAND_QUEUE.get(queueKey)||[];queue.push({task:task,resolve:resolve,reject:reject}),BLE_COMMAND_QUEUE.set(queueKey,queue),runNextBleCommand(queueKey)})})(deviceId,()=>new Promise((resolve,reject)=>{let isCompleted=!1,timeoutId=null,responsed=!1,len=null,pkg=[];const cmdContent=hexArr2ab(command),cleanup=()=>{isCompleted||(isCompleted=!0,clearTimeout(timeoutId),eventBus.off("setBleChangedCharacteristicValue",dataHandler))},dataHandler=payload=>{if(!payload||payload.deviceId!==deviceId||!payload.value)return;const hexArr=ab2decimalArr(payload.value);if(console.log("hexArr: ",hexArr),console.warn(tag,"接收到数据:",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);if(console.log("数据包验证结果:",{verified:verified}),verified){if(responsed=!0,cleanup(),"mp-weixin"!==platform){const value=[...pkg].map(o=>`00${o.toString(16)}`.slice(-2)).join(""),cmdCode=mqttServer.currentCommand;value&&cmdCode&&(0===mqttServer.setPassthroughType&&mqttServer.publishPassthroughHandle({value:value,cmdCode:cmdCode},deviceId),mqttServer.setPassthroughType=0)}resolve([...pkg])}else 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 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 sleep(retryInterval),!responsed&&attempt<maxRetries?(console.log(tag,`未收到响应,准备第${attempt+1}次重试`),writeToDevice(attempt+1)):responsed||(console.warn(tag,`达到最大重试次数(${maxRetries}),未收到响应`),cleanup(),resolve(null))}catch(error){console.error(tag,"写入过程发生错误:",error),cleanup(),reject(error)}};timeoutId=setTimeout(()=>{console.warn(tag,"操作超时"),cleanup(),resolve(null)},(maxRetries+2)*retryInterval),eventBus.on("setBleChangedCharacteristicValue",dataHandler),writeToDevice().catch(error=>{cleanup(),reject(error)})}))},setMTUAsync=(deviceId,mtu=512,delay=2500)=>new Promise((resolve,reject)=>{try{if(getOS().isIOS)return resolve(!0);setTimeout(async()=>{await uni.setBLEMTU({deviceId:deviceId,mtu:mtu}),resolve(!0)},delay)}catch(error){console.error(error),reject(error)}});export{getData,setMTUAsync};