@jiabaida/tools 1.0.6 → 1.0.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/core/BleApiManager.js +1 -1
- package/dist/cjs/core/BleCmdAnalysis/BleCmdAnalysis.js +1 -1
- package/dist/cjs/core/BleCmdAnalysis/BleCmdDDA4.js +1 -0
- package/dist/cjs/core/mqttServer.js +1 -0
- package/dist/cjs/core/rsaEncrypt.js +1 -0
- package/dist/cjs/index.js +1 -1
- package/dist/esm/core/BleApiManager.js +1 -1
- package/dist/esm/core/BleCmdAnalysis/BleCmdAnalysis.js +1 -1
- package/dist/esm/core/BleCmdAnalysis/BleCmdDDA4.js +1 -0
- package/dist/esm/core/mqttServer.js +1 -0
- package/dist/esm/core/rsaEncrypt.js +1 -0
- package/dist/esm/index.js +1 -1
- package/package.json +4 -3
- package/src/core/BleApiManager.js +3 -1
- package/src/core/BleCmdAnalysis/BleCmdAnalysis.js +3 -2
- package/src/core/BleCmdAnalysis/BleCmdDDA4.js +74 -11
- package/src/core/BleCmdAnalysis/index.js +6 -5
- package/src/core/mqttServer.js +9 -9
- package/src/core/rsaEncrypt.js +1 -1
- package/src/index.js +4 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var vue=require("vue"),BleDataProcess=require("./BleDataProcess.js"),commonfun=require("./commonfun.js");const serviceId="0000FF00-0000-1000-8000-00805F9B34FB",{isAndroid:isAndroid,isIOS:isIOS}=commonfun.getOS(),bluetoothAdapterState=vue.ref({available:!1,discovering:!1});exports.isInit=!1;const checkBluetoothStatus=async(successCallback=()=>{})=>new Promise((resolve,reject)=>{uni.openBluetoothAdapter({success:async res=>{successCallback&&successCallback(res),resolve(res)},fail:err=>{console.log("openBluetoothAdapter fail4-----",err),err&&3==err?.errno&&reject({code:105,message:"请授权微信位置信息和蓝牙权限"}),err&&103==err?.errno&&reject({code:106,message:"请授权蓝牙和位置权限,并重启小程序"}),reject({code:102,message:"当前手机蓝牙不可用,请检查手机蓝牙状态"})}})}),checkLocationStatus=async(successCallback=()=>{})=>{const timeoutPromise=new Promise((resolve,reject)=>{setTimeout(()=>{reject({code:101,message:"网络信号差或连接异常,请检查网络情况"})},1e4)}),locationPromise=new Promise((resolve,reject)=>{uni.getLocation({type:"wgs84",success:res=>{console.log("位置信息-----------",res),resolve(res)},fail:err=>{console.log("位置信息err",err),err&&103==err?.errno&&reject({code:103,message:"请授权小程序位置信息权限, 并重启小程序。"}),err&&2==err?.errCode&&reject({code:101,message:"网络信号差或连接异常,请检查网络情况"}),reject({code:104,message:"请授权微信位置信息权限, 并重启小程序。"})}})});return Promise.race([locationPromise,timeoutPromise]).then(async res=>await checkBluetoothStatus(successCallback))},getBluetoothPermission=async(successCallback=()=>{})=>{try{return isAndroid?await checkLocationStatus(successCallback):await checkBluetoothStatus(successCallback)}catch(error){throw console.error("初始化蓝牙失败:",error),error}},startDevicesDiscovery=async(allowDuplicatesKey=!0)=>new Promise((resolve,reject)=>{bluetoothAdapterState.value.discovering?reject(new Error("蓝牙设备搜索已在进行中")):uni.startBluetoothDevicesDiscovery({services:[serviceId],allowDuplicatesKey:allowDuplicatesKey,success:async res=>{console.log("广播设备 success",res),resolve(res)},fail:err=>{console.log("广播设备 fail",err),reject(err)}})}),onBluetoothDeviceFound=async()=>{uni.onBluetoothDeviceFound(characteristic=>{console.log("setBluetoothDeviceFound",characteristic);const device=(device=>{const adv=device?.advertisData;if(!adv)return null;if(adv){const advHex=Array.prototype.map.call(new Uint8Array(adv),o=>("00"+o.toString(16)).slice(-2)).join("").toUpperCase();let macAddr=advHex.slice(0,12).toUpperCase(),arr=macAddr.match(/(.{2})/g);const flag=macAddr.slice(-4);"C1A4"!=flag&&"C2A5"!=flag&&"C2A8"!=flag||arr.reverse(),macAddr=arr.join(":"),device.hasFound=!0;const moduleType=advHex.slice(12,16),socHex=advHex.slice(16,18),soc=socHex||0==socHex?BleDataProcess.hexToDecimal(socHex):"",productType=advHex.slice(18,20);let protocolVersion=advHex.slice(20,22);if(protocolVersion){const v=BleDataProcess.hexToDecimal(protocolVersion);macAddr.startsWith("A5:C2")&&v<=35&&(protocolVersion="01")}const appkeyStatus=advHex.slice(22,24),tempVoltage=advHex.slice(24,26),voltage=tempVoltage||0==tempVoltage?BleDataProcess.hexToDecimal(tempVoltage):"",tempCurrent=advHex.slice(26,28),current=tempCurrent||0==tempCurrent?BleDataProcess.hexToDecimal(tempCurrent):"",broadcastLen=advHex.length/2,isNewAppKey=advHex.length>=24;device={...device,macAddr:macAddr,moduleType:moduleType,soc:soc,productType:productType,advHex:advHex,protocolVersion:protocolVersion,appkeyStatus:appkeyStatus,broadcastLen:broadcastLen,isNewAppKey:isNewAppKey,voltage:voltage,current:current}}return device})(characteristic.devices[0]);device&&commonfun.eventBus.emit("setBluetoothDeviceFound",device)})},onFoundDevice=callback=>{commonfun.eventBus.on("setBluetoothDeviceFound",callback)},onBluetoothAdapterStateChange=async()=>{uni.onBluetoothAdapterStateChange(res=>{console.log("onBluetoothAdapterStateChange监听蓝牙适配器变化",res),bluetoothAdapterState.value=res})},onBLECharacteristicValueChange=async()=>{uni.onBLECharacteristicValueChange(characteristic=>{const decimalArr=BleDataProcess.ab2decimalArr(characteristic.value);console.warn("decimalArr: 监听到的回复-------------------",decimalArr),commonfun.eventBus.emit("setBleChangedCharacteristicValue",characteristic)})},onBLEConnectionStateChange=async()=>{uni.onBLEConnectionStateChange(characteristic=>{console.log("onBLEConnectionStateChange",characteristic),commonfun.eventBus.emit("setBleChangedConnectionState",characteristic)})},createBLEConnection=async(deviceId,timeout=1e4)=>new Promise((resolve,reject)=>{console.log(deviceId,"点击的设备信息"),uni.createBLEConnection({deviceId:deviceId,timeout:timeout,success:res=>{console.log(res,"连接成功"),resolve(!0)},fail:err=>{console.log(err,"Connection"),-1==(err.code||err.errCode)?resolve(!0):reject(err)}})}),withRetry=async(asyncOperation,maxRetries=20,retryInterval=100,type)=>new Promise((resolve,reject)=>{let retryCount=0;const attempt=async()=>{try{const result=await asyncOperation();resolve(result)}catch(error){if(retryCount>=maxRetries)return void reject(new Error(`${type}失败,${error.message} (已重试${maxRetries}次)`));retryCount++,console.warn(`${type}失败,第${retryCount}次重试:`,error.message),setTimeout(attempt,retryInterval)}};attempt()}),getBLEDeviceServices=deviceId=>withRetry(async()=>{const res=await new Promise((resolve,reject)=>{uni.getBLEDeviceServices({deviceId:deviceId,success:resolve,fail:reject})});if(console.log("获取蓝牙服务成功:",res),0===res.services.length)throw new Error("未找到蓝牙服务");return await getBLEDeviceCharacteristics(deviceId),res.services},20,100,"获取蓝牙服务"),getBLEDeviceCharacteristics=async deviceId=>withRetry(async()=>{const res=await new Promise((resolve,reject)=>{uni.getBLEDeviceCharacteristics({deviceId:deviceId,serviceId:serviceId,success:resolve,fail:reject})});return console.log("获取特征值成功:",res),res.characteristics},20,100,"获取蓝牙特征值"),notify=async deviceId=>new Promise((resolve,reject)=>{uni.notifyBLECharacteristicValueChange({deviceId:deviceId,serviceId:serviceId,characteristicId:"0000FF01-0000-1000-8000-00805F9B34FB",state:!0,success:res=>{console.log("订阅===========",res),resolve(res)},fail:reject})}),foundScanDevice=async(result,connectFn)=>{const deviceList=[];await startDevicesDiscovery(isIOS),onFoundDevice(device=>{deviceList.push(device);const findDevice=device.macAddr===result||device.name===result;findDevice?(scanTimeout&&(clearTimeout(scanTimeout),scanTimeout=null),uni.stopBluetoothDevicesDiscovery(),connectFn(findDevice)):console.log("未找到设备,继续搜索中...")});let scanTimeout=setTimeout(async()=>{try{console.log("stopBluetoothDevicesDiscovery",deviceList),uni.stopBluetoothDevicesDiscovery();const findDevice=deviceList.find(device=>device.macAddr===result||device.name===result);connectFn(findDevice)}finally{}},5e3)};exports.checkBluetoothStatus=checkBluetoothStatus,exports.checkLocationStatus=checkLocationStatus,exports.connectAsync=async(deviceId,timeout=1e4)=>new Promise(async(resolve,reject)=>{try{await createBLEConnection(deviceId,timeout),await getBLEDeviceServices(deviceId),await notify(deviceId),resolve(!0)}catch(error){console.log("error: ",error),reject(error)}}),exports.createBLEConnection=createBLEConnection,exports.disConnect=deviceId=>new Promise((resolve,reject)=>{uni.closeBLEConnection({deviceId:deviceId,success:res=>{resolve(res),console.log(res,"断开连接成功")},fail:err=>{reject(err),console.log(err,"err 断开连接")}})}),exports.foundScanDevice=foundScanDevice,exports.getBLEDeviceCharacteristics=getBLEDeviceCharacteristics,exports.getBLEDeviceServices=getBLEDeviceServices,exports.getBluetoothAdapterState=async()=>new Promise((resolve,reject)=>{uni.getBluetoothAdapterState({success:res=>{console.log("getBluetoothAdapterState success",res),resolve(res)},fail:err=>{console.log("getBluetoothAdapterState fail",err),reject(err)}})}),exports.getBluetoothPermission=getBluetoothPermission,exports.initBle=async()=>await getBluetoothPermission(()=>{try{onBluetoothDeviceFound(),onBLECharacteristicValueChange(),onBLEConnectionStateChange(),onBluetoothAdapterStateChange(),exports.isInit=!0}catch(error){throw error}}),exports.notify=notify,exports.onBLECharacteristicValueChange=onBLECharacteristicValueChange,exports.onBLEConnectionStateChange=onBLEConnectionStateChange,exports.onBleChangedConnectionState=callback=>{commonfun.eventBus.on("setBleChangedConnectionState",callback)},exports.onBluetoothAdapterStateChange=onBluetoothAdapterStateChange,exports.onBluetoothDeviceFound=onBluetoothDeviceFound,exports.onFoundDevice=onFoundDevice,exports.scanHandle=(historyConnectedList=[],connectFn=device=>{},failScanFn=err=>{})=>{uni.scanCode({scanType:["barCode","qrCode"],success:async({result:result})=>{console.log("扫描内容: "+result);let searchKey=result;try{const formatMacAddress=mac=>mac.replace(/(.{2})/g,"$1:").slice(0,-1).toUpperCase();let isMac=!1;result.includes("?qrCodeInfo=")?(searchKey=result.split("?qrCodeInfo=")[1],searchKey.includes(":")?(searchKey=searchKey.slice(-17).toUpperCase(),isMac=!0):(searchKey=searchKey.slice(-12),searchKey=formatMacAddress(searchKey),isMac=!0)):17===result.length&&result.includes(":")?(searchKey=result.toUpperCase(),isMac=!0):12===result.length&&(searchKey=formatMacAddress(result),isMac=!0);const matchedHistoryDevice=historyConnectedList.find(item=>item.macAddr==searchKey);if(matchedHistoryDevice)return void connectFn(matchedHistoryDevice);isAndroid&&isMac?connectFn({deviceId:searchKey,macAddr:searchKey,name:searchKey}):foundScanDevice(searchKey,connectFn)}catch(error){console.log(error)}},complete:err=>{},fail:err=>{console.log("scanCode err",err),failScanFn(err)}})},exports.startDevicesDiscovery=startDevicesDiscovery,exports.stopBluetoothDevicesDiscovery=async()=>(bluetoothAdapterState.value={available:bluetoothAdapterState.value.available,discovering:!1},new Promise((resolve,reject)=>{uni.stopBluetoothDevicesDiscovery({success:res=>{console.log("停止广播设备 success",res),resolve(res)},fail:err=>{console.log("停止广播设备 fail",err),reject(err)},complete:res=>{console.log("停止广播设备 取消订阅"),commonfun.eventBus.off("setBluetoothDeviceFound")}})}));
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var vue=require("vue"),BleDataProcess=require("./BleDataProcess.js"),commonfun=require("./commonfun.js");const serviceId="0000FF00-0000-1000-8000-00805F9B34FB",{isAndroid:isAndroid,isIOS:isIOS}=commonfun.getOS(),bluetoothAdapterState=vue.ref({available:!1,discovering:!1});exports.isInit=!1;const enhanceDevice=device=>{const adv=device?.advertisData;if(!adv)return null;if(adv){const advHex=Array.prototype.map.call(new Uint8Array(adv),o=>("00"+o.toString(16)).slice(-2)).join("").toUpperCase();let macAddr=advHex.slice(0,12).toUpperCase(),arr=macAddr.match(/(.{2})/g);const flag=macAddr.slice(-4);"C1A4"!=flag&&"C2A5"!=flag&&"C2A8"!=flag||arr.reverse(),macAddr=arr.join(":"),device.hasFound=!0;const moduleType=advHex.slice(12,16),socHex=advHex.slice(16,18),soc=socHex||0==socHex?BleDataProcess.hexToDecimal(socHex):"",productType=advHex.slice(18,20);let protocolVersion=advHex.slice(20,22);if(protocolVersion){const v=BleDataProcess.hexToDecimal(protocolVersion);macAddr.startsWith("A5:C2")&&v<=35&&(protocolVersion="01")}const appkeyStatus=advHex.slice(22,24),tempVoltage=advHex.slice(24,26),voltage=tempVoltage||0==tempVoltage?BleDataProcess.hexToDecimal(tempVoltage):"",tempCurrent=advHex.slice(26,28),current=tempCurrent||0==tempCurrent?BleDataProcess.hexToDecimal(tempCurrent):"",broadcastLen=advHex.length/2,isNewAppKey=advHex.length>=24;device={...device,macAddr:macAddr,moduleType:moduleType,soc:soc,productType:productType,advHex:advHex,protocolVersion:protocolVersion,appkeyStatus:appkeyStatus,broadcastLen:broadcastLen,isNewAppKey:isNewAppKey,voltage:voltage,current:current}}return device},checkBluetoothStatus=async(successCallback=()=>{})=>new Promise((resolve,reject)=>{uni.openBluetoothAdapter({success:async res=>{successCallback&&successCallback(res),resolve(res)},fail:err=>{console.log("openBluetoothAdapter fail4-----",err),err&&3==err?.errno&&reject({code:105,message:"请授权微信位置信息和蓝牙权限"}),err&&103==err?.errno&&reject({code:106,message:"请授权蓝牙和位置权限,并重启小程序"}),reject({code:102,message:"当前手机蓝牙不可用,请检查手机蓝牙状态"})}})}),checkLocationStatus=async(successCallback=()=>{})=>{const timeoutPromise=new Promise((resolve,reject)=>{setTimeout(()=>{reject({code:101,message:"网络信号差或连接异常,请检查网络情况"})},1e4)}),locationPromise=new Promise((resolve,reject)=>{uni.getLocation({type:"wgs84",success:res=>{console.log("位置信息-----------",res),resolve(res)},fail:err=>{console.log("位置信息err",err),err&&103==err?.errno&&reject({code:103,message:"请授权小程序位置信息权限, 并重启小程序。"}),err&&2==err?.errCode&&reject({code:101,message:"网络信号差或连接异常,请检查网络情况"}),reject({code:104,message:"请授权微信位置信息权限, 并重启小程序。"})}})});return Promise.race([locationPromise,timeoutPromise]).then(async res=>await checkBluetoothStatus(successCallback))},getBluetoothPermission=async(successCallback=()=>{})=>{try{return isAndroid?await checkLocationStatus(successCallback):await checkBluetoothStatus(successCallback)}catch(error){throw console.error("初始化蓝牙失败:",error),error}},startDevicesDiscovery=async(allowDuplicatesKey=!0)=>new Promise((resolve,reject)=>{bluetoothAdapterState.value.discovering?reject(new Error("蓝牙设备搜索已在进行中")):uni.startBluetoothDevicesDiscovery({services:[serviceId],allowDuplicatesKey:allowDuplicatesKey,success:async res=>{console.log("广播设备 success",res),resolve(res)},fail:err=>{console.log("广播设备 fail",err),reject(err)}})}),onBluetoothDeviceFound=async()=>{uni.onBluetoothDeviceFound(characteristic=>{console.log("setBluetoothDeviceFound",characteristic);const device=enhanceDevice(characteristic.devices[0]);device&&commonfun.eventBus.emit("setBluetoothDeviceFound",device)})},onFoundDevice=callback=>{commonfun.eventBus.on("setBluetoothDeviceFound",callback)},onBluetoothAdapterStateChange=async()=>{uni.onBluetoothAdapterStateChange(res=>{console.log("onBluetoothAdapterStateChange监听蓝牙适配器变化",res),bluetoothAdapterState.value=res})},onBLECharacteristicValueChange=async()=>{uni.onBLECharacteristicValueChange(characteristic=>{const decimalArr=BleDataProcess.ab2decimalArr(characteristic.value);console.warn("decimalArr: 监听到的回复-------------------",decimalArr),commonfun.eventBus.emit("setBleChangedCharacteristicValue",characteristic)})},onBLEConnectionStateChange=async()=>{uni.onBLEConnectionStateChange(characteristic=>{console.log("onBLEConnectionStateChange",characteristic),commonfun.eventBus.emit("setBleChangedConnectionState",characteristic)})},createBLEConnection=async(deviceId,timeout=1e4)=>new Promise((resolve,reject)=>{console.log(deviceId,"点击的设备信息"),uni.createBLEConnection({deviceId:deviceId,timeout:timeout,success:res=>{console.log(res,"连接成功"),resolve(!0)},fail:err=>{console.log(err,"Connection"),-1==(err.code||err.errCode)?resolve(!0):reject(err)}})}),withRetry=async(asyncOperation,maxRetries=20,retryInterval=100,type)=>new Promise((resolve,reject)=>{let retryCount=0;const attempt=async()=>{try{const result=await asyncOperation();resolve(result)}catch(error){if(retryCount>=maxRetries)return void reject(new Error(`${type}失败,${error.message} (已重试${maxRetries}次)`));retryCount++,console.warn(`${type}失败,第${retryCount}次重试:`,error.message),setTimeout(attempt,retryInterval)}};attempt()}),getBLEDeviceServices=deviceId=>withRetry(async()=>{const res=await new Promise((resolve,reject)=>{uni.getBLEDeviceServices({deviceId:deviceId,success:resolve,fail:reject})});if(console.log("获取蓝牙服务成功:",res),0===res.services.length)throw new Error("未找到蓝牙服务");return await getBLEDeviceCharacteristics(deviceId),res.services},20,100,"获取蓝牙服务"),getBLEDeviceCharacteristics=async deviceId=>withRetry(async()=>{const res=await new Promise((resolve,reject)=>{uni.getBLEDeviceCharacteristics({deviceId:deviceId,serviceId:serviceId,success:resolve,fail:reject})});return console.log("获取特征值成功:",res),res.characteristics},20,100,"获取蓝牙特征值"),notify=async deviceId=>new Promise((resolve,reject)=>{uni.notifyBLECharacteristicValueChange({deviceId:deviceId,serviceId:serviceId,characteristicId:"0000FF01-0000-1000-8000-00805F9B34FB",state:!0,success:res=>{console.log("订阅===========",res),resolve(res)},fail:reject})}),foundScanDevice=async(result,connectFn)=>{const deviceList=[];await startDevicesDiscovery(isIOS),onFoundDevice(device=>{deviceList.push(device);const findDevice=device.macAddr===result||device.name===result;findDevice?(scanTimeout&&(clearTimeout(scanTimeout),scanTimeout=null),uni.stopBluetoothDevicesDiscovery(),connectFn(findDevice)):console.log("未找到设备,继续搜索中...")});let scanTimeout=setTimeout(async()=>{try{console.log("stopBluetoothDevicesDiscovery",deviceList),uni.stopBluetoothDevicesDiscovery();const findDevice=deviceList.find(device=>device.macAddr===result||device.name===result);connectFn(findDevice)}finally{}},5e3)};exports.checkBluetoothStatus=checkBluetoothStatus,exports.checkLocationStatus=checkLocationStatus,exports.connectAsync=async(deviceId,timeout=1e4)=>new Promise(async(resolve,reject)=>{try{await createBLEConnection(deviceId,timeout),await getBLEDeviceServices(deviceId),await notify(deviceId),resolve(!0)}catch(error){console.log("error: ",error),reject(error)}}),exports.createBLEConnection=createBLEConnection,exports.disConnect=deviceId=>new Promise((resolve,reject)=>{uni.closeBLEConnection({deviceId:deviceId,success:res=>{resolve(res),console.log(res,"断开连接成功")},fail:err=>{reject(err),console.log(err,"err 断开连接")}})}),exports.enhanceDevice=enhanceDevice,exports.foundScanDevice=foundScanDevice,exports.getBLEDeviceCharacteristics=getBLEDeviceCharacteristics,exports.getBLEDeviceServices=getBLEDeviceServices,exports.getBluetoothAdapterState=async()=>new Promise((resolve,reject)=>{uni.getBluetoothAdapterState({success:res=>{console.log("getBluetoothAdapterState success",res),resolve(res)},fail:err=>{console.log("getBluetoothAdapterState fail",err),reject(err)}})}),exports.getBluetoothPermission=getBluetoothPermission,exports.initBle=async()=>await getBluetoothPermission(()=>{console.log("初始化蓝牙成功initBluetoothSuccessCb1");try{if(exports.isInit)return;onBluetoothDeviceFound(),onBLECharacteristicValueChange(),onBLEConnectionStateChange(),onBluetoothAdapterStateChange(),exports.isInit=!0}catch(error){throw error}}),exports.notify=notify,exports.onBLECharacteristicValueChange=onBLECharacteristicValueChange,exports.onBLEConnectionStateChange=onBLEConnectionStateChange,exports.onBleChangedConnectionState=callback=>{commonfun.eventBus.on("setBleChangedConnectionState",callback)},exports.onBluetoothAdapterStateChange=onBluetoothAdapterStateChange,exports.onBluetoothDeviceFound=onBluetoothDeviceFound,exports.onFoundDevice=onFoundDevice,exports.scanHandle=(historyConnectedList=[],connectFn=device=>{},failScanFn=err=>{})=>{uni.scanCode({scanType:["barCode","qrCode"],success:async({result:result})=>{console.log("扫描内容: "+result);let searchKey=result;try{const formatMacAddress=mac=>mac.replace(/(.{2})/g,"$1:").slice(0,-1).toUpperCase();let isMac=!1;result.includes("?qrCodeInfo=")?(searchKey=result.split("?qrCodeInfo=")[1],searchKey.includes(":")?(searchKey=searchKey.slice(-17).toUpperCase(),isMac=!0):(searchKey=searchKey.slice(-12),searchKey=formatMacAddress(searchKey),isMac=!0)):17===result.length&&result.includes(":")?(searchKey=result.toUpperCase(),isMac=!0):12===result.length&&(searchKey=formatMacAddress(result),isMac=!0);const matchedHistoryDevice=historyConnectedList.find(item=>item.macAddr==searchKey);if(matchedHistoryDevice)return void connectFn(matchedHistoryDevice);isAndroid&&isMac?connectFn({deviceId:searchKey,macAddr:searchKey,name:searchKey}):foundScanDevice(searchKey,connectFn)}catch(error){console.log(error)}},complete:err=>{},fail:err=>{console.log("scanCode err",err),failScanFn(err)}})},exports.startDevicesDiscovery=startDevicesDiscovery,exports.stopBluetoothDevicesDiscovery=async()=>(bluetoothAdapterState.value={available:bluetoothAdapterState.value.available,discovering:!1},new Promise((resolve,reject)=>{uni.stopBluetoothDevicesDiscovery({success:res=>{console.log("停止广播设备 success",res),resolve(res)},fail:err=>{console.log("停止广播设备 fail",err),reject(err)},complete:res=>{console.log("停止广播设备 取消订阅"),commonfun.eventBus.off("setBluetoothDeviceFound")}})}));
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var BleDataProcess=require("../BleDataProcess.js"),commonfun=require("../commonfun.js");async function _writeAsync(deviceId,value){return console.log("deviceId, value: ",deviceId,value),!(!deviceId||!value)&&new Promise(resolve=>{const{isAndroid:isAndroid,isIOS:isIOS}=commonfun.getOS(),platform=commonfun.getPlatform();console.log("platform: ",platform),console.log("isAndroid, isIOS: ",isAndroid,isIOS);const writeType="mp-weixin"===platform||isAndroid?"writeNoResponse":"write";uni.writeBLECharacteristicValue({deviceId:deviceId,serviceId:"0000FF00-0000-1000-8000-00805F9B34FB",characteristicId:"0000FF02-0000-1000-8000-00805F9B34FB",writeType:writeType,value:value,success:res=>{console.error("res: 写入成功",res),resolve(!0)},fail:e=>{console.error("写入失败",e),resolve(!1)}}),isIOS&&setTimeout(()=>resolve(!0),50)})}exports.getData=async(deviceId,{command:command,commandVerifyHandler:commandVerifyHandler=hexArr=>({verified:!1,pkgLen:null}),pkgVerifyHandler:pkgVerifyHandler=pkg=>({verified:!1}),maxRetries:maxRetries=2,retryInterval:retryInterval=300},tag="")=>{if(!deviceId)throw new Error("deviceId is required");if(!command||command.length<=0)throw new Error("command is required");return new Promise((resolve,reject)=>{let isCompleted=!1,timeoutId=null,responsed=!1,len=null,pkg=[];const cmdContent=BleDataProcess.hexArr2ab(command),cleanup=()=>{isCompleted||(isCompleted=!0,clearTimeout(timeoutId),commonfun.eventBus.off("setBleChangedCharacteristicValue",dataHandler))},dataHandler=payload=>{if(!payload||payload.deviceId!==deviceId||!payload.value)return;const hexArr=BleDataProcess.ab2decimalArr(payload.value);if(console.log("hexArr: ",hexArr),console.warn(tag,"接收到数据:",BleDataProcess.hexArr2string(hexArr)),0!==hexArr.length){if(null===len){const{verified:verified,pkgLen:pkgLen}=commandVerifyHandler(hexArr);console.log("指令验证结果:",{verified:verified,pkgLen:pkgLen}),verified&&(len=pkgLen)}if(len){if(pkg=[...pkg,...hexArr],console.log("当前数据包:",pkg,`长度: ${pkg.length}/${len}`),pkg.length>=len){pkg=pkg.slice(0,len);const{verified:verified}=pkgVerifyHandler(pkg);console.log("数据包验证结果:",{verified:verified}),verified?(responsed=!0,cleanup(),resolve([...pkg])):(len=null,pkg=[])}}else pkg=[]}},writeToDevice=async(attempt=1)=>{try{console.warn(tag,`第${attempt}次写入指令:`,command.join("").replace(/0x/g,"").toUpperCase());const writeSucceed=await async function(deviceId,value){return console.log("value: ",value),console.log("deviceId: ",deviceId),!(!deviceId||!value)&&new Promise(async resolve=>{const n=Math.ceil(value.byteLength/20);let res;for(let i=0;i<n;i++){const _value=value.slice(20*i,20*(i+1));if(console.log("分包写入_value: ",_value),await BleDataProcess.sleep(150),res=await _writeAsync(deviceId,_value),console.log(`分包写入结果 ${i+1}/${n} : ${res}`),!res)return resolve(!1)}resolve(res)})}(deviceId,cmdContent);if(console.warn(tag,`第${attempt}次写入结果:`,writeSucceed?"成功":"失败"),!writeSucceed)return void(attempt<maxRetries?setTimeout(()=>writeToDevice(attempt+1),retryInterval):(cleanup(),resolve(null)));await BleDataProcess.sleep(retryInterval),!responsed&&attempt<maxRetries?(console.log(tag,`未收到响应,准备第${attempt+1}次重试`),writeToDevice(attempt+1)):responsed||(console.warn(tag,`达到最大重试次数(${maxRetries}),未收到响应`),cleanup(),resolve(null))}catch(error){console.error(tag,"写入过程发生错误:",error),cleanup(),reject(error)}};timeoutId=setTimeout(()=>{console.warn(tag,"操作超时"),cleanup(),resolve(null)},(maxRetries+2)*retryInterval),commonfun.eventBus.on("setBleChangedCharacteristicValue",dataHandler),writeToDevice().catch(error=>{cleanup(),reject(error)})})},exports.setMTUAsync=(deviceId,mtu=512,delay=2500)=>new Promise((resolve,reject)=>{try{if(commonfun.getOS().isIOS)return resolve(!0);setTimeout(async()=>{await uni.setBLEMTU({deviceId:deviceId,mtu:mtu}),resolve(!0)},delay)}catch(error){console.error(error),reject(error)}});
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var BleDataProcess=require("../BleDataProcess.js"),commonfun=require("../commonfun.js");async function _writeAsync(deviceId,value){return console.log("deviceId, value: ",deviceId,value),!(!deviceId||!value)&&new Promise(resolve=>{const{isAndroid:isAndroid,isIOS:isIOS}=commonfun.getOS(),platform=commonfun.getPlatform();console.log("platform: ",platform),console.log("isAndroid, isIOS: ",isAndroid,isIOS);const writeType="mp-weixin"===platform||isAndroid?"writeNoResponse":"write";console.log("writeType: ",writeType),uni.writeBLECharacteristicValue({deviceId:deviceId,serviceId:"0000FF00-0000-1000-8000-00805F9B34FB",characteristicId:"0000FF02-0000-1000-8000-00805F9B34FB",writeType:writeType,value:value,success:res=>{console.error("res: 写入成功",res),resolve(!0)},fail:e=>{console.error("写入失败",e),resolve(!1)}}),isIOS&&setTimeout(()=>resolve(!0),50)})}exports.getData=async(deviceId,{command:command,commandVerifyHandler:commandVerifyHandler=hexArr=>({verified:!1,pkgLen:null}),pkgVerifyHandler:pkgVerifyHandler=pkg=>({verified:!1}),maxRetries:maxRetries=2,retryInterval:retryInterval=300},tag="")=>{if(!deviceId)throw new Error("deviceId is required");if(!command||command.length<=0)throw new Error("command is required");return new Promise((resolve,reject)=>{let isCompleted=!1,timeoutId=null,responsed=!1,len=null,pkg=[];const cmdContent=BleDataProcess.hexArr2ab(command),cleanup=()=>{isCompleted||(isCompleted=!0,clearTimeout(timeoutId),commonfun.eventBus.off("setBleChangedCharacteristicValue",dataHandler))},dataHandler=payload=>{if(!payload||payload.deviceId!==deviceId||!payload.value)return;const hexArr=BleDataProcess.ab2decimalArr(payload.value);if(console.log("hexArr: ",hexArr),console.warn(tag,"接收到数据:",BleDataProcess.hexArr2string(hexArr)),0!==hexArr.length){if(null===len){const{verified:verified,pkgLen:pkgLen}=commandVerifyHandler(hexArr);console.log("指令验证结果:",{verified:verified,pkgLen:pkgLen}),verified&&(len=pkgLen)}if(len){if(pkg=[...pkg,...hexArr],console.log("当前数据包:",pkg,`长度: ${pkg.length}/${len}`),pkg.length>=len){pkg=pkg.slice(0,len);const{verified:verified}=pkgVerifyHandler(pkg);console.log("数据包验证结果:",{verified:verified}),verified?(responsed=!0,cleanup(),resolve([...pkg])):(len=null,pkg=[])}}else pkg=[]}},writeToDevice=async(attempt=1)=>{try{console.warn(tag,`第${attempt}次写入指令:`,command.join("").replace(/0x/g,"").toUpperCase());const writeSucceed=await async function(deviceId,value){return console.log("value: ",value),console.log("deviceId: ",deviceId),!(!deviceId||!value)&&new Promise(async resolve=>{const n=Math.ceil(value.byteLength/20);let res;for(let i=0;i<n;i++){const _value=value.slice(20*i,20*(i+1));if(console.log("分包写入_value: ",_value),await BleDataProcess.sleep(150),res=await _writeAsync(deviceId,_value),console.log(`分包写入结果 ${i+1}/${n} : ${res}`),!res)return resolve(!1)}resolve(res)})}(deviceId,cmdContent);if(console.warn(tag,`第${attempt}次写入结果:`,writeSucceed?"成功":"失败"),!writeSucceed)return void(attempt<maxRetries?setTimeout(()=>writeToDevice(attempt+1),retryInterval):(cleanup(),resolve(null)));await BleDataProcess.sleep(retryInterval),!responsed&&attempt<maxRetries?(console.log(tag,`未收到响应,准备第${attempt+1}次重试`),writeToDevice(attempt+1)):responsed||(console.warn(tag,`达到最大重试次数(${maxRetries}),未收到响应`),cleanup(),resolve(null))}catch(error){console.error(tag,"写入过程发生错误:",error),cleanup(),reject(error)}};timeoutId=setTimeout(()=>{console.warn(tag,"操作超时"),cleanup(),resolve(null)},(maxRetries+2)*retryInterval),commonfun.eventBus.on("setBleChangedCharacteristicValue",dataHandler),writeToDevice().catch(error=>{cleanup(),reject(error)})})},exports.setMTUAsync=(deviceId,mtu=512,delay=2500)=>new Promise((resolve,reject)=>{try{if(commonfun.getOS().isIOS)return resolve(!0);setTimeout(async()=>{await uni.setBLEMTU({deviceId:deviceId,mtu:mtu}),resolve(!0)},delay)}catch(error){console.error(error),reject(error)}});
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var BleDataProcess=require("../BleDataProcess.js"),BleCmdAnalysis=require("./BleCmdAnalysis.js");exports.getDDA420Async=async deviceId=>{const _command=["0x20","0x00"],checks=BleDataProcess.generateCrcCheckSum(_command),command=["0xdd","0xa4",..._command,...checks,"0x77"];return BleCmdAnalysis.getData(deviceId,{command:command,commandVerifyHandler:hexArr=>({verified:221==hexArr[0]&&32==hexArr[1],pkgLen:hexArr[3]+7}),pkgVerifyHandler:pkg=>{const len=pkg.length,[c1,c2]=BleDataProcess.generateCrcCheckSum(pkg.slice(2,len-3)),[_c1,_c2]=[pkg[len-3],pkg[len-2]];return{verified:c1==_c1&&c2==_c2}}},"DDA420")},exports.getDDA421Async=async deviceId=>{const _command=["0x21","0x00"],checks=BleDataProcess.generateCrcCheckSum(_command),command=["0xdd","0xa4",..._command,...checks,"0x77"];return(void 0).getData(deviceId,{command:command,commandVerifyHandler:hexArr=>({verified:221==hexArr[0]&&33==hexArr[1],pkgLen:hexArr[3]+7}),pkgVerifyHandler:pkg=>{const len=pkg.length,[c1,c2]=BleDataProcess.generateCrcCheckSum(pkg.slice(2,len-3)),[_c1,_c2]=[pkg[len-3],pkg[len-2]];return{verified:c1==_c1&&c2==_c2}}},"DDA421")},exports.getDDA422Async=async(deviceId,startReg,endReg)=>{const startRegHex=BleDataProcess.decimalToHex(startReg,4),endRegHex=BleDataProcess.decimalToHex(endReg,4),_command=["0x22","0x04",...[parseInt(startRegHex.slice(0,2),16),parseInt(startRegHex.slice(2,4),16)],...[parseInt(endRegHex.slice(0,2),16),parseInt(endRegHex.slice(2,4),16)]],checks=BleDataProcess.generateCrcCheckSum(_command),command=["0xDD","0xA4",..._command,...checks,"0x77"];return BleCmdAnalysis.getData(deviceId,{command:command,commandVerifyHandler:hexArr=>({verified:221==hexArr[0]&&34==hexArr[1],pkgLen:hexArr[3]+7}),pkgVerifyHandler:pkg=>{const len=pkg.length,[c1,c2]=BleDataProcess.generateCrcCheckSum(pkg.slice(2,len-3)),[_c1,_c2]=[pkg[len-3],pkg[len-2]];return{verified:c1==_c1&&c2==_c2}}},"DDA422")},exports.getDDA423Async=async(deviceId,startReg,endReg,values,valuesLength)=>{const startRegHex=BleDataProcess.decimalToHex(startReg,4),startRegArr=[parseInt(startRegHex.slice(0,2),16),parseInt(startRegHex.slice(2,4),16)],endRegHex=BleDataProcess.decimalToHex(endReg,4),endRegArr=[parseInt(endRegHex.slice(0,2),16),parseInt(endRegHex.slice(2,4),16)],valueRegHex=BleDataProcess.decimalToHex(values,2*valuesLength);let valueArr=[];for(let i=0;i<valuesLength;i++){const hex=valueRegHex.slice(2*i,2*i+2);valueArr.push(parseInt(hex.slice(0,2),16))}const _command=["0x23",BleDataProcess.decimalToHex(4+valuesLength,2),...startRegArr,...endRegArr,...valueArr],checks=BleDataProcess.generateCrcCheckSum(_command),command=["0xDD","0xA4",..._command,...checks,"0x77"];return BleCmdAnalysis.getData(deviceId,{command:command,commandVerifyHandler:hexArr=>({verified:221==hexArr[0]&&35==hexArr[1],pkgLen:hexArr[3]+7}),pkgVerifyHandler:pkg=>{const len=pkg.length,[c1,c2]=BleDataProcess.generateCrcCheckSum(pkg.slice(2,len-3)),[_c1,_c2]=[pkg[len-3],pkg[len-2]];return{verified:c1==_c1&&c2==_c2}}},"DDA423")},exports.getDDA425Async=async(deviceId,type)=>{const _command=["0x25","0x01",type],checks=BleDataProcess.generateCrcCheckSum(_command),command=["0xDD","0xA4",..._command,...checks,"0x77"];return console.log("command: ",command),BleCmdAnalysis.getData(deviceId,{command:command,commandVerifyHandler:hexArr=>({verified:221==hexArr[0]&&37==hexArr[1],pkgLen:hexArr[3]+7}),pkgVerifyHandler:pkg=>({verified:!0})},"DDA425")},exports.getDDA426Async=async(deviceId,testMode=0,outputVoltage=0,outputCurrent=0)=>{const clamp32=v=>((v=Number(v)||0)<0&&(v=0),v>4294967295&&(v=4294967295),v);testMode=2===testMode?2:0,outputVoltage=clamp32(outputVoltage),outputCurrent=clamp32(outputCurrent);const to4Bytes=val=>{const hex=commonfun.decimalToHex(val,8);return[0,2,4,6].map(i=>parseInt(hex.slice(i,i+2),16))},voltageArr=to4Bytes(outputVoltage),currentArr=to4Bytes(outputCurrent),_command=["0x26",`0x${commonfun.decimalToHex(9,2)}`,255&testMode,...voltageArr,...currentArr].map(o=>"number"==typeof o?`0x${("00"+o.toString(16)).slice(-2)}`:o),_commandNums=_command.map(h=>parseInt(h,16)),checks=BleDataProcess.generateCrcCheckSum(_commandNums),command=["0xDD","0xA4",..._command,...checks,"0x77"];return BleCmdAnalysis.getData(deviceId,{command:command,commandVerifyHandler:hexArr=>({verified:221==hexArr[0]&&38==hexArr[1],pkgLen:hexArr[3]+7}),pkgVerifyHandler:pkg=>({verified:!0})},"DDA426(充电测试)")},exports.getDDA427Async=async(deviceId,startTime,endTime,granularity=2,type=1)=>{const startTimeHex=startTime.toString(16).padStart(8,"0"),endTimeHex=endTime.toString(16).padStart(8,"0"),startTimeArr=[parseInt(startTimeHex.slice(0,2),16),parseInt(startTimeHex.slice(2,4),16),parseInt(startTimeHex.slice(4,6),16),parseInt(startTimeHex.slice(6,8),16)],endTimeArr=[parseInt(endTimeHex.slice(0,2),16),parseInt(endTimeHex.slice(2,4),16),parseInt(endTimeHex.slice(4,6),16),parseInt(endTimeHex.slice(6,8),16)],historyType=BleDataProcess.decimalToHex(type,2),granularityArr=BleDataProcess.decimalToHex(granularity,2),_command=["0x27","0x0A",...startTimeArr,...endTimeArr,historyType,granularityArr],checks=BleDataProcess.generateCrcCheckSum(_command),command=["0xDD","0xA4",..._command,...checks,"0x77"];return console.log("getDDA427Async getDDA427Async",startTimeHex,endTimeHex,startTimeArr,endTimeArr,granularity,command),BleCmdAnalysis.getData(deviceId,{command:command,commandVerifyHandler:hexArr=>({verified:221==hexArr[0]&&39==hexArr[1],pkgLen:hexArr[3]+7}),pkgVerifyHandler:pkg=>{const len=pkg.length,[c1,c2]=BleDataProcess.generateCrcCheckSum(pkg.slice(2,len-3)),[_c1,_c2]=[pkg[len-3],pkg[len-2]];return{verified:c1==_c1&&c2==_c2}}},"DDA427")},exports.getDDA429Async=async(deviceId,id)=>{const idHex=BleDataProcess.decimalToHex(id,8),_command=["0x29","0x04",...[parseInt(idHex.slice(0,2),16),parseInt(idHex.slice(2,4),16),parseInt(idHex.slice(4,6),16),parseInt(idHex.slice(4,6),16),parseInt(idHex.slice(6,8),16)]],checks=BleDataProcess.generateCrcCheckSum(_command),command=["0xdd","0xa4",..._command,...checks,"0x77"];return BleCmdAnalysis.getData(deviceId,{command:command,commandVerifyHandler:hexArr=>{if(221!=hexArr[0]||41!=hexArr[1])return{verified:!1,pkgLen:null};if(hexArr.length<8)return{verified:!1,pkgLen:null};if(hexArr.length>=36){const respIdHex=BleDataProcess.decimalToHex(hexArr[32])+BleDataProcess.decimalToHex(hexArr[33])+BleDataProcess.decimalToHex(hexArr[34])+BleDataProcess.decimalToHex(hexArr[35]);if(BleDataProcess.hexToDecimal(respIdHex)!==id)return{verified:!1,pkgLen:null}}return{verified:!0,pkgLen:hexArr[3]+7}},pkgVerifyHandler:pkg=>{const len=pkg.length,[c1,c2]=BleDataProcess.generateCrcCheckSum(pkg.slice(2,len-3)),[_c1,_c2]=[pkg[len-3],pkg[len-2]];return{verified:c1==_c1&&c2==_c2}}},"DDA429")},exports.resolveDDA420=data=>{if(!data)return null;const dataStr=BleDataProcess.hexArr2string(data);let n=4;const workStatus=data[n++],chargeStatus=data[n++],chargeVoltage=BleDataProcess.hexToDecimal(BleDataProcess.decimalToHex(data[n++])+BleDataProcess.decimalToHex(data[n++])+BleDataProcess.decimalToHex(data[n++])+BleDataProcess.decimalToHex(data[n++])),chargeElectricity=BleDataProcess.hexToDecimal(BleDataProcess.decimalToHex(data[n++])+BleDataProcess.decimalToHex(data[n++])+BleDataProcess.decimalToHex(data[n++])+BleDataProcess.decimalToHex(data[n++])),chargePower=BleDataProcess.hexToDecimal(BleDataProcess.decimalToHex(data[n++])+BleDataProcess.decimalToHex(data[n++])),chargeTemperature=BleDataProcess.hexToDecimal(BleDataProcess.decimalToHex(data[n++])+BleDataProcess.decimalToHex(data[n++]))/10,chargeCapacity=BleDataProcess.hexToDecimal(BleDataProcess.decimalToHex(data[n++])+BleDataProcess.decimalToHex(data[n++])+BleDataProcess.decimalToHex(data[n++])+BleDataProcess.decimalToHex(data[n++])),chargeTime=BleDataProcess.hexToDecimal(BleDataProcess.decimalToHex(data[n++])+BleDataProcess.decimalToHex(data[n++])),chargeRemainTime=BleDataProcess.hexToDecimal(BleDataProcess.decimalToHex(data[n++])+BleDataProcess.decimalToHex(data[n++])),chargeCompleteTime=BleDataProcess.hexToDecimal(BleDataProcess.decimalToHex(data[n++])+BleDataProcess.decimalToHex(data[n++])),outputVoltagePercent=BleDataProcess.hexToDecimal(BleDataProcess.decimalToHex(data[n++])+BleDataProcess.decimalToHex(data[n++])+BleDataProcess.decimalToHex(data[n++])+BleDataProcess.decimalToHex(data[n++])),outputElectricityPercent=BleDataProcess.hexToDecimal(BleDataProcess.decimalToHex(data[n++])+BleDataProcess.decimalToHex(data[n++])+BleDataProcess.decimalToHex(data[n++])+BleDataProcess.decimalToHex(data[n++])),outputVoltage=BleDataProcess.hexToDecimal(BleDataProcess.decimalToHex(data[n++])+BleDataProcess.decimalToHex(data[n++])+BleDataProcess.decimalToHex(data[n++])+BleDataProcess.decimalToHex(data[n++])),outputElectricity=BleDataProcess.hexToDecimal(BleDataProcess.decimalToHex(data[n++])+BleDataProcess.decimalToHex(data[n++])+BleDataProcess.decimalToHex(data[n++])+BleDataProcess.decimalToHex(data[n++])),batteryVoltage=BleDataProcess.hexToDecimal(BleDataProcess.decimalToHex(data[n++])+BleDataProcess.decimalToHex(data[n++])+BleDataProcess.decimalToHex(data[n++])+BleDataProcess.decimalToHex(data[n++])),swtichStatusArr=BleDataProcess.hexToDecimal(BleDataProcess.decimalToHex(data[n++])+BleDataProcess.decimalToHex(data[n++])).toString(2).padStart(16,"0").split("").reverse(),chargeSwitch="1"==swtichStatusArr[0],preChargeSwitch="1"==swtichStatusArr[1],fanSwitch="1"==swtichStatusArr[2],protectStatusArr=BleDataProcess.hexToDecimal(BleDataProcess.decimalToHex(data[n++])+BleDataProcess.decimalToHex(data[n++])+BleDataProcess.decimalToHex(data[n++])+BleDataProcess.decimalToHex(data[n++])).toString(2).padStart(32,"0").split("").reverse();let protectStatusIndexs=[];for(let i=0;i<protectStatusArr.length;i++)"1"==protectStatusArr[i]&&protectStatusIndexs.push(i);const alarmStatusArr=BleDataProcess.hexToDecimal(BleDataProcess.decimalToHex(data[n++])+BleDataProcess.decimalToHex(data[n++])+BleDataProcess.decimalToHex(data[n++])+BleDataProcess.decimalToHex(data[n++])).toString(2).padStart(32,"0").split("").reverse();let alarmStatusIndexs=[];for(let i=0;i<alarmStatusArr.length;i++)"1"==alarmStatusArr[i]&&alarmStatusIndexs.push(i);return{dataStr:dataStr,workStatus:workStatus,chargeStatus:chargeStatus,chargeVoltage:chargeVoltage,chargeElectricity:chargeElectricity,chargePower:chargePower,chargeTemperature:chargeTemperature,chargeCapacity:chargeCapacity,chargeTime:chargeTime,chargeRemainTime:chargeRemainTime,chargeCompleteTime:chargeCompleteTime,outputVoltagePercent:outputVoltagePercent,outputElectricityPercent:outputElectricityPercent,outputVoltage:outputVoltage,outputElectricity:outputElectricity,batteryVoltage:batteryVoltage,chargeSwitch:chargeSwitch,preChargeSwitch:preChargeSwitch,fanSwitch:fanSwitch,protectStatusIndexs:protectStatusIndexs,alarmStatusIndexs:alarmStatusIndexs,communicationMode:data[n++]}},exports.resolveDDA421=data=>{if(!data)return null;const dataStr=BleDataProcess.hexArr2string(data),batteryVoltageHex=BleDataProcess.decimalToHex(data[4])+BleDataProcess.decimalToHex(data[5])+BleDataProcess.decimalToHex(data[6])+BleDataProcess.decimalToHex(data[7]),batteryVoltage=BleDataProcess.hexToDecimal(batteryVoltageHex),batteryCurrentHex=BleDataProcess.decimalToHex(data[8])+BleDataProcess.decimalToHex(data[9])+BleDataProcess.decimalToHex(data[10])+BleDataProcess.decimalToHex(data[11]),batteryCurrent=BleDataProcess.hexToDecimal(batteryCurrentHex),batteryType=data[12],batterySeries=data[13],batteryCapacityHex=BleDataProcess.decimalToHex(data[14])+BleDataProcess.decimalToHex(data[15])+BleDataProcess.decimalToHex(data[16])+BleDataProcess.decimalToHex(data[17]),batteryCapacity=BleDataProcess.hexToDecimal(batteryCapacityHex),batterySOC=data[18],batteryTempHex=BleDataProcess.decimalToHex(data[19])+BleDataProcess.decimalToHex(data[20]),batteryTemperature=BleDataProcess.hexToDecimal(batteryTempHex)/10,heatingStatus=data[21],heatingCurrentHex=BleDataProcess.decimalToHex(data[22])+BleDataProcess.decimalToHex(data[23])+BleDataProcess.decimalToHex(data[24])+BleDataProcess.decimalToHex(data[25]),heatingCurrent=BleDataProcess.hexToDecimal(heatingCurrentHex),protectStatusHex=BleDataProcess.decimalToHex(data[26])+BleDataProcess.decimalToHex(data[27]),protectStatusArr=BleDataProcess.hexToDecimal(protectStatusHex).toString(2).padStart(16,"0").split("").reverse();let protectStatusIndexs=[];for(let i=0;i<protectStatusArr.length;i++)"1"==protectStatusArr[i]&&protectStatusIndexs.push(i);const alarmStatusHex=BleDataProcess.decimalToHex(data[28])+BleDataProcess.decimalToHex(data[29]),alarmStatusArr=BleDataProcess.hexToDecimal(alarmStatusHex).toString(2).padStart(16,"0").split("").reverse();let alarmStatusIndexs=[];for(let i=0;i<alarmStatusArr.length;i++)"1"==alarmStatusArr[i]&&alarmStatusIndexs.push(i);return{dataStr:dataStr,batteryVoltage:batteryVoltage,batteryCurrent:batteryCurrent,batteryType:batteryType,batterySeries:batterySeries,batteryCapacity:batteryCapacity,batterySOC:batterySOC,batteryTemperature:batteryTemperature,heatingStatus:heatingStatus,heatingCurrent:heatingCurrent,protectStatusIndexs:protectStatusIndexs,alarmStatusIndexs:alarmStatusIndexs}},exports.resolveDDA422=data=>{if(!data)return null;const dataStr=BleDataProcess.hexArr2string(data),startRegHex=BleDataProcess.decimalToHex(data[4])+BleDataProcess.decimalToHex(data[5]),startReg=BleDataProcess.hexToDecimal(startRegHex),endRegHex=BleDataProcess.decimalToHex(data[6])+BleDataProcess.decimalToHex(data[7]);return{dataStr:dataStr,startReg:startReg,endReg:BleDataProcess.hexToDecimal(endRegHex),regData:data.slice(8,data.length-3)}},exports.resolveDDA423=data=>{if(!data)return null;return{dataStr:BleDataProcess.hexArr2string(data),status:BleDataProcess.hex2string(data[2])}},exports.resolveDDA425=data=>{if(!data)return null;return{dataStr:BleDataProcess.hexArr2string(data),status:BleDataProcess.hex2string(data[2])}},exports.resolveDDA426=data=>{if(!data)return null;return{dataStr:BleDataProcess.hexArr2string(data),status:BleDataProcess.hex2string(data[2])}},exports.resolveDDA427=data=>{if(!data)return null;const dataStr=BleDataProcess.hexArr2string(data),startTimeHex=BleDataProcess.decimalToHex(data[4])+BleDataProcess.decimalToHex(data[5])+BleDataProcess.decimalToHex(data[6])+BleDataProcess.decimalToHex(data[7]),startTime=BleDataProcess.hexToDecimal(startTimeHex),endTimeHex=BleDataProcess.decimalToHex(data[8])+BleDataProcess.decimalToHex(data[9])+BleDataProcess.decimalToHex(data[10])+BleDataProcess.decimalToHex(data[11]),endTime=BleDataProcess.hexToDecimal(endTimeHex),historyType=data[12],granularity=data[13],count=data[14];let history=[];for(let i=0;i<count;i++){const base=15+8*i,voltageHex=BleDataProcess.decimalToHex(data[base])+BleDataProcess.decimalToHex(data[base+1])+BleDataProcess.decimalToHex(data[base+2])+BleDataProcess.decimalToHex(data[base+3]),voltage=BleDataProcess.hexToDecimal(voltageHex),currentHex=BleDataProcess.decimalToHex(data[base+4])+BleDataProcess.decimalToHex(data[base+5])+BleDataProcess.decimalToHex(data[base+6])+BleDataProcess.decimalToHex(data[base+7]),current=BleDataProcess.hexToDecimal(currentHex);history.push({current:current,voltage:voltage})}return console.log("historyType",historyType),{dataStr:dataStr,startTime:startTime,endTime:endTime,historyType:historyType,granularity:granularity,count:count,history:history}},exports.resolveDDA429=data=>{if(!data)return null;const dataStr=BleDataProcess.hexArr2string(data);let n=4;const workStatus=data[n++],chargeStatus=data[n++],chargeVoltage=BleDataProcess.hexToDecimal(BleDataProcess.decimalToHex(data[n++])+BleDataProcess.decimalToHex(data[n++])+BleDataProcess.decimalToHex(data[n++])+BleDataProcess.decimalToHex(data[n++])),chargeElectricity=BleDataProcess.hexToDecimal(BleDataProcess.decimalToHex(data[n++])+BleDataProcess.decimalToHex(data[n++])+BleDataProcess.decimalToHex(data[n++])+BleDataProcess.decimalToHex(data[n++])),chargePower=BleDataProcess.hexToDecimal(BleDataProcess.decimalToHex(data[n++])+BleDataProcess.decimalToHex(data[n++])),chargeTemperature=BleDataProcess.hexToDecimal(BleDataProcess.decimalToHex(data[n++])+BleDataProcess.decimalToHex(data[n++]))/10,chargeCapacity=BleDataProcess.hexToDecimal(BleDataProcess.decimalToHex(data[n++])+BleDataProcess.decimalToHex(data[n++])+BleDataProcess.decimalToHex(data[n++])+BleDataProcess.decimalToHex(data[n++])),chargeTime=BleDataProcess.hexToDecimal(BleDataProcess.decimalToHex(data[n++])+BleDataProcess.decimalToHex(data[n++])),chargeRemainTime=BleDataProcess.hexToDecimal(BleDataProcess.decimalToHex(data[n++])+BleDataProcess.decimalToHex(data[n++])),chargeCompleteTime=BleDataProcess.hexToDecimal(BleDataProcess.decimalToHex(data[n++])+BleDataProcess.decimalToHex(data[n++])),outputVoltagePercent=data[n++],outputElectricityPercent=data[n++],id1=BleDataProcess.hexToDecimal(BleDataProcess.decimalToHex(data[n++])+BleDataProcess.decimalToHex(data[n++])+BleDataProcess.decimalToHex(data[n++])+BleDataProcess.decimalToHex(data[n++])),outputElectricity=BleDataProcess.hexToDecimal(BleDataProcess.decimalToHex(data[n++])+BleDataProcess.decimalToHex(data[n++])+BleDataProcess.decimalToHex(data[n++])+BleDataProcess.decimalToHex(data[n++])),id=BleDataProcess.hexToDecimal(BleDataProcess.decimalToHex(data[n++])+BleDataProcess.decimalToHex(data[n++])+BleDataProcess.decimalToHex(data[n++])+BleDataProcess.decimalToHex(data[n++])),swtichStatusArr=BleDataProcess.hexToDecimal(BleDataProcess.decimalToHex(data[n++])+BleDataProcess.decimalToHex(data[n++])).toString(2).padStart(16,"0").split("").reverse(),chargeSwitch="1"==swtichStatusArr[0],preChargeSwitch="1"==swtichStatusArr[1],fanSwitch="1"==swtichStatusArr[2],protectStatusArr=BleDataProcess.hexToDecimal(BleDataProcess.decimalToHex(data[n++])+BleDataProcess.decimalToHex(data[n++])+BleDataProcess.decimalToHex(data[n++])+BleDataProcess.decimalToHex(data[n++])).toString(2).padStart(32,"0").split("").reverse();let protectStatusIndexs=[];for(let i=0;i<protectStatusArr.length;i++)"1"==protectStatusArr[i]&&protectStatusIndexs.push(i);const alarmStatusArr=BleDataProcess.hexToDecimal(BleDataProcess.decimalToHex(data[n++])+BleDataProcess.decimalToHex(data[n++])+BleDataProcess.decimalToHex(data[n++])+BleDataProcess.decimalToHex(data[n++])).toString(2).padStart(32,"0").split("").reverse();let alarmStatusIndexs=[];for(let i=0;i<alarmStatusArr.length;i++)"1"==alarmStatusArr[i]&&alarmStatusIndexs.push(i);return{dataStr:dataStr,workStatus:workStatus,chargeStatus:chargeStatus,chargeVoltage:chargeVoltage,chargeElectricity:chargeElectricity,chargePower:chargePower,chargeTemperature:chargeTemperature,chargeCapacity:chargeCapacity,chargeTime:chargeTime,chargeRemainTime:chargeRemainTime,chargeCompleteTime:chargeCompleteTime,outputVoltagePercent:outputVoltagePercent,outputElectricityPercent:outputElectricityPercent,id:id,outputElectricity:outputElectricity,id1:id1,chargeSwitch:chargeSwitch,preChargeSwitch:preChargeSwitch,fanSwitch:fanSwitch,protectStatusIndexs:protectStatusIndexs,alarmStatusIndexs:alarmStatusIndexs}};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var SHA256=require("crypto-js/sha256"),mqtt=require("mqtt/dist/mqtt.min.js"),BleCmdDD=require("./BleCmdAnalysis/BleCmdDD.js"),BleCmdFFAA=require("./BleCmdAnalysis/BleCmdFFAA.js"),BleCmdHVES=require("./BleCmdAnalysis/BleCmdHVES.js"),BleDataProcess=require("./BleDataProcess.js"),rsaEncrypt=require("./rsaEncrypt.js"),Transfer=require("./Transfer.js");function _interopDefaultLegacy(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var SHA256__default=_interopDefaultLegacy(SHA256),mqtt__default=_interopDefaultLegacy(mqtt);exports.MqttServer=class{constructor({mqttClient:mqttClient={},MQTT_HOST:MQTT_HOST="wxs://mqtt.jiabaida.com/mqtt",DELAY_TIME:DELAY_TIME=300,networkModelUrl:networkModelUrl="https://cloud.jiabaida.com/bluetooth/server/device/networkModel",request:request}){this.timer=null,this.productKey="bms_wifi",this.is0f=!1,this.publishObj={},this.cmdCode="",this.callbackId="",this.mqttCode="",this.mqttPublish=!1,this.mqttClient=mqttClient,this.MQTT_HOST=MQTT_HOST,this.DELAY_TIME=DELAY_TIME,this.networkModelUrl=networkModelUrl,this.request=request}async getParams(item){try{return await this.request({url:`${this.networkModelUrl}?macAddr=${item.macAddr}`,method:"get"})}catch(error){throw console.error("getnetworkModel-error",error),error}}async connectMqtt(deviceObj){try{const modalData=await this.getParams(deviceObj);if(!modalData||200!==modalData.data.code)return;const mqttParam=modalData.data.data,clientId=rsaEncrypt.decrypt(mqttParam.clientId),username=mqttParam.mqttUsername,password=rsaEncrypt.decrypt(mqttParam.mqttSecret);console.log("连接 MQTT...");const options={clean:!0,connectTimeout:4e3,clientId:clientId,username:username,password:SHA256__default.default(password).toString(),deviceId:deviceObj.deviceId},client=mqtt__default.default.connect(this.MQTT_HOST,options);console.log("MQTT 客户端创建成功:",client),client.on("connect",res=>{console.log("res连接成功",res),client.productKey=this.productKey,this.handleMqttConnect(client,deviceObj)}),client.on("message",(topic,message)=>{this.handleMqttMessage(topic,message,client)}),client.on("reconnect",res=>console.log("MQTT 重连中...",res,client)),client.on("close",res=>this.handleMqttClose(client,res)),client.on("offline",res=>console.log("MQTT 脱机状态",res,client)),client.on("error",res=>console.error("MQTT 连接错误",res,client)),client.on("disconnect",res=>console.log("MQTT 断开连接",res,client))}catch(e){console.error("MQTT 连接异常:",e)}}handleMqttConnect(client,deviceObj){console.log("MQTT 连接成功 client",client),console.log("MQTT 连接成功 deviceObj",deviceObj),this.storeMqttClient(client),this.publishInOrder(client,deviceObj).then(()=>this.subscribeInOrder(client))}storeMqttClient(client){this.mqttClient[`${client.options.deviceId}_mqtt`]=client,console.log("存储的 MQTT 客户端:",this.mqttClient)}getTopicsAndMessages(client,deviceObj){const{productType:productType,soc:soc,moduleType:moduleType,macAddr:macAddr}=deviceObj,message=JSON.stringify({productKey:productType,soc:soc,moduleTypeKey:moduleType,macAddr:macAddr});return[{topic:`/${client.productKey}/${client.options.clientId}/device/login`,message:message}]}async publishInOrder(client,deviceObj){const topicsAndMessages=this.getTopicsAndMessages(client,deviceObj);try{for(const item of topicsAndMessages)await new Promise(resolve=>{client.publish(item.topic,item.message,()=>{resolve()})})}catch(error){console.error(`处理发布时出现错误: ${error}`)}}getSubscribeTopics(client){const{productKey:productKey}=client,clientId=client.options.clientId;return[`/${productKey}/${clientId}/device/login/reply`,`/${productKey}/${clientId}/device/passthrough/reply`,`/${productKey}/${clientId}/plat/cmd`,`/${productKey}/${clientId}/plat/passthrough`]}async subscribeInOrder(client){const subscribeTopics=this.getSubscribeTopics(client);try{for(const topic of subscribeTopics)await new Promise((resolve,reject)=>{client.subscribe(topic,err=>{err?reject(err):resolve()})})}catch(error){console.error(`订阅主题时出现错误: ${error}`)}}handleMqttMessage(topic,message,client){const clientId=topic.split("/")[2];topic!==`/${(client=Object.values(this.mqttClient).find(c=>c?.options?.clientId===clientId)||client).productKey}/${client.options.clientId}/plat/passthrough`&&topic!==`/${client.productKey}/${client.options.clientId}/plat/cmd`||this.processMessageAsync(client,message.toString())}async processMessageAsync(client,message){const msg=JSON.parse(message);this.callbackId=msg.callbackId,this.cmdCode=msg.cmdCode;let resultArray=[],codeValue=[];if("jbdPWD"===this.cmdCode){const cmdContent={2:"FFAA23010125",3:"FFAA1F010121",4:"FFAA20010122",5:"FFAA23010226"}[msg.value];codeValue=cmdContent?cmdContent.split(","):[]}else codeValue=msg.value?msg.value.split(","):[],this.is0f=2===codeValue.length;resultArray=codeValue[0]?codeValue[0].match(/.{1,2}/g):[];try{"FF"===resultArray[0]?.toUpperCase()&&"AA"===resultArray[1]?.toUpperCase()||"78"===resultArray[1]?.toUpperCase()||resultArray[1]?.toUpperCase();const publishObj={deviceId:client.options.deviceId,clientId:client.options.clientId,productKey:client.productKey,callbackId:this.callbackId,cmdCode:this.cmdCode,is0f:this.is0f,isLast:msg.isLast};this.publishObj=publishObj,this.cmdCode.toLowerCase().includes("wifi_")?await this.publishATHandle(msg.value):(this.writePublishInfoCmd(resultArray),await BleDataProcess.sleep(this.DELAY_TIME))}catch(error){console.error("error: 处理后台发指令错误",error)}}async publishATHandle(ATvalue){const{deviceId:deviceId,cmdCode:cmdCode,callbackId:callbackId,productKey:productKey,clientId:clientId,isLast:isLast}=this.publishObj,client=this.mqttClient[`${deviceId}_mqtt`];try{if(client){const hex=await BleCmdFFAA.getFFAA80Async(deviceId,ATvalue),res=BleCmdFFAA.resolveFFAA80(hex);if(res&&res.moduleVersion){const value=res.moduleVersion;client.publish(`/${productKey}/${clientId}/plat/cmd/reply`,JSON.stringify({value:value,cmdCode:cmdCode,callbackId:callbackId}),()=>{})}}isLast&&(await BleDataProcess.sleep(300),this.mqttPublish=!1,uni.removeStorageSync&&uni.removeStorageSync(`${deviceId}_mqttPublish`))}catch(error){console.error(error)}}handleMqttClose(client,res){console.log("MQTT 连接关闭",res,client),client.end(()=>{this.mqttClient[`${client.options.deviceId}_mqtt`]=null})}async publishHandle(value,baseValue,voltageValue){const client=this.mqttClient[`${this.publishObj.deviceId}_mqtt`];this.publishObj.is0f&&(value=baseValue+","+voltageValue);const msg=JSON.stringify({value:value,cmdCode:this.publishObj.cmdCode,callbackId:this.publishObj.callbackId});client&&client.publish(`/${this.publishObj.productKey}/${this.publishObj.clientId}/plat/passthrough/reply`,msg,()=>{}),this.publishObj.isLast&&(await BleDataProcess.sleep(300),this.mqttPublish=!1,uni.removeStorageSync&&uni.removeStorageSync(`${this.publishObj.deviceId}_mqttPublish`))}publishPassthroughHandle({value:value,cmdCode:cmdCode},deviceId,timeOffset=3e4){const client=this.mqttClient[`${deviceId}_mqtt`];if(client){const clientTime=(new Date).getTime(),{laseCmdCode:laseCmdCode,lastPassthroughTime:lastPassthroughTime,clientId:clientId}=client?.options;if(laseCmdCode!=cmdCode||!(lastPassthroughTime&&clientTime-lastPassthroughTime<timeOffset)){const topic=`/${client?.productKey}/${clientId}/device/passthrough`,payload=JSON.stringify({value:value,cmdCode:cmdCode,clientTime:clientTime});client.publish(topic,payload,()=>{client.options.lastPassthroughTime=clientTime,client.options.laseCmdCode=cmdCode})}}}async writePublishInfoCmd(values){clearTimeout(this.timer),this.mqttPublish=!0,this.mqttCode=values[2];let res=null;res="FF"===values[0]?.toUpperCase()&&"AA"===values[1]?.toUpperCase()?await BleCmdFFAA.set_PlanCMD_FFAA(this.publishObj.deviceId,values.join("")):"78"===values[1]?.toUpperCase()||"50"===values[1]?.toUpperCase()?await BleCmdHVES.getCMDESInfoAsync(this.publishObj.deviceId,values.join("")):await BleCmdDD.set_PlanCMD_DD(this.publishObj.deviceId,values.join(""));const content=res?.data||[];let code=Transfer.Transfer.decimalToHex(content[1]);255==content[0]&&170==content[1]&&(code=Transfer.Transfer.decimalToHex(content[2])),console.log("code: 回复的code",code),code.toUpperCase()==this.mqttCode.toUpperCase()&&this.publishHandle(res?.dataStr),this.timer=setTimeout(()=>{this.mqttPublish=!1},3e4)}};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";function _interopDefaultLegacy(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}Object.defineProperty(exports,"__esModule",{value:!0});var JSEncrypt__default=_interopDefaultLegacy(require("jsencrypt"));const publicKey="MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBANL378k3RiZHWx5AfJqdH9xRNBmD9wGD\n2iRe41HdTNF8RUhNnHit5NpMNtGL0NPTSSpPjjI1kJfVorRvaQerUgkCAwEAAQ==";function decrypt(txt){const encryptor=new JSEncrypt__default.default;return encryptor.setPrivateKey("MIIBVgIBADANBgkqhkiG9w0BAQEFAASCAUAwggE8AgEAAkEA4cWDRXldfRIqc2Mg\nJSAiKqvRGa0v7a4fC0j3YjzpxcIArm1Ui5d9DN8Ly7vGdUnltPuy7yC9nVQuW89+\nJ6PnowIDAQABAkEApgP1/l07KJ/2BTkrxwD0/smvDaFzL+QswcCa4GsIP7iBvPna\n003yp3UGSXfEZWiQzHfehW2UHB5DIh5YbghaqQIhAPkB8LWgJlsaC8WP90ztg0nl\n+6VBLiunF6dV0Q7eJzMlAiEA6ByIpg2ZvT+X8Zzmkw32Si/Aw5VZ/ulJ5D6/MKuS\nmScCIAjcRNBxrmu3dYvGH6qhGPbcNCQhOZ9cBr9xkkrRJNvxAiEAvVapUWs+wdWi\nSIFIxSRah+G0SNcH9pyunfVhWH5cs3kCIQDGArpiAGQ4WOO+tFDqUVaDXwhQnx2H\n5OGt/FZJpmDnUw=="),encryptor.decrypt(txt)}exports.decrypt=decrypt,exports.decrypt2=function(txt){const encryptor=new JSEncrypt__default.default;return encryptor.setPrivateKey(publicKey),encryptor.decrypt(txt)},exports.decryptUsername=txt=>{const text=decrypt(txt);if(text)return text.substring(0,text.length-13)},exports.encrypt=function(txt){const encryptor=new JSEncrypt__default.default;return encryptor.setPublicKey(publicKey),encryptor.encrypt(txt)};
|
package/dist/cjs/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var array=require("./core/array.js"),BleApiManager=require("./core/BleApiManager.js"),commonfun=require("./core/commonfun.js"),keyAndPwdManager=require("./core/keyAndPwdManager.js"),OtaUpgrade=require("./core/OtaUpgrade.js"),TelinkApi=require("./core/TelinkApi.js"),Transfer=require("./core/Transfer.js"),BleDataProcess=require("./core/BleDataProcess.js"),BleCmdAnalysis=require("./core/BleCmdAnalysis/BleCmdAnalysis.js"),BleCmdFFAA=require("./core/BleCmdAnalysis/BleCmdFFAA.js"),BleCmdDD=require("./core/BleCmdAnalysis/BleCmdDD.js"),readAndSetParam=require("./core/BleCmdAnalysis/readAndSetParam.js"),BaseParamProtocol=require("./core/BleCmdAnalysis/BaseParamProtocol.js"),BleCmdHVES=require("./core/BleCmdAnalysis/BleCmdHVES.js"),ESHostProtocol=require("./core/BleCmdAnalysis/ESHostProtocol.js"),baseParamsJson=require("./core/dataJson/baseParamsJson.js");exports.chunk=array.chunk,exports.unique=array.unique,exports.checkBluetoothStatus=BleApiManager.checkBluetoothStatus,exports.checkLocationStatus=BleApiManager.checkLocationStatus,exports.connectAsync=BleApiManager.connectAsync,exports.createBLEConnection=BleApiManager.createBLEConnection,exports.disConnect=BleApiManager.disConnect,exports.foundScanDevice=BleApiManager.foundScanDevice,exports.getBLEDeviceCharacteristics=BleApiManager.getBLEDeviceCharacteristics,exports.getBLEDeviceServices=BleApiManager.getBLEDeviceServices,exports.getBluetoothAdapterState=BleApiManager.getBluetoothAdapterState,exports.getBluetoothPermission=BleApiManager.getBluetoothPermission,exports.initBle=BleApiManager.initBle,Object.defineProperty(exports,"isInit",{enumerable:!0,get:function(){return BleApiManager.isInit}}),exports.notify=BleApiManager.notify,exports.onBLECharacteristicValueChange=BleApiManager.onBLECharacteristicValueChange,exports.onBLEConnectionStateChange=BleApiManager.onBLEConnectionStateChange,exports.onBleChangedConnectionState=BleApiManager.onBleChangedConnectionState,exports.onBluetoothAdapterStateChange=BleApiManager.onBluetoothAdapterStateChange,exports.onBluetoothDeviceFound=BleApiManager.onBluetoothDeviceFound,exports.onFoundDevice=BleApiManager.onFoundDevice,exports.scanHandle=BleApiManager.scanHandle,exports.startDevicesDiscovery=BleApiManager.startDevicesDiscovery,exports.stopBluetoothDevicesDiscovery=BleApiManager.stopBluetoothDevicesDiscovery,exports.eventBus=commonfun.eventBus,exports.formatTimeHHmm=commonfun.formatTimeHHmm,exports.getOS=commonfun.getOS,exports.getPlatform=commonfun.getPlatform,exports.inArray=commonfun.inArray,exports.isEmpty=commonfun.isEmpty,exports.isNotEmpty=commonfun.isNotEmpty,exports.ALLOWED_MAC_PREFIX=keyAndPwdManager.ALLOWED_MAC_PREFIX,exports.APP_KEY_STATUS=keyAndPwdManager.APP_KEY_STATUS,exports.extractModuleInfo=keyAndPwdManager.extractModuleInfo,exports.getRandomNum=keyAndPwdManager.getRandomNum,exports.getTypeBuyCmd=keyAndPwdManager.getTypeBuyCmd,exports.handleNewAppKey=keyAndPwdManager.handleNewAppKey,exports.handleOldAppKey=keyAndPwdManager.handleOldAppKey,exports.sendAppKey=keyAndPwdManager.sendAppKey,exports.sendEnableOrVerifyKey=keyAndPwdManager.sendEnableOrVerifyKey,exports.sendOldAppKey=keyAndPwdManager.sendOldAppKey,exports.sendVerifyPwd=keyAndPwdManager.sendVerifyPwd,exports.sendWrite1LevelPwd=keyAndPwdManager.sendWrite1LevelPwd,exports.verify3LevelPassword=keyAndPwdManager.verify3LevelPassword,exports.verifyMacAddrAndKey=keyAndPwdManager.verifyMacAddrAndKey,exports.OTAUpgrade=OtaUpgrade.OTAUpgrade,exports.TelinkApi=TelinkApi.TelinkApi,exports.BLE=Transfer.BLE,exports.Logger=Transfer.Logger,exports.Observer=Transfer.Observer,exports.Transfer=Transfer.Transfer,exports.ab2decimalArr=BleDataProcess.ab2decimalArr,exports.ab2hex=BleDataProcess.ab2hex,exports.arrayBufferToHexArray=BleDataProcess.arrayBufferToHexArray,exports.base64ToHexArray=BleDataProcess.base64ToHexArray,exports.checkSum=BleDataProcess.checkSum,exports.crc16modbus=BleDataProcess.crc16modbus,exports.crcCheckSum=BleDataProcess.crcCheckSum,exports.decimalToHex=BleDataProcess.decimalToHex,exports.decimalToHex0x=BleDataProcess.decimalToHex0x,exports.decimalToTwoByteHexArray=BleDataProcess.decimalToTwoByteHexArray,exports.extractBits=BleDataProcess.extractBits,exports.fromBCD=BleDataProcess.fromBCD,exports.generateCheckSum=BleDataProcess.generateCheckSum,exports.generateCrc16modbusCheck=BleDataProcess.generateCrc16modbusCheck,exports.generateCrcCheckSum=BleDataProcess.generateCrcCheckSum,exports.getParamBaseValue=BleDataProcess.getParamBaseValue,exports.hex2Ascii=BleDataProcess.hex2Ascii,exports.hex2Binary=BleDataProcess.hex2Binary,exports.hex2string=BleDataProcess.hex2string,exports.hexArr2Assic=BleDataProcess.hexArr2Assic,exports.hexArr2ab=BleDataProcess.hexArr2ab,exports.hexArr2string=BleDataProcess.hexArr2string,exports.hexArrayToModuleArrayBuffer=BleDataProcess.hexArrayToModuleArrayBuffer,exports.hexStrAscii=BleDataProcess.hexStrAscii,exports.hexStringToBinary=BleDataProcess.hexStringToBinary,exports.hexToDecimal=BleDataProcess.hexToDecimal,exports.isWithin30Minutes=BleDataProcess.isWithin30Minutes,exports.parseDateTime=BleDataProcess.parseDateTime,exports.sleep=BleDataProcess.sleep,exports.string2hexArr=BleDataProcess.string2hexArr,exports.stringToTwoHexArray=BleDataProcess.stringToTwoHexArray,exports.toBCD=BleDataProcess.toBCD,exports.getData=BleCmdAnalysis.getData,exports.setMTUAsync=BleCmdAnalysis.setMTUAsync,exports.clearPrimaryKey=BleCmdFFAA.clearPrimaryKey,exports.getBluetoothName=BleCmdFFAA.getBluetoothName,exports.getBroadcastDataCmd=BleCmdFFAA.getBroadcastDataCmd,exports.getFFAA03Async=BleCmdFFAA.getFFAA03Async,exports.getFFAA17Async=BleCmdFFAA.getFFAA17Async,exports.getFFAA25Async=BleCmdFFAA.getFFAA25Async,exports.getFFAA26Async=BleCmdFFAA.getFFAA26Async,exports.getFFAA80Async=BleCmdFFAA.getFFAA80Async,exports.getFFAAKeyAsync=BleCmdFFAA.getFFAAKeyAsync,exports.getWiFiIP=BleCmdFFAA.getWiFiIP,exports.resetFactoryData=BleCmdFFAA.resetFactoryData,exports.resetSecondaryKey=BleCmdFFAA.resetSecondaryKey,exports.resolveFFAA25=BleCmdFFAA.resolveFFAA25,exports.resolveFFAA26=BleCmdFFAA.resolveFFAA26,exports.resolveFFAA80=BleCmdFFAA.resolveFFAA80,exports.resolveFFAAKey=BleCmdFFAA.resolveFFAAKey,exports.setBluetoothName=BleCmdFFAA.setBluetoothName,exports.setWiFi=BleCmdFFAA.setWiFi,exports.setWiFiSta=BleCmdFFAA.setWiFiSta,exports.set_PlanCMD_FFAA=BleCmdFFAA.set_PlanCMD_FFAA,exports.set_PlanCMD_FFAA80=BleCmdFFAA.set_PlanCMD_FFAA80,exports.activateAsync=BleCmdDD.activateAsync,exports.enterFactory=BleCmdDD.enterFactory,exports.existFactory=BleCmdDD.existFactory,exports.get3B3CAsync=BleCmdDD.get3B3CAsync,exports.get3B3CInfo=BleCmdDD.get3B3CInfo,exports.getChipTypeAsync=BleCmdDD.getChipTypeAsync,exports.getDD5A0AAsync=BleCmdDD.getDD5A0AAsync,exports.getDD5A0EAsync=BleCmdDD.getDD5A0EAsync,exports.getDD5A17Async=BleCmdDD.getDD5A17Async,exports.getDD5AAllAsync=BleCmdDD.getDD5AAllAsync,exports.getDD5AE0Async=BleCmdDD.getDD5AE0Async,exports.getDD5AE1Async=BleCmdDD.getDD5AE1Async,exports.getDD5AE4Async=BleCmdDD.getDD5AE4Async,exports.getDD5AFAAsync=BleCmdDD.getDD5AFAAsync,exports.getDD5AFBAsync=BleCmdDD.getDD5AFBAsync,exports.getDDA4F0Async=BleCmdDD.getDDA4F0Async,exports.getDDA503Async=BleCmdDD.getDDA503Async,exports.getDDA504Async=BleCmdDD.getDDA504Async,exports.getDDA505Async=BleCmdDD.getDDA505Async,exports.getDDA506Async=BleCmdDD.getDDA506Async,exports.getDDA507Async=BleCmdDD.getDDA507Async,exports.getDDA508Async=BleCmdDD.getDDA508Async,exports.getDDA5DCAsync=BleCmdDD.getDDA5DCAsync,exports.getDDA5FAAsync=BleCmdDD.getDDA5FAAsync,exports.getDDA5OldAsync=BleCmdDD.getDDA5OldAsync,exports.getProtectCountCmd=BleCmdDD.getProtectCountCmd,exports.readExistFactory=BleCmdDD.readExistFactory,exports.resetCapacity=BleCmdDD.resetCapacity,exports.resolve3B3C=BleCmdDD.resolve3B3C,exports.resolveBMSCmd=BleCmdDD.resolveBMSCmd,exports.resolveBaseDD=BleCmdDD.resolveBaseDD,exports.resolveDD5A0A=BleCmdDD.resolveDD5A0A,exports.resolveDDA4F0=BleCmdDD.resolveDDA4F0,exports.resolveDDA500=BleCmdDD.resolveDDA500,exports.resolveDDA503=BleCmdDD.resolveDDA503,exports.resolveDDA504=BleCmdDD.resolveDDA504,exports.resolveDDA505=BleCmdDD.resolveDDA505,exports.resolveDDA506=BleCmdDD.resolveDDA506,exports.resolveDDA508=BleCmdDD.resolveDDA508,exports.resolveDDA5DC=BleCmdDD.resolveDDA5DC,exports.resolveDDA5FA=BleCmdDD.resolveDDA5FA,exports.resolveProtections=BleCmdDD.resolveProtections,exports.sendBMSAsync=BleCmdDD.sendBMSAsync,exports.setDD5AE3sync=BleCmdDD.setDD5AE3sync,exports.setDDA5FAAsync=BleCmdDD.setDDA5FAAsync,exports.setDDA5OldAsync=BleCmdDD.setDDA5OldAsync,exports.set_PlanCMD_3B3C=BleCmdDD.set_PlanCMD_3B3C,exports.set_PlanCMD_DD=BleCmdDD.set_PlanCMD_DD,exports.getSysParamCmd=readAndSetParam.getSysParamCmd,exports.readParamCmd=readAndSetParam.readParamCmd,exports.setCapacityParamCmd=readAndSetParam.setCapacityParamCmd,exports.setParamCmd=readAndSetParam.setParamCmd,exports.setSysParamCmd=readAndSetParam.setSysParamCmd,exports.getBaseInfo=BaseParamProtocol.getBaseInfo,exports.getBaseParams=BaseParamProtocol.getBaseParams,exports.getResistance=BaseParamProtocol.getResistance,exports.getCMDESInfoAsync=BleCmdHVES.getCMDESInfoAsync,exports.getHVESInfoAsync=BleCmdHVES.getHVESInfoAsync,exports.resolveHVESBMUInfo=BleCmdHVES.resolveHVESBMUInfo,exports.resolveHVESBaseInfo=BleCmdHVES.resolveHVESBaseInfo,exports.resolveHVESCalibrationC1Info=BleCmdHVES.resolveHVESCalibrationC1Info,exports.resolveHVESCalibrationC2Info=BleCmdHVES.resolveHVESCalibrationC2Info,exports.resolveHVESCalibrationConfigInfo=BleCmdHVES.resolveHVESCalibrationConfigInfo,exports.resolveHVESCalibrationInfo=BleCmdHVES.resolveHVESCalibrationInfo,exports.resolveHVESCtInfo=BleCmdHVES.resolveHVESCtInfo,exports.resolveHVESDisCtInfo=BleCmdHVES.resolveHVESDisCtInfo,exports.resolveHVESElectrodeHTInfo=BleCmdHVES.resolveHVESElectrodeHTInfo,exports.resolveHVESEtInfo=BleCmdHVES.resolveHVESEtInfo,exports.resolveHVESInsulationLRInfo=BleCmdHVES.resolveHVESInsulationLRInfo,exports.resolveHVESLSocInfo=BleCmdHVES.resolveHVESLSocInfo,exports.resolveHVESMonoVolInfo=BleCmdHVES.resolveHVESMonoVolInfo,exports.resolveHVESOeInfo=BleCmdHVES.resolveHVESOeInfo,exports.resolveHVESOtRisingInfo=BleCmdHVES.resolveHVESOtRisingInfo,exports.resolveHVESOtrInfo=BleCmdHVES.resolveHVESOtrInfo,exports.resolveHVESOvrInfo=BleCmdHVES.resolveHVESOvrInfo,exports.resolveHVESPackInfo=BleCmdHVES.resolveHVESPackInfo,exports.resolveHVESParamsInfo=BleCmdHVES.resolveHVESParamsInfo,exports.resolveHVESSumInfo=BleCmdHVES.resolveHVESSumInfo,exports.resolveHVESSumVolInfo=BleCmdHVES.resolveHVESSumVolInfo,exports.resolveHVESVersionInfo=BleCmdHVES.resolveHVESVersionInfo,exports.HostProtocol=ESHostProtocol.HostProtocol,exports.batteryInfoJson=baseParamsJson.batteryInfoJson,exports.capInfoJson=baseParamsJson.capInfoJson,exports.capVolInfoJson=baseParamsJson.capVolInfoJson,exports.currentInfoJson=baseParamsJson.currentInfoJson,exports.equalizerFunJson=baseParamsJson.equalizerFunJson,exports.funcAndTempFuncJson=baseParamsJson.funcAndTempFuncJson,exports.funcJson=baseParamsJson.funcJson,exports.systemJson=baseParamsJson.systemJson,exports.tempFuncJson=baseParamsJson.tempFuncJson,exports.tempInfoJson=baseParamsJson.tempInfoJson,exports.voltageInfoJson=baseParamsJson.voltageInfoJson;
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var array=require("./core/array.js"),BleApiManager=require("./core/BleApiManager.js"),BleDataProcess=require("./core/BleDataProcess.js"),commonfun=require("./core/commonfun.js"),keyAndPwdManager=require("./core/keyAndPwdManager.js"),mqttServer=require("./core/mqttServer.js"),OtaUpgrade=require("./core/OtaUpgrade.js"),rsaEncrypt=require("./core/rsaEncrypt.js"),TelinkApi=require("./core/TelinkApi.js"),Transfer=require("./core/Transfer.js"),BaseParamProtocol=require("./core/BleCmdAnalysis/BaseParamProtocol.js"),BleCmdAnalysis=require("./core/BleCmdAnalysis/BleCmdAnalysis.js"),BleCmdDD=require("./core/BleCmdAnalysis/BleCmdDD.js"),BleCmdDDA4=require("./core/BleCmdAnalysis/BleCmdDDA4.js"),BleCmdFFAA=require("./core/BleCmdAnalysis/BleCmdFFAA.js"),BleCmdHVES=require("./core/BleCmdAnalysis/BleCmdHVES.js"),ESHostProtocol=require("./core/BleCmdAnalysis/ESHostProtocol.js"),readAndSetParam=require("./core/BleCmdAnalysis/readAndSetParam.js"),baseParamsJson=require("./core/dataJson/baseParamsJson.js");exports.chunk=array.chunk,exports.unique=array.unique,exports.checkBluetoothStatus=BleApiManager.checkBluetoothStatus,exports.checkLocationStatus=BleApiManager.checkLocationStatus,exports.connectAsync=BleApiManager.connectAsync,exports.createBLEConnection=BleApiManager.createBLEConnection,exports.disConnect=BleApiManager.disConnect,exports.enhanceDevice=BleApiManager.enhanceDevice,exports.foundScanDevice=BleApiManager.foundScanDevice,exports.getBLEDeviceCharacteristics=BleApiManager.getBLEDeviceCharacteristics,exports.getBLEDeviceServices=BleApiManager.getBLEDeviceServices,exports.getBluetoothAdapterState=BleApiManager.getBluetoothAdapterState,exports.getBluetoothPermission=BleApiManager.getBluetoothPermission,exports.initBle=BleApiManager.initBle,Object.defineProperty(exports,"isInit",{enumerable:!0,get:function(){return BleApiManager.isInit}}),exports.notify=BleApiManager.notify,exports.onBLECharacteristicValueChange=BleApiManager.onBLECharacteristicValueChange,exports.onBLEConnectionStateChange=BleApiManager.onBLEConnectionStateChange,exports.onBleChangedConnectionState=BleApiManager.onBleChangedConnectionState,exports.onBluetoothAdapterStateChange=BleApiManager.onBluetoothAdapterStateChange,exports.onBluetoothDeviceFound=BleApiManager.onBluetoothDeviceFound,exports.onFoundDevice=BleApiManager.onFoundDevice,exports.scanHandle=BleApiManager.scanHandle,exports.startDevicesDiscovery=BleApiManager.startDevicesDiscovery,exports.stopBluetoothDevicesDiscovery=BleApiManager.stopBluetoothDevicesDiscovery,exports.ab2decimalArr=BleDataProcess.ab2decimalArr,exports.ab2hex=BleDataProcess.ab2hex,exports.arrayBufferToHexArray=BleDataProcess.arrayBufferToHexArray,exports.base64ToHexArray=BleDataProcess.base64ToHexArray,exports.checkSum=BleDataProcess.checkSum,exports.crc16modbus=BleDataProcess.crc16modbus,exports.crcCheckSum=BleDataProcess.crcCheckSum,exports.decimalToHex=BleDataProcess.decimalToHex,exports.decimalToHex0x=BleDataProcess.decimalToHex0x,exports.decimalToTwoByteHexArray=BleDataProcess.decimalToTwoByteHexArray,exports.extractBits=BleDataProcess.extractBits,exports.fromBCD=BleDataProcess.fromBCD,exports.generateCheckSum=BleDataProcess.generateCheckSum,exports.generateCrc16modbusCheck=BleDataProcess.generateCrc16modbusCheck,exports.generateCrcCheckSum=BleDataProcess.generateCrcCheckSum,exports.getParamBaseValue=BleDataProcess.getParamBaseValue,exports.hex2Ascii=BleDataProcess.hex2Ascii,exports.hex2Binary=BleDataProcess.hex2Binary,exports.hex2string=BleDataProcess.hex2string,exports.hexArr2Assic=BleDataProcess.hexArr2Assic,exports.hexArr2ab=BleDataProcess.hexArr2ab,exports.hexArr2string=BleDataProcess.hexArr2string,exports.hexArrayToModuleArrayBuffer=BleDataProcess.hexArrayToModuleArrayBuffer,exports.hexStrAscii=BleDataProcess.hexStrAscii,exports.hexStringToBinary=BleDataProcess.hexStringToBinary,exports.hexToDecimal=BleDataProcess.hexToDecimal,exports.isWithin30Minutes=BleDataProcess.isWithin30Minutes,exports.parseDateTime=BleDataProcess.parseDateTime,exports.sleep=BleDataProcess.sleep,exports.string2hexArr=BleDataProcess.string2hexArr,exports.stringToTwoHexArray=BleDataProcess.stringToTwoHexArray,exports.toBCD=BleDataProcess.toBCD,exports.eventBus=commonfun.eventBus,exports.formatTimeHHmm=commonfun.formatTimeHHmm,exports.getOS=commonfun.getOS,exports.getPlatform=commonfun.getPlatform,exports.inArray=commonfun.inArray,exports.isEmpty=commonfun.isEmpty,exports.isNotEmpty=commonfun.isNotEmpty,exports.ALLOWED_MAC_PREFIX=keyAndPwdManager.ALLOWED_MAC_PREFIX,exports.APP_KEY_STATUS=keyAndPwdManager.APP_KEY_STATUS,exports.extractModuleInfo=keyAndPwdManager.extractModuleInfo,exports.getRandomNum=keyAndPwdManager.getRandomNum,exports.getTypeBuyCmd=keyAndPwdManager.getTypeBuyCmd,exports.handleNewAppKey=keyAndPwdManager.handleNewAppKey,exports.handleOldAppKey=keyAndPwdManager.handleOldAppKey,exports.sendAppKey=keyAndPwdManager.sendAppKey,exports.sendEnableOrVerifyKey=keyAndPwdManager.sendEnableOrVerifyKey,exports.sendOldAppKey=keyAndPwdManager.sendOldAppKey,exports.sendVerifyPwd=keyAndPwdManager.sendVerifyPwd,exports.sendWrite1LevelPwd=keyAndPwdManager.sendWrite1LevelPwd,exports.verify3LevelPassword=keyAndPwdManager.verify3LevelPassword,exports.verifyMacAddrAndKey=keyAndPwdManager.verifyMacAddrAndKey,exports.MqttServer=mqttServer.MqttServer,exports.OTAUpgrade=OtaUpgrade.OTAUpgrade,exports.decrypt=rsaEncrypt.decrypt,exports.decrypt2=rsaEncrypt.decrypt2,exports.decryptUsername=rsaEncrypt.decryptUsername,exports.encrypt=rsaEncrypt.encrypt,exports.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.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";const serviceId="0000FF00-0000-1000-8000-00805F9B34FB",{isAndroid:isAndroid,isIOS:isIOS}=getOS(),bluetoothAdapterState=ref({available:!1,discovering:!1});var isInit=!1;const checkBluetoothStatus=async(successCallback=()=>{})=>new Promise((resolve,reject)=>{uni.openBluetoothAdapter({success:async res=>{successCallback&&successCallback(res),resolve(res)},fail:err=>{console.log("openBluetoothAdapter fail4-----",err),err&&3==err?.errno&&reject({code:105,message:"请授权微信位置信息和蓝牙权限"}),err&&103==err?.errno&&reject({code:106,message:"请授权蓝牙和位置权限,并重启小程序"}),reject({code:102,message:"当前手机蓝牙不可用,请检查手机蓝牙状态"})}})}),checkLocationStatus=async(successCallback=()=>{})=>{const timeoutPromise=new Promise((resolve,reject)=>{setTimeout(()=>{reject({code:101,message:"网络信号差或连接异常,请检查网络情况"})},1e4)}),locationPromise=new Promise((resolve,reject)=>{uni.getLocation({type:"wgs84",success:res=>{console.log("位置信息-----------",res),resolve(res)},fail:err=>{console.log("位置信息err",err),err&&103==err?.errno&&reject({code:103,message:"请授权小程序位置信息权限, 并重启小程序。"}),err&&2==err?.errCode&&reject({code:101,message:"网络信号差或连接异常,请检查网络情况"}),reject({code:104,message:"请授权微信位置信息权限, 并重启小程序。"})}})});return Promise.race([locationPromise,timeoutPromise]).then(async res=>await checkBluetoothStatus(successCallback))},getBluetoothPermission=async(successCallback=()=>{})=>{try{return isAndroid?await checkLocationStatus(successCallback):await checkBluetoothStatus(successCallback)}catch(error){throw console.error("初始化蓝牙失败:",error),error}},initBle=async()=>await getBluetoothPermission(()=>{try{onBluetoothDeviceFound(),onBLECharacteristicValueChange(),onBLEConnectionStateChange(),onBluetoothAdapterStateChange(),isInit=!0}catch(error){throw error}}),getBluetoothAdapterState=async()=>new Promise((resolve,reject)=>{uni.getBluetoothAdapterState({success:res=>{console.log("getBluetoothAdapterState success",res),resolve(res)},fail:err=>{console.log("getBluetoothAdapterState fail",err),reject(err)}})}),startDevicesDiscovery=async(allowDuplicatesKey=!0)=>new Promise((resolve,reject)=>{bluetoothAdapterState.value.discovering?reject(new Error("蓝牙设备搜索已在进行中")):uni.startBluetoothDevicesDiscovery({services:[serviceId],allowDuplicatesKey:allowDuplicatesKey,success:async res=>{console.log("广播设备 success",res),resolve(res)},fail:err=>{console.log("广播设备 fail",err),reject(err)}})}),stopBluetoothDevicesDiscovery=async()=>(bluetoothAdapterState.value={available:bluetoothAdapterState.value.available,discovering:!1},new Promise((resolve,reject)=>{uni.stopBluetoothDevicesDiscovery({success:res=>{console.log("停止广播设备 success",res),resolve(res)},fail:err=>{console.log("停止广播设备 fail",err),reject(err)},complete:res=>{console.log("停止广播设备 取消订阅"),eventBus.off("setBluetoothDeviceFound")}})})),onBluetoothDeviceFound=async()=>{uni.onBluetoothDeviceFound(characteristic=>{console.log("setBluetoothDeviceFound",characteristic);const device=(
|
|
1
|
+
import{ref}from"vue";import{ab2decimalArr,hexToDecimal}from"./BleDataProcess.js";import{getOS,eventBus}from"./commonfun.js";const serviceId="0000FF00-0000-1000-8000-00805F9B34FB",{isAndroid:isAndroid,isIOS:isIOS}=getOS(),bluetoothAdapterState=ref({available:!1,discovering:!1});var isInit=!1;const 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)})},onBleChangedConnectionState=callback=>{eventBus.on("setBleChangedConnectionState",callback)},createBLEConnection=async(deviceId,timeout=1e4)=>new Promise((resolve,reject)=>{console.log(deviceId,"点击的设备信息"),uni.createBLEConnection({deviceId:deviceId,timeout:timeout,success:res=>{console.log(res,"连接成功"),resolve(!0)},fail:err=>{console.log(err,"Connection"),-1==(err.code||err.errCode)?resolve(!0):reject(err)}})}),withRetry=async(asyncOperation,maxRetries=20,retryInterval=100,type)=>new Promise((resolve,reject)=>{let retryCount=0;const attempt=async()=>{try{const result=await asyncOperation();resolve(result)}catch(error){if(retryCount>=maxRetries)return void reject(new Error(`${type}失败,${error.message} (已重试${maxRetries}次)`));retryCount++,console.warn(`${type}失败,第${retryCount}次重试:`,error.message),setTimeout(attempt,retryInterval)}};attempt()}),getBLEDeviceServices=deviceId=>withRetry(async()=>{const res=await new Promise((resolve,reject)=>{uni.getBLEDeviceServices({deviceId:deviceId,success:resolve,fail:reject})});if(console.log("获取蓝牙服务成功:",res),0===res.services.length)throw new Error("未找到蓝牙服务");return await getBLEDeviceCharacteristics(deviceId),res.services},20,100,"获取蓝牙服务"),getBLEDeviceCharacteristics=async deviceId=>withRetry(async()=>{const res=await new Promise((resolve,reject)=>{uni.getBLEDeviceCharacteristics({deviceId:deviceId,serviceId:serviceId,success:resolve,fail:reject})});return console.log("获取特征值成功:",res),res.characteristics},20,100,"获取蓝牙特征值"),notify=async deviceId=>new Promise((resolve,reject)=>{uni.notifyBLECharacteristicValueChange({deviceId:deviceId,serviceId:serviceId,characteristicId:"0000FF01-0000-1000-8000-00805F9B34FB",state:!0,success:res=>{console.log("订阅===========",res),resolve(res)},fail:reject})}),disConnect=deviceId=>new Promise((resolve,reject)=>{uni.closeBLEConnection({deviceId:deviceId,success:res=>{resolve(res),console.log(res,"断开连接成功")},fail:err=>{reject(err),console.log(err,"err 断开连接")}})}),connectAsync=async(deviceId,timeout=1e4)=>new Promise(async(resolve,reject)=>{try{await createBLEConnection(deviceId,timeout),await getBLEDeviceServices(deviceId),await notify(deviceId),resolve(!0)}catch(error){console.log("error: ",error),reject(error)}}),scanHandle=(historyConnectedList=[],connectFn=device=>{},failScanFn=err=>{})=>{uni.scanCode({scanType:["barCode","qrCode"],success:async({result:result})=>{console.log("扫描内容: "+result);let searchKey=result;try{const formatMacAddress=mac=>mac.replace(/(.{2})/g,"$1:").slice(0,-1).toUpperCase();let isMac=!1;result.includes("?qrCodeInfo=")?(searchKey=result.split("?qrCodeInfo=")[1],searchKey.includes(":")?(searchKey=searchKey.slice(-17).toUpperCase(),isMac=!0):(searchKey=searchKey.slice(-12),searchKey=formatMacAddress(searchKey),isMac=!0)):17===result.length&&result.includes(":")?(searchKey=result.toUpperCase(),isMac=!0):12===result.length&&(searchKey=formatMacAddress(result),isMac=!0);const matchedHistoryDevice=historyConnectedList.find(item=>item.macAddr==searchKey);if(matchedHistoryDevice)return void connectFn(matchedHistoryDevice);isAndroid&&isMac?connectFn({deviceId:searchKey,macAddr:searchKey,name:searchKey}):foundScanDevice(searchKey,connectFn)}catch(error){console.log(error)}},complete:err=>{},fail:err=>{console.log("scanCode err",err),failScanFn(err)}})},foundScanDevice=async(result,connectFn)=>{const deviceList=[];await startDevicesDiscovery(isIOS),onFoundDevice(device=>{deviceList.push(device);const findDevice=device.macAddr===result||device.name===result;findDevice?(scanTimeout&&(clearTimeout(scanTimeout),scanTimeout=null),uni.stopBluetoothDevicesDiscovery(),connectFn(findDevice)):console.log("未找到设备,继续搜索中...")});let scanTimeout=setTimeout(async()=>{try{console.log("stopBluetoothDevicesDiscovery",deviceList),uni.stopBluetoothDevicesDiscovery();const findDevice=deviceList.find(device=>device.macAddr===result||device.name===result);connectFn(findDevice)}finally{}},5e3)};export{checkBluetoothStatus,checkLocationStatus,connectAsync,createBLEConnection,disConnect,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{eventBus,getOS,getPlatform}from"../commonfun.js";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";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 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);console.log("数据包验证结果:",{verified:verified}),verified?(responsed=!0,cleanup(),resolve([...pkg])):(len=null,pkg=[])}}else pkg=[]}},writeToDevice=async(attempt=1)=>{try{console.warn(tag,`第${attempt}次写入指令:`,command.join("").replace(/0x/g,"").toUpperCase());const writeSucceed=await async function(deviceId,value){return console.log("value: ",value),console.log("deviceId: ",deviceId),!(!deviceId||!value)&&new Promise(async resolve=>{const n=Math.ceil(value.byteLength/20);let res;for(let i=0;i<n;i++){const _value=value.slice(20*i,20*(i+1));if(console.log("分包写入_value: ",_value),await 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{eventBus,getOS,getPlatform}from"../commonfun.js";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 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);console.log("数据包验证结果:",{verified:verified}),verified?(responsed=!0,cleanup(),resolve([...pkg])):(len=null,pkg=[])}}else pkg=[]}},writeToDevice=async(attempt=1)=>{try{console.warn(tag,`第${attempt}次写入指令:`,command.join("").replace(/0x/g,"").toUpperCase());const writeSucceed=await async function(deviceId,value){return console.log("value: ",value),console.log("deviceId: ",deviceId),!(!deviceId||!value)&&new Promise(async resolve=>{const n=Math.ceil(value.byteLength/20);let res;for(let i=0;i<n;i++){const _value=value.slice(20*i,20*(i+1));if(console.log("分包写入_value: ",_value),await 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};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{generateCrcCheckSum,hexArr2string,hexToDecimal,decimalToHex,hex2string}from"../BleDataProcess.js";import{getData}from"./BleCmdAnalysis.js";const getDDA420Async=async deviceId=>{const _command=["0x20","0x00"],checks=generateCrcCheckSum(_command),command=["0xdd","0xa4",..._command,...checks,"0x77"];return getData(deviceId,{command:command,commandVerifyHandler:hexArr=>({verified:221==hexArr[0]&&32==hexArr[1],pkgLen:hexArr[3]+7}),pkgVerifyHandler:pkg=>{const len=pkg.length,[c1,c2]=generateCrcCheckSum(pkg.slice(2,len-3)),[_c1,_c2]=[pkg[len-3],pkg[len-2]];return{verified:c1==_c1&&c2==_c2}}},"DDA420")},resolveDDA420=data=>{if(!data)return null;const dataStr=hexArr2string(data);let n=4;const workStatus=data[n++],chargeStatus=data[n++],chargeVoltage=hexToDecimal(decimalToHex(data[n++])+decimalToHex(data[n++])+decimalToHex(data[n++])+decimalToHex(data[n++])),chargeElectricity=hexToDecimal(decimalToHex(data[n++])+decimalToHex(data[n++])+decimalToHex(data[n++])+decimalToHex(data[n++])),chargePower=hexToDecimal(decimalToHex(data[n++])+decimalToHex(data[n++])),chargeTemperature=hexToDecimal(decimalToHex(data[n++])+decimalToHex(data[n++]))/10,chargeCapacity=hexToDecimal(decimalToHex(data[n++])+decimalToHex(data[n++])+decimalToHex(data[n++])+decimalToHex(data[n++])),chargeTime=hexToDecimal(decimalToHex(data[n++])+decimalToHex(data[n++])),chargeRemainTime=hexToDecimal(decimalToHex(data[n++])+decimalToHex(data[n++])),chargeCompleteTime=hexToDecimal(decimalToHex(data[n++])+decimalToHex(data[n++])),outputVoltagePercent=hexToDecimal(decimalToHex(data[n++])+decimalToHex(data[n++])+decimalToHex(data[n++])+decimalToHex(data[n++])),outputElectricityPercent=hexToDecimal(decimalToHex(data[n++])+decimalToHex(data[n++])+decimalToHex(data[n++])+decimalToHex(data[n++])),outputVoltage=hexToDecimal(decimalToHex(data[n++])+decimalToHex(data[n++])+decimalToHex(data[n++])+decimalToHex(data[n++])),outputElectricity=hexToDecimal(decimalToHex(data[n++])+decimalToHex(data[n++])+decimalToHex(data[n++])+decimalToHex(data[n++])),batteryVoltage=hexToDecimal(decimalToHex(data[n++])+decimalToHex(data[n++])+decimalToHex(data[n++])+decimalToHex(data[n++])),swtichStatusArr=hexToDecimal(decimalToHex(data[n++])+decimalToHex(data[n++])).toString(2).padStart(16,"0").split("").reverse(),chargeSwitch="1"==swtichStatusArr[0],preChargeSwitch="1"==swtichStatusArr[1],fanSwitch="1"==swtichStatusArr[2],protectStatusArr=hexToDecimal(decimalToHex(data[n++])+decimalToHex(data[n++])+decimalToHex(data[n++])+decimalToHex(data[n++])).toString(2).padStart(32,"0").split("").reverse();let protectStatusIndexs=[];for(let i=0;i<protectStatusArr.length;i++)"1"==protectStatusArr[i]&&protectStatusIndexs.push(i);const alarmStatusArr=hexToDecimal(decimalToHex(data[n++])+decimalToHex(data[n++])+decimalToHex(data[n++])+decimalToHex(data[n++])).toString(2).padStart(32,"0").split("").reverse();let alarmStatusIndexs=[];for(let i=0;i<alarmStatusArr.length;i++)"1"==alarmStatusArr[i]&&alarmStatusIndexs.push(i);return{dataStr:dataStr,workStatus:workStatus,chargeStatus:chargeStatus,chargeVoltage:chargeVoltage,chargeElectricity:chargeElectricity,chargePower:chargePower,chargeTemperature:chargeTemperature,chargeCapacity:chargeCapacity,chargeTime:chargeTime,chargeRemainTime:chargeRemainTime,chargeCompleteTime:chargeCompleteTime,outputVoltagePercent:outputVoltagePercent,outputElectricityPercent:outputElectricityPercent,outputVoltage:outputVoltage,outputElectricity:outputElectricity,batteryVoltage:batteryVoltage,chargeSwitch:chargeSwitch,preChargeSwitch:preChargeSwitch,fanSwitch:fanSwitch,protectStatusIndexs:protectStatusIndexs,alarmStatusIndexs:alarmStatusIndexs,communicationMode:data[n++]}},getDDA421Async=async deviceId=>{const _command=["0x21","0x00"],checks=generateCrcCheckSum(_command),command=["0xdd","0xa4",..._command,...checks,"0x77"];return(void 0).getData(deviceId,{command:command,commandVerifyHandler:hexArr=>({verified:221==hexArr[0]&&33==hexArr[1],pkgLen:hexArr[3]+7}),pkgVerifyHandler:pkg=>{const len=pkg.length,[c1,c2]=generateCrcCheckSum(pkg.slice(2,len-3)),[_c1,_c2]=[pkg[len-3],pkg[len-2]];return{verified:c1==_c1&&c2==_c2}}},"DDA421")},resolveDDA421=data=>{if(!data)return null;const dataStr=hexArr2string(data),batteryVoltageHex=decimalToHex(data[4])+decimalToHex(data[5])+decimalToHex(data[6])+decimalToHex(data[7]),batteryVoltage=hexToDecimal(batteryVoltageHex),batteryCurrentHex=decimalToHex(data[8])+decimalToHex(data[9])+decimalToHex(data[10])+decimalToHex(data[11]),batteryCurrent=hexToDecimal(batteryCurrentHex),batteryType=data[12],batterySeries=data[13],batteryCapacityHex=decimalToHex(data[14])+decimalToHex(data[15])+decimalToHex(data[16])+decimalToHex(data[17]),batteryCapacity=hexToDecimal(batteryCapacityHex),batterySOC=data[18],batteryTempHex=decimalToHex(data[19])+decimalToHex(data[20]),batteryTemperature=hexToDecimal(batteryTempHex)/10,heatingStatus=data[21],heatingCurrentHex=decimalToHex(data[22])+decimalToHex(data[23])+decimalToHex(data[24])+decimalToHex(data[25]),heatingCurrent=hexToDecimal(heatingCurrentHex),protectStatusHex=decimalToHex(data[26])+decimalToHex(data[27]),protectStatusArr=hexToDecimal(protectStatusHex).toString(2).padStart(16,"0").split("").reverse();let protectStatusIndexs=[];for(let i=0;i<protectStatusArr.length;i++)"1"==protectStatusArr[i]&&protectStatusIndexs.push(i);const alarmStatusHex=decimalToHex(data[28])+decimalToHex(data[29]),alarmStatusArr=hexToDecimal(alarmStatusHex).toString(2).padStart(16,"0").split("").reverse();let alarmStatusIndexs=[];for(let i=0;i<alarmStatusArr.length;i++)"1"==alarmStatusArr[i]&&alarmStatusIndexs.push(i);return{dataStr:dataStr,batteryVoltage:batteryVoltage,batteryCurrent:batteryCurrent,batteryType:batteryType,batterySeries:batterySeries,batteryCapacity:batteryCapacity,batterySOC:batterySOC,batteryTemperature:batteryTemperature,heatingStatus:heatingStatus,heatingCurrent:heatingCurrent,protectStatusIndexs:protectStatusIndexs,alarmStatusIndexs:alarmStatusIndexs}},getDDA425Async=async(deviceId,type)=>{const _command=["0x25","0x01",type],checks=generateCrcCheckSum(_command),command=["0xDD","0xA4",..._command,...checks,"0x77"];return console.log("command: ",command),getData(deviceId,{command:command,commandVerifyHandler:hexArr=>({verified:221==hexArr[0]&&37==hexArr[1],pkgLen:hexArr[3]+7}),pkgVerifyHandler:pkg=>({verified:!0})},"DDA425")},resolveDDA425=data=>{if(!data)return null;return{dataStr:hexArr2string(data),status:hex2string(data[2])}},getDDA422Async=async(deviceId,startReg,endReg)=>{const startRegHex=decimalToHex(startReg,4),endRegHex=decimalToHex(endReg,4),_command=["0x22","0x04",...[parseInt(startRegHex.slice(0,2),16),parseInt(startRegHex.slice(2,4),16)],...[parseInt(endRegHex.slice(0,2),16),parseInt(endRegHex.slice(2,4),16)]],checks=generateCrcCheckSum(_command),command=["0xDD","0xA4",..._command,...checks,"0x77"];return getData(deviceId,{command:command,commandVerifyHandler:hexArr=>({verified:221==hexArr[0]&&34==hexArr[1],pkgLen:hexArr[3]+7}),pkgVerifyHandler:pkg=>{const len=pkg.length,[c1,c2]=generateCrcCheckSum(pkg.slice(2,len-3)),[_c1,_c2]=[pkg[len-3],pkg[len-2]];return{verified:c1==_c1&&c2==_c2}}},"DDA422")},resolveDDA422=data=>{if(!data)return null;const dataStr=hexArr2string(data),startRegHex=decimalToHex(data[4])+decimalToHex(data[5]),startReg=hexToDecimal(startRegHex),endRegHex=decimalToHex(data[6])+decimalToHex(data[7]);return{dataStr:dataStr,startReg:startReg,endReg:hexToDecimal(endRegHex),regData:data.slice(8,data.length-3)}},getDDA423Async=async(deviceId,startReg,endReg,values,valuesLength)=>{const startRegHex=decimalToHex(startReg,4),startRegArr=[parseInt(startRegHex.slice(0,2),16),parseInt(startRegHex.slice(2,4),16)],endRegHex=decimalToHex(endReg,4),endRegArr=[parseInt(endRegHex.slice(0,2),16),parseInt(endRegHex.slice(2,4),16)],valueRegHex=decimalToHex(values,2*valuesLength);let valueArr=[];for(let i=0;i<valuesLength;i++){const hex=valueRegHex.slice(2*i,2*i+2);valueArr.push(parseInt(hex.slice(0,2),16))}const _command=["0x23",decimalToHex(4+valuesLength,2),...startRegArr,...endRegArr,...valueArr],checks=generateCrcCheckSum(_command),command=["0xDD","0xA4",..._command,...checks,"0x77"];return getData(deviceId,{command:command,commandVerifyHandler:hexArr=>({verified:221==hexArr[0]&&35==hexArr[1],pkgLen:hexArr[3]+7}),pkgVerifyHandler:pkg=>{const len=pkg.length,[c1,c2]=generateCrcCheckSum(pkg.slice(2,len-3)),[_c1,_c2]=[pkg[len-3],pkg[len-2]];return{verified:c1==_c1&&c2==_c2}}},"DDA423")},resolveDDA423=data=>{if(!data)return null;return{dataStr:hexArr2string(data),status:hex2string(data[2])}},getDDA426Async=async(deviceId,testMode=0,outputVoltage=0,outputCurrent=0)=>{const clamp32=v=>((v=Number(v)||0)<0&&(v=0),v>4294967295&&(v=4294967295),v);testMode=2===testMode?2:0,outputVoltage=clamp32(outputVoltage),outputCurrent=clamp32(outputCurrent);const to4Bytes=val=>{const hex=commonfun.decimalToHex(val,8);return[0,2,4,6].map(i=>parseInt(hex.slice(i,i+2),16))},voltageArr=to4Bytes(outputVoltage),currentArr=to4Bytes(outputCurrent),_command=["0x26",`0x${commonfun.decimalToHex(9,2)}`,255&testMode,...voltageArr,...currentArr].map(o=>"number"==typeof o?`0x${("00"+o.toString(16)).slice(-2)}`:o),_commandNums=_command.map(h=>parseInt(h,16)),checks=generateCrcCheckSum(_commandNums),command=["0xDD","0xA4",..._command,...checks,"0x77"];return getData(deviceId,{command:command,commandVerifyHandler:hexArr=>({verified:221==hexArr[0]&&38==hexArr[1],pkgLen:hexArr[3]+7}),pkgVerifyHandler:pkg=>({verified:!0})},"DDA426(充电测试)")},resolveDDA426=data=>{if(!data)return null;return{dataStr:hexArr2string(data),status:hex2string(data[2])}},getDDA427Async=async(deviceId,startTime,endTime,granularity=2,type=1)=>{const startTimeHex=startTime.toString(16).padStart(8,"0"),endTimeHex=endTime.toString(16).padStart(8,"0"),startTimeArr=[parseInt(startTimeHex.slice(0,2),16),parseInt(startTimeHex.slice(2,4),16),parseInt(startTimeHex.slice(4,6),16),parseInt(startTimeHex.slice(6,8),16)],endTimeArr=[parseInt(endTimeHex.slice(0,2),16),parseInt(endTimeHex.slice(2,4),16),parseInt(endTimeHex.slice(4,6),16),parseInt(endTimeHex.slice(6,8),16)],historyType=decimalToHex(type,2),granularityArr=decimalToHex(granularity,2),_command=["0x27","0x0A",...startTimeArr,...endTimeArr,historyType,granularityArr],checks=generateCrcCheckSum(_command),command=["0xDD","0xA4",..._command,...checks,"0x77"];return console.log("getDDA427Async getDDA427Async",startTimeHex,endTimeHex,startTimeArr,endTimeArr,granularity,command),getData(deviceId,{command:command,commandVerifyHandler:hexArr=>({verified:221==hexArr[0]&&39==hexArr[1],pkgLen:hexArr[3]+7}),pkgVerifyHandler:pkg=>{const len=pkg.length,[c1,c2]=generateCrcCheckSum(pkg.slice(2,len-3)),[_c1,_c2]=[pkg[len-3],pkg[len-2]];return{verified:c1==_c1&&c2==_c2}}},"DDA427")},resolveDDA427=data=>{if(!data)return null;const dataStr=hexArr2string(data),startTimeHex=decimalToHex(data[4])+decimalToHex(data[5])+decimalToHex(data[6])+decimalToHex(data[7]),startTime=hexToDecimal(startTimeHex),endTimeHex=decimalToHex(data[8])+decimalToHex(data[9])+decimalToHex(data[10])+decimalToHex(data[11]),endTime=hexToDecimal(endTimeHex),historyType=data[12],granularity=data[13],count=data[14];let history=[];for(let i=0;i<count;i++){const base=15+8*i,voltageHex=decimalToHex(data[base])+decimalToHex(data[base+1])+decimalToHex(data[base+2])+decimalToHex(data[base+3]),voltage=hexToDecimal(voltageHex),currentHex=decimalToHex(data[base+4])+decimalToHex(data[base+5])+decimalToHex(data[base+6])+decimalToHex(data[base+7]),current=hexToDecimal(currentHex);history.push({current:current,voltage:voltage})}return console.log("historyType",historyType),{dataStr:dataStr,startTime:startTime,endTime:endTime,historyType:historyType,granularity:granularity,count:count,history:history}},getDDA429Async=async(deviceId,id)=>{const idHex=decimalToHex(id,8),_command=["0x29","0x04",...[parseInt(idHex.slice(0,2),16),parseInt(idHex.slice(2,4),16),parseInt(idHex.slice(4,6),16),parseInt(idHex.slice(4,6),16),parseInt(idHex.slice(6,8),16)]],checks=generateCrcCheckSum(_command),command=["0xdd","0xa4",..._command,...checks,"0x77"];return getData(deviceId,{command:command,commandVerifyHandler:hexArr=>{if(221!=hexArr[0]||41!=hexArr[1])return{verified:!1,pkgLen:null};if(hexArr.length<8)return{verified:!1,pkgLen:null};if(hexArr.length>=36){const respIdHex=decimalToHex(hexArr[32])+decimalToHex(hexArr[33])+decimalToHex(hexArr[34])+decimalToHex(hexArr[35]);if(hexToDecimal(respIdHex)!==id)return{verified:!1,pkgLen:null}}return{verified:!0,pkgLen:hexArr[3]+7}},pkgVerifyHandler:pkg=>{const len=pkg.length,[c1,c2]=generateCrcCheckSum(pkg.slice(2,len-3)),[_c1,_c2]=[pkg[len-3],pkg[len-2]];return{verified:c1==_c1&&c2==_c2}}},"DDA429")},resolveDDA429=data=>{if(!data)return null;const dataStr=hexArr2string(data);let n=4;const workStatus=data[n++],chargeStatus=data[n++],chargeVoltage=hexToDecimal(decimalToHex(data[n++])+decimalToHex(data[n++])+decimalToHex(data[n++])+decimalToHex(data[n++])),chargeElectricity=hexToDecimal(decimalToHex(data[n++])+decimalToHex(data[n++])+decimalToHex(data[n++])+decimalToHex(data[n++])),chargePower=hexToDecimal(decimalToHex(data[n++])+decimalToHex(data[n++])),chargeTemperature=hexToDecimal(decimalToHex(data[n++])+decimalToHex(data[n++]))/10,chargeCapacity=hexToDecimal(decimalToHex(data[n++])+decimalToHex(data[n++])+decimalToHex(data[n++])+decimalToHex(data[n++])),chargeTime=hexToDecimal(decimalToHex(data[n++])+decimalToHex(data[n++])),chargeRemainTime=hexToDecimal(decimalToHex(data[n++])+decimalToHex(data[n++])),chargeCompleteTime=hexToDecimal(decimalToHex(data[n++])+decimalToHex(data[n++])),outputVoltagePercent=data[n++],outputElectricityPercent=data[n++],id1=hexToDecimal(decimalToHex(data[n++])+decimalToHex(data[n++])+decimalToHex(data[n++])+decimalToHex(data[n++])),outputElectricity=hexToDecimal(decimalToHex(data[n++])+decimalToHex(data[n++])+decimalToHex(data[n++])+decimalToHex(data[n++])),id=hexToDecimal(decimalToHex(data[n++])+decimalToHex(data[n++])+decimalToHex(data[n++])+decimalToHex(data[n++])),swtichStatusArr=hexToDecimal(decimalToHex(data[n++])+decimalToHex(data[n++])).toString(2).padStart(16,"0").split("").reverse(),chargeSwitch="1"==swtichStatusArr[0],preChargeSwitch="1"==swtichStatusArr[1],fanSwitch="1"==swtichStatusArr[2],protectStatusArr=hexToDecimal(decimalToHex(data[n++])+decimalToHex(data[n++])+decimalToHex(data[n++])+decimalToHex(data[n++])).toString(2).padStart(32,"0").split("").reverse();let protectStatusIndexs=[];for(let i=0;i<protectStatusArr.length;i++)"1"==protectStatusArr[i]&&protectStatusIndexs.push(i);const alarmStatusArr=hexToDecimal(decimalToHex(data[n++])+decimalToHex(data[n++])+decimalToHex(data[n++])+decimalToHex(data[n++])).toString(2).padStart(32,"0").split("").reverse();let alarmStatusIndexs=[];for(let i=0;i<alarmStatusArr.length;i++)"1"==alarmStatusArr[i]&&alarmStatusIndexs.push(i);return{dataStr:dataStr,workStatus:workStatus,chargeStatus:chargeStatus,chargeVoltage:chargeVoltage,chargeElectricity:chargeElectricity,chargePower:chargePower,chargeTemperature:chargeTemperature,chargeCapacity:chargeCapacity,chargeTime:chargeTime,chargeRemainTime:chargeRemainTime,chargeCompleteTime:chargeCompleteTime,outputVoltagePercent:outputVoltagePercent,outputElectricityPercent:outputElectricityPercent,id:id,outputElectricity:outputElectricity,id1:id1,chargeSwitch:chargeSwitch,preChargeSwitch:preChargeSwitch,fanSwitch:fanSwitch,protectStatusIndexs:protectStatusIndexs,alarmStatusIndexs:alarmStatusIndexs}};export{getDDA420Async,getDDA421Async,getDDA422Async,getDDA423Async,getDDA425Async,getDDA426Async,getDDA427Async,getDDA429Async,resolveDDA420,resolveDDA421,resolveDDA422,resolveDDA423,resolveDDA425,resolveDDA426,resolveDDA427,resolveDDA429};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import SHA256 from"crypto-js/sha256";import mqtt from"mqtt/dist/mqtt.min.js";import{set_PlanCMD_DD}from"./BleCmdAnalysis/BleCmdDD.js";import{getFFAA80Async,resolveFFAA80,set_PlanCMD_FFAA}from"./BleCmdAnalysis/BleCmdFFAA.js";import{getCMDESInfoAsync}from"./BleCmdAnalysis/BleCmdHVES.js";import{sleep}from"./BleDataProcess.js";import{decrypt}from"./rsaEncrypt.js";import{Transfer}from"./Transfer.js";class MqttServer{constructor({mqttClient:mqttClient={},MQTT_HOST:MQTT_HOST="wxs://mqtt.jiabaida.com/mqtt",DELAY_TIME:DELAY_TIME=300,networkModelUrl:networkModelUrl="https://cloud.jiabaida.com/bluetooth/server/device/networkModel",request:request}){this.timer=null,this.productKey="bms_wifi",this.is0f=!1,this.publishObj={},this.cmdCode="",this.callbackId="",this.mqttCode="",this.mqttPublish=!1,this.mqttClient=mqttClient,this.MQTT_HOST=MQTT_HOST,this.DELAY_TIME=DELAY_TIME,this.networkModelUrl=networkModelUrl,this.request=request}async getParams(item){try{return await this.request({url:`${this.networkModelUrl}?macAddr=${item.macAddr}`,method:"get"})}catch(error){throw console.error("getnetworkModel-error",error),error}}async connectMqtt(deviceObj){try{const modalData=await this.getParams(deviceObj);if(!modalData||200!==modalData.data.code)return;const mqttParam=modalData.data.data,clientId=decrypt(mqttParam.clientId),username=mqttParam.mqttUsername,password=decrypt(mqttParam.mqttSecret);console.log("连接 MQTT...");const options={clean:!0,connectTimeout:4e3,clientId:clientId,username:username,password:SHA256(password).toString(),deviceId:deviceObj.deviceId},client=mqtt.connect(this.MQTT_HOST,options);console.log("MQTT 客户端创建成功:",client),client.on("connect",res=>{console.log("res连接成功",res),client.productKey=this.productKey,this.handleMqttConnect(client,deviceObj)}),client.on("message",(topic,message)=>{this.handleMqttMessage(topic,message,client)}),client.on("reconnect",res=>console.log("MQTT 重连中...",res,client)),client.on("close",res=>this.handleMqttClose(client,res)),client.on("offline",res=>console.log("MQTT 脱机状态",res,client)),client.on("error",res=>console.error("MQTT 连接错误",res,client)),client.on("disconnect",res=>console.log("MQTT 断开连接",res,client))}catch(e){console.error("MQTT 连接异常:",e)}}handleMqttConnect(client,deviceObj){console.log("MQTT 连接成功 client",client),console.log("MQTT 连接成功 deviceObj",deviceObj),this.storeMqttClient(client),this.publishInOrder(client,deviceObj).then(()=>this.subscribeInOrder(client))}storeMqttClient(client){this.mqttClient[`${client.options.deviceId}_mqtt`]=client,console.log("存储的 MQTT 客户端:",this.mqttClient)}getTopicsAndMessages(client,deviceObj){const{productType:productType,soc:soc,moduleType:moduleType,macAddr:macAddr}=deviceObj,message=JSON.stringify({productKey:productType,soc:soc,moduleTypeKey:moduleType,macAddr:macAddr});return[{topic:`/${client.productKey}/${client.options.clientId}/device/login`,message:message}]}async publishInOrder(client,deviceObj){const topicsAndMessages=this.getTopicsAndMessages(client,deviceObj);try{for(const item of topicsAndMessages)await new Promise(resolve=>{client.publish(item.topic,item.message,()=>{resolve()})})}catch(error){console.error(`处理发布时出现错误: ${error}`)}}getSubscribeTopics(client){const{productKey:productKey}=client,clientId=client.options.clientId;return[`/${productKey}/${clientId}/device/login/reply`,`/${productKey}/${clientId}/device/passthrough/reply`,`/${productKey}/${clientId}/plat/cmd`,`/${productKey}/${clientId}/plat/passthrough`]}async subscribeInOrder(client){const subscribeTopics=this.getSubscribeTopics(client);try{for(const topic of subscribeTopics)await new Promise((resolve,reject)=>{client.subscribe(topic,err=>{err?reject(err):resolve()})})}catch(error){console.error(`订阅主题时出现错误: ${error}`)}}handleMqttMessage(topic,message,client){const clientId=topic.split("/")[2];topic!==`/${(client=Object.values(this.mqttClient).find(c=>c?.options?.clientId===clientId)||client).productKey}/${client.options.clientId}/plat/passthrough`&&topic!==`/${client.productKey}/${client.options.clientId}/plat/cmd`||this.processMessageAsync(client,message.toString())}async processMessageAsync(client,message){const msg=JSON.parse(message);this.callbackId=msg.callbackId,this.cmdCode=msg.cmdCode;let resultArray=[],codeValue=[];if("jbdPWD"===this.cmdCode){const cmdContent={2:"FFAA23010125",3:"FFAA1F010121",4:"FFAA20010122",5:"FFAA23010226"}[msg.value];codeValue=cmdContent?cmdContent.split(","):[]}else codeValue=msg.value?msg.value.split(","):[],this.is0f=2===codeValue.length;resultArray=codeValue[0]?codeValue[0].match(/.{1,2}/g):[];try{"FF"===resultArray[0]?.toUpperCase()&&"AA"===resultArray[1]?.toUpperCase()||"78"===resultArray[1]?.toUpperCase()||resultArray[1]?.toUpperCase();const publishObj={deviceId:client.options.deviceId,clientId:client.options.clientId,productKey:client.productKey,callbackId:this.callbackId,cmdCode:this.cmdCode,is0f:this.is0f,isLast:msg.isLast};this.publishObj=publishObj,this.cmdCode.toLowerCase().includes("wifi_")?await this.publishATHandle(msg.value):(this.writePublishInfoCmd(resultArray),await 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 getFFAA80Async(deviceId,ATvalue),res=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 sleep(300),this.mqttPublish=!1,uni.removeStorageSync&&uni.removeStorageSync(`${deviceId}_mqttPublish`))}catch(error){console.error(error)}}handleMqttClose(client,res){console.log("MQTT 连接关闭",res,client),client.end(()=>{this.mqttClient[`${client.options.deviceId}_mqtt`]=null})}async publishHandle(value,baseValue,voltageValue){const client=this.mqttClient[`${this.publishObj.deviceId}_mqtt`];this.publishObj.is0f&&(value=baseValue+","+voltageValue);const msg=JSON.stringify({value:value,cmdCode:this.publishObj.cmdCode,callbackId:this.publishObj.callbackId});client&&client.publish(`/${this.publishObj.productKey}/${this.publishObj.clientId}/plat/passthrough/reply`,msg,()=>{}),this.publishObj.isLast&&(await sleep(300),this.mqttPublish=!1,uni.removeStorageSync&&uni.removeStorageSync(`${this.publishObj.deviceId}_mqttPublish`))}publishPassthroughHandle({value:value,cmdCode:cmdCode},deviceId,timeOffset=3e4){const client=this.mqttClient[`${deviceId}_mqtt`];if(client){const clientTime=(new Date).getTime(),{laseCmdCode:laseCmdCode,lastPassthroughTime:lastPassthroughTime,clientId:clientId}=client?.options;if(laseCmdCode!=cmdCode||!(lastPassthroughTime&&clientTime-lastPassthroughTime<timeOffset)){const topic=`/${client?.productKey}/${clientId}/device/passthrough`,payload=JSON.stringify({value:value,cmdCode:cmdCode,clientTime:clientTime});client.publish(topic,payload,()=>{client.options.lastPassthroughTime=clientTime,client.options.laseCmdCode=cmdCode})}}}async writePublishInfoCmd(values){clearTimeout(this.timer),this.mqttPublish=!0,this.mqttCode=values[2];let res=null;res="FF"===values[0]?.toUpperCase()&&"AA"===values[1]?.toUpperCase()?await set_PlanCMD_FFAA(this.publishObj.deviceId,values.join("")):"78"===values[1]?.toUpperCase()||"50"===values[1]?.toUpperCase()?await getCMDESInfoAsync(this.publishObj.deviceId,values.join("")):await set_PlanCMD_DD(this.publishObj.deviceId,values.join(""));const content=res?.data||[];let code=Transfer.decimalToHex(content[1]);255==content[0]&&170==content[1]&&(code=Transfer.decimalToHex(content[2])),console.log("code: 回复的code",code),code.toUpperCase()==this.mqttCode.toUpperCase()&&this.publishHandle(res?.dataStr),this.timer=setTimeout(()=>{this.mqttPublish=!1},3e4)}}export{MqttServer};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import JSEncrypt from"jsencrypt";const publicKey="MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBANL378k3RiZHWx5AfJqdH9xRNBmD9wGD\n2iRe41HdTNF8RUhNnHit5NpMNtGL0NPTSSpPjjI1kJfVorRvaQerUgkCAwEAAQ==";function encrypt(txt){const encryptor=new JSEncrypt;return encryptor.setPublicKey(publicKey),encryptor.encrypt(txt)}function decrypt(txt){const encryptor=new JSEncrypt;return encryptor.setPrivateKey("MIIBVgIBADANBgkqhkiG9w0BAQEFAASCAUAwggE8AgEAAkEA4cWDRXldfRIqc2Mg\nJSAiKqvRGa0v7a4fC0j3YjzpxcIArm1Ui5d9DN8Ly7vGdUnltPuy7yC9nVQuW89+\nJ6PnowIDAQABAkEApgP1/l07KJ/2BTkrxwD0/smvDaFzL+QswcCa4GsIP7iBvPna\n003yp3UGSXfEZWiQzHfehW2UHB5DIh5YbghaqQIhAPkB8LWgJlsaC8WP90ztg0nl\n+6VBLiunF6dV0Q7eJzMlAiEA6ByIpg2ZvT+X8Zzmkw32Si/Aw5VZ/ulJ5D6/MKuS\nmScCIAjcRNBxrmu3dYvGH6qhGPbcNCQhOZ9cBr9xkkrRJNvxAiEAvVapUWs+wdWi\nSIFIxSRah+G0SNcH9pyunfVhWH5cs3kCIQDGArpiAGQ4WOO+tFDqUVaDXwhQnx2H\n5OGt/FZJpmDnUw=="),encryptor.decrypt(txt)}function decrypt2(txt){const encryptor=new JSEncrypt;return encryptor.setPrivateKey(publicKey),encryptor.decrypt(txt)}const decryptUsername=txt=>{const text=decrypt(txt);if(text)return text.substring(0,text.length-13)};export{decrypt,decrypt2,decryptUsername,encrypt};
|
package/dist/esm/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export{chunk,unique}from"./core/array.js";export{checkBluetoothStatus,checkLocationStatus,connectAsync,createBLEConnection,disConnect,foundScanDevice,getBLEDeviceCharacteristics,getBLEDeviceServices,getBluetoothAdapterState,getBluetoothPermission,initBle,isInit,notify,onBLECharacteristicValueChange,onBLEConnectionStateChange,onBleChangedConnectionState,onBluetoothAdapterStateChange,onBluetoothDeviceFound,onFoundDevice,scanHandle,startDevicesDiscovery,stopBluetoothDevicesDiscovery}from"./core/BleApiManager.js";export{eventBus,formatTimeHHmm,getOS,getPlatform,inArray,isEmpty,isNotEmpty}from"./core/commonfun.js";export{ALLOWED_MAC_PREFIX,APP_KEY_STATUS,extractModuleInfo,getRandomNum,getTypeBuyCmd,handleNewAppKey,handleOldAppKey,sendAppKey,sendEnableOrVerifyKey,sendOldAppKey,sendVerifyPwd,sendWrite1LevelPwd,verify3LevelPassword,verifyMacAddrAndKey}from"./core/keyAndPwdManager.js";export{
|
|
1
|
+
export{chunk,unique}from"./core/array.js";export{checkBluetoothStatus,checkLocationStatus,connectAsync,createBLEConnection,disConnect,enhanceDevice,foundScanDevice,getBLEDeviceCharacteristics,getBLEDeviceServices,getBluetoothAdapterState,getBluetoothPermission,initBle,isInit,notify,onBLECharacteristicValueChange,onBLEConnectionStateChange,onBleChangedConnectionState,onBluetoothAdapterStateChange,onBluetoothDeviceFound,onFoundDevice,scanHandle,startDevicesDiscovery,stopBluetoothDevicesDiscovery}from"./core/BleApiManager.js";export{ab2decimalArr,ab2hex,arrayBufferToHexArray,base64ToHexArray,checkSum,crc16modbus,crcCheckSum,decimalToHex,decimalToHex0x,decimalToTwoByteHexArray,extractBits,fromBCD,generateCheckSum,generateCrc16modbusCheck,generateCrcCheckSum,getParamBaseValue,hex2Ascii,hex2Binary,hex2string,hexArr2Assic,hexArr2ab,hexArr2string,hexArrayToModuleArrayBuffer,hexStrAscii,hexStringToBinary,hexToDecimal,isWithin30Minutes,parseDateTime,sleep,string2hexArr,stringToTwoHexArray,toBCD}from"./core/BleDataProcess.js";export{eventBus,formatTimeHHmm,getOS,getPlatform,inArray,isEmpty,isNotEmpty}from"./core/commonfun.js";export{ALLOWED_MAC_PREFIX,APP_KEY_STATUS,extractModuleInfo,getRandomNum,getTypeBuyCmd,handleNewAppKey,handleOldAppKey,sendAppKey,sendEnableOrVerifyKey,sendOldAppKey,sendVerifyPwd,sendWrite1LevelPwd,verify3LevelPassword,verifyMacAddrAndKey}from"./core/keyAndPwdManager.js";export{MqttServer}from"./core/mqttServer.js";export{OTAUpgrade}from"./core/OtaUpgrade.js";export{decrypt,decrypt2,decryptUsername,encrypt}from"./core/rsaEncrypt.js";export{TelinkApi}from"./core/TelinkApi.js";export{BLE,Logger,Observer,Transfer}from"./core/Transfer.js";export{getBaseInfo,getBaseParams,getResistance}from"./core/BleCmdAnalysis/BaseParamProtocol.js";export{getData,setMTUAsync}from"./core/BleCmdAnalysis/BleCmdAnalysis.js";export{activateAsync,enterFactory,existFactory,get3B3CAsync,get3B3CInfo,getChipTypeAsync,getDD5A0AAsync,getDD5A0EAsync,getDD5A17Async,getDD5AAllAsync,getDD5AE0Async,getDD5AE1Async,getDD5AE4Async,getDD5AFAAsync,getDD5AFBAsync,getDDA4F0Async,getDDA503Async,getDDA504Async,getDDA505Async,getDDA506Async,getDDA507Async,getDDA508Async,getDDA5DCAsync,getDDA5FAAsync,getDDA5OldAsync,getProtectCountCmd,readExistFactory,resetCapacity,resolve3B3C,resolveBMSCmd,resolveBaseDD,resolveDD5A0A,resolveDDA4F0,resolveDDA500,resolveDDA503,resolveDDA504,resolveDDA505,resolveDDA506,resolveDDA508,resolveDDA5DC,resolveDDA5FA,resolveProtections,sendBMSAsync,setDD5AE3sync,setDDA5FAAsync,setDDA5OldAsync,set_PlanCMD_3B3C,set_PlanCMD_DD}from"./core/BleCmdAnalysis/BleCmdDD.js";export{getDDA420Async,getDDA421Async,getDDA422Async,getDDA423Async,getDDA425Async,getDDA426Async,getDDA427Async,getDDA429Async,resolveDDA420,resolveDDA421,resolveDDA422,resolveDDA423,resolveDDA425,resolveDDA426,resolveDDA427,resolveDDA429}from"./core/BleCmdAnalysis/BleCmdDDA4.js";export{clearPrimaryKey,getBluetoothName,getBroadcastDataCmd,getFFAA03Async,getFFAA17Async,getFFAA25Async,getFFAA26Async,getFFAA80Async,getFFAAKeyAsync,getWiFiIP,resetFactoryData,resetSecondaryKey,resolveFFAA25,resolveFFAA26,resolveFFAA80,resolveFFAAKey,setBluetoothName,setWiFi,setWiFiSta,set_PlanCMD_FFAA,set_PlanCMD_FFAA80}from"./core/BleCmdAnalysis/BleCmdFFAA.js";export{getCMDESInfoAsync,getHVESInfoAsync,resolveHVESBMUInfo,resolveHVESBaseInfo,resolveHVESCalibrationC1Info,resolveHVESCalibrationC2Info,resolveHVESCalibrationConfigInfo,resolveHVESCalibrationInfo,resolveHVESCtInfo,resolveHVESDisCtInfo,resolveHVESElectrodeHTInfo,resolveHVESEtInfo,resolveHVESInsulationLRInfo,resolveHVESLSocInfo,resolveHVESMonoVolInfo,resolveHVESOeInfo,resolveHVESOtRisingInfo,resolveHVESOtrInfo,resolveHVESOvrInfo,resolveHVESPackInfo,resolveHVESParamsInfo,resolveHVESSumInfo,resolveHVESSumVolInfo,resolveHVESVersionInfo}from"./core/BleCmdAnalysis/BleCmdHVES.js";export{HostProtocol}from"./core/BleCmdAnalysis/ESHostProtocol.js";export{getSysParamCmd,readParamCmd,setCapacityParamCmd,setParamCmd,setSysParamCmd}from"./core/BleCmdAnalysis/readAndSetParam.js";export{batteryInfoJson,capInfoJson,capVolInfoJson,currentInfoJson,equalizerFunJson,funcAndTempFuncJson,funcJson,systemJson,tempFuncJson,tempInfoJson,voltageInfoJson}from"./core/dataJson/baseParamsJson.js";
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@jiabaida/tools",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.7",
|
|
4
4
|
"main": "dist/cjs/index.js",
|
|
5
5
|
"module": "dist/esm/index.js",
|
|
6
6
|
"exports": {
|
|
@@ -15,6 +15,7 @@
|
|
|
15
15
|
"./OtaUpgrade": "./dist/esm/core/OtaUpgrade.js",
|
|
16
16
|
"./TelinkApi": "./dist/esm/core/TelinkApi.js",
|
|
17
17
|
"./Transfer": "./dist/esm/core/Transfer.js",
|
|
18
|
+
"./mqttServer": "./dist/esm/core/mqttServer.js",
|
|
18
19
|
"./index": "./src/index.js"
|
|
19
20
|
},
|
|
20
21
|
"files": [
|
|
@@ -36,6 +37,7 @@
|
|
|
36
37
|
"@babel/core": "^7.28.0",
|
|
37
38
|
"@babel/preset-env": "^7.28.0",
|
|
38
39
|
"@rollup/plugin-babel": "^6.0.4",
|
|
40
|
+
"@rollup/plugin-commonjs": "^25.0.8",
|
|
39
41
|
"@rollup/plugin-node-resolve": "^16.0.1",
|
|
40
42
|
"babel-jest": "^30.0.5",
|
|
41
43
|
"jest": "^30.0.5",
|
|
@@ -43,7 +45,6 @@
|
|
|
43
45
|
"rollup-plugin-terser": "^7.0.2"
|
|
44
46
|
},
|
|
45
47
|
"dependencies": {
|
|
46
|
-
|
|
47
|
-
"mqtt": "^5.14.1"
|
|
48
|
+
|
|
48
49
|
}
|
|
49
50
|
}
|
|
@@ -19,7 +19,7 @@ export var isInit = false;
|
|
|
19
19
|
* @param {*} device
|
|
20
20
|
* @returns 处理后的设备信息
|
|
21
21
|
*/
|
|
22
|
-
const enhanceDevice = (device) => {
|
|
22
|
+
export const enhanceDevice = (device) => {
|
|
23
23
|
const adv = device?.advertisData;
|
|
24
24
|
if (!adv) return null;
|
|
25
25
|
if (adv) {
|
|
@@ -145,7 +145,9 @@ export const getBluetoothPermission = async (successCallback = () => {}) => {
|
|
|
145
145
|
*/
|
|
146
146
|
export const initBle = async () => {
|
|
147
147
|
const initBluetoothSuccessCb = () => {
|
|
148
|
+
console.log('初始化蓝牙成功initBluetoothSuccessCb1');
|
|
148
149
|
try {
|
|
150
|
+
if(isInit) return;
|
|
149
151
|
onBluetoothDeviceFound();
|
|
150
152
|
onBLECharacteristicValueChange();
|
|
151
153
|
onBLEConnectionStateChange();
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
1
|
+
import { ab2decimalArr, hexArr2ab, hexArr2string, sleep } from '../BleDataProcess';
|
|
2
|
+
import { eventBus, getOS, getPlatform } from '../commonfun';
|
|
3
3
|
|
|
4
4
|
const BLE_RESPONSE_TIMEOUT = 300; // 蓝牙指令响应超时
|
|
5
5
|
const STORE_MUTATION_NAME = 'setBleChangedCharacteristicValue';
|
|
@@ -21,6 +21,7 @@ async function _writeAsync(deviceId, value) {
|
|
|
21
21
|
console.log('platform: ', platform);
|
|
22
22
|
console.log('isAndroid, isIOS: ', isAndroid, isIOS);
|
|
23
23
|
const writeType = platform === 'mp-weixin' ? 'writeNoResponse' : isAndroid ? 'writeNoResponse' : 'write';
|
|
24
|
+
console.log('writeType: ', writeType);
|
|
24
25
|
uni.writeBLECharacteristicValue({
|
|
25
26
|
deviceId,
|
|
26
27
|
serviceId,
|
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import { decimalToHex,
|
|
1
|
+
import { decimalToHex, generateCrcCheckSum, hex2string, hexArr2string, hexToDecimal } from '../BleDataProcess';
|
|
2
2
|
import { getData } from './BleCmdAnalysis.js';
|
|
3
3
|
|
|
4
4
|
export const getDDA420Async = async (deviceId) => {
|
|
5
5
|
const _command = ['0x20', '0x00'];
|
|
6
|
-
const checks =
|
|
6
|
+
const checks = generateCrcCheckSum(_command);
|
|
7
7
|
const command = ['0xdd', '0xa4', ..._command, ...checks, '0x77'];
|
|
8
8
|
|
|
9
9
|
const response = 'DD03002313E10000199D27100000310F00000000000014410310060BB60BC60BC10BBA0BBD0BC1F89777';
|
|
@@ -15,7 +15,7 @@ export const getDDA420Async = async (deviceId) => {
|
|
|
15
15
|
commandVerifyHandler: (hexArr) => ({ verified: hexArr[0] == 0xdd && hexArr[1] == 0x20, pkgLen: hexArr[3] + 7 }),
|
|
16
16
|
pkgVerifyHandler: (pkg) => {
|
|
17
17
|
const len = pkg.length;
|
|
18
|
-
const [c1, c2] =
|
|
18
|
+
const [c1, c2] = generateCrcCheckSum(pkg.slice(2, len - 3));
|
|
19
19
|
const [_c1, _c2] = [pkg[len - 3], pkg[len - 2]];
|
|
20
20
|
return { verified: c1 == _c1 && c2 == _c2 };
|
|
21
21
|
},
|
|
@@ -29,7 +29,7 @@ export const getDDA420Async = async (deviceId) => {
|
|
|
29
29
|
* @param {number[]} data DDA420十六进制数据数组
|
|
30
30
|
* @returns {Object} 解析后的充电器工作信息对象
|
|
31
31
|
* @returns {string} dataStr 十六进制数据数组转换后的字符串
|
|
32
|
-
* @returns {number} workStatus 工作状态:1=待机,2=就绪,3=激活电池中,4=通讯充电中,5=调试充电中,6=盲充中,7=结束充电
|
|
32
|
+
* @returns {number} workStatus 工作状态:1=待机,2=就绪,3=激活电池中,4=通讯充电中,5=调试充电中,6=盲充中,7=结束充电 8=停止充电(异常) 9=充电比对中 10=校准中 11=老化中 12=握手充电中 13=小电流充电中
|
|
33
33
|
* @returns {number} chargeStatus 充电状态:1=恒流,2=恒压,3=涓流
|
|
34
34
|
* @returns {number} chargeVoltage 充电电压,单位毫伏(mV)
|
|
35
35
|
* @returns {number} chargeElectricity 充电电流,单位毫安(mA)
|
|
@@ -51,7 +51,7 @@ export const getDDA420Async = async (deviceId) => {
|
|
|
51
51
|
* @returns {number} ratedPower 充电器额定功率,单位瓦特(W)
|
|
52
52
|
* @returns {number} inputVoltage 输入电压,单位毫伏(mV)
|
|
53
53
|
*/
|
|
54
|
-
export const resolveDDA420 =
|
|
54
|
+
export const resolveDDA420 = (data) => {
|
|
55
55
|
if (!data) return null;
|
|
56
56
|
const dataStr = hexArr2string(data);
|
|
57
57
|
let n = 4; // 起始偏移
|
|
@@ -251,7 +251,7 @@ export const getDDA420Async = async (deviceId) => {
|
|
|
251
251
|
* @param {number[]} data DDA421十六进制数据数组
|
|
252
252
|
* @returns {Object} 解析后的充电电池信息对象
|
|
253
253
|
*/
|
|
254
|
-
export const resolveDDA421 =
|
|
254
|
+
export const resolveDDA421 = (data) => {
|
|
255
255
|
if (!data) return null;
|
|
256
256
|
const dataStr = hexArr2string(data);
|
|
257
257
|
// 电池电压 4BYTE [4,5,6,7]
|
|
@@ -335,7 +335,7 @@ export const getDDA420Async = async (deviceId) => {
|
|
|
335
335
|
'DDA425'
|
|
336
336
|
);
|
|
337
337
|
}
|
|
338
|
-
export const resolveDDA425 =
|
|
338
|
+
export const resolveDDA425 = (data) => {
|
|
339
339
|
if (!data) return null;
|
|
340
340
|
const dataStr = hexArr2string(data);
|
|
341
341
|
return {
|
|
@@ -384,7 +384,7 @@ export const getDDA420Async = async (deviceId) => {
|
|
|
384
384
|
* @param {number[]} data DDA422响应数据
|
|
385
385
|
* @returns {Object} 解析结果
|
|
386
386
|
*/
|
|
387
|
-
export const resolveDDA422 =
|
|
387
|
+
export const resolveDDA422 = (data) => {
|
|
388
388
|
if (!data) return null;
|
|
389
389
|
const dataStr = hexArr2string(data);
|
|
390
390
|
// 起始地址 2BYTE [4,5]
|
|
@@ -447,14 +447,77 @@ export const getDDA420Async = async (deviceId) => {
|
|
|
447
447
|
'DDA423'
|
|
448
448
|
);
|
|
449
449
|
}
|
|
450
|
-
export const resolveDDA423 =
|
|
450
|
+
export const resolveDDA423 = (data) => {
|
|
451
451
|
if (!data) return null;
|
|
452
452
|
const dataStr = hexArr2string(data);
|
|
453
453
|
return {
|
|
454
454
|
dataStr,
|
|
455
455
|
status: hex2string(data[2])
|
|
456
456
|
};
|
|
457
|
+
}
|
|
458
|
+
/** 充电器充电测试 26 指令
|
|
459
|
+
* 发送: DD A4 26 09 <测试模式1B> <输出电压4B mV> <输出电流4B mA> CRC_H CRC_L 77
|
|
460
|
+
* 响应: DD 26 <状态位1B> 00 CRC_H CRC_L 77 (或: DD 26 <状态位> 00 ...)
|
|
461
|
+
* @param {string} deviceId 设备ID
|
|
462
|
+
* @param {number} testMode 测试模式 1=调试模式 2=老化模式
|
|
463
|
+
* @param {number} outputVoltage 输出目标电压(mV) 0~4294967295
|
|
464
|
+
* @param {number} outputCurrent 输出目标电流(mA) 0~4294967295
|
|
465
|
+
* @returns {Promise<number[]|null>} 原始响应数据数组; 失败返回 null
|
|
466
|
+
*/
|
|
467
|
+
export const getDDA426Async = async (deviceId, testMode = 0, outputVoltage = 0, outputCurrent = 0) => {
|
|
468
|
+
// 保护参数范围(简单防御,防止生成溢出字节/异常写入)
|
|
469
|
+
const clamp32 = (v) => {
|
|
470
|
+
v = Number(v) || 0; if (v < 0) v = 0; if (v > 0xFFFFFFFF) v = 0xFFFFFFFF; return v;
|
|
471
|
+
};
|
|
472
|
+
testMode = testMode === 2 ? 2 : 0; // 只允许 0 / 2
|
|
473
|
+
outputVoltage = clamp32(outputVoltage);
|
|
474
|
+
outputCurrent = clamp32(outputCurrent);
|
|
475
|
+
|
|
476
|
+
// 转 4 字节 (大端) 十六进制 -> 数组
|
|
477
|
+
const to4Bytes = (val) => {
|
|
478
|
+
const hex = commonfun.decimalToHex(val, 8); // 8位十六进制字符串
|
|
479
|
+
return [0, 2, 4, 6].map(i => parseInt(hex.slice(i, i + 2), 16));
|
|
480
|
+
};
|
|
481
|
+
const voltageArr = to4Bytes(outputVoltage);
|
|
482
|
+
const currentArr = to4Bytes(outputCurrent);
|
|
483
|
+
|
|
484
|
+
// 长度 = 1(模式) +4(电压)+4(电流) = 9
|
|
485
|
+
const lengthHex = commonfun.decimalToHex(9, 2); // '09'
|
|
486
|
+
const _command = ['0x26', `0x${lengthHex}`, testMode & 0xFF, ...voltageArr, ...currentArr].map(o => typeof o === 'number' ? `0x${('00' + o.toString(16)).slice(-2)}` : o);
|
|
487
|
+
// 去掉 0x 前缀转成数值数组生成 CRC
|
|
488
|
+
const _commandNums = _command.map(h => parseInt(h, 16));
|
|
489
|
+
const checks = generateCrcCheckSum(_commandNums);
|
|
490
|
+
const command = ['0xDD', '0xA4', ..._command, ...checks, '0x77'];
|
|
491
|
+
|
|
492
|
+
return getData(
|
|
493
|
+
deviceId,
|
|
494
|
+
{
|
|
495
|
+
command,
|
|
496
|
+
commandVerifyHandler: (hexArr) => ({ verified: hexArr[0] == 0xdd && hexArr[1] == 0x26, pkgLen: hexArr[3] + 7 }),
|
|
497
|
+
pkgVerifyHandler: (pkg) => {
|
|
498
|
+
// const len = pkg.length;
|
|
499
|
+
// const [c1, c2] = this.generateCrcCheckSum(pkg.slice(2, len - 3));
|
|
500
|
+
// const [_c1, _c2] = [pkg[len - 3], pkg[len - 2]];
|
|
501
|
+
// return { verified: c1 == _c1 && c2 == _c2 };
|
|
502
|
+
return { verified: true }
|
|
503
|
+
},
|
|
504
|
+
},
|
|
505
|
+
'DDA426(充电测试)',
|
|
506
|
+
3000
|
|
507
|
+
);
|
|
508
|
+
}
|
|
509
|
+
|
|
510
|
+
/** 解析充电器充电测试 26 指令响应
|
|
511
|
+
* @param {number[]} data
|
|
512
|
+
* @returns {{dataStr:string,status:string}|null}
|
|
513
|
+
*/
|
|
514
|
+
|
|
515
|
+
export const resolveDDA426 = (data) => {
|
|
516
|
+
if (!data) return null;
|
|
517
|
+
const dataStr = hexArr2string(data);
|
|
518
|
+
return { dataStr, status: hex2string(data[2]) };
|
|
457
519
|
}
|
|
520
|
+
|
|
458
521
|
/** 查询充电历史数据27指令
|
|
459
522
|
* @param {*} deviceId
|
|
460
523
|
* @param {number} startTime 充电起始时间(秒,4字节)
|
|
@@ -509,7 +572,7 @@ export const getDDA420Async = async (deviceId) => {
|
|
|
509
572
|
* @param {number[]} data DDA427响应数据
|
|
510
573
|
* @returns {Object} 解析结果
|
|
511
574
|
*/
|
|
512
|
-
export const resolveDDA427 =
|
|
575
|
+
export const resolveDDA427 = (data) => {
|
|
513
576
|
if (!data) return null;
|
|
514
577
|
const dataStr = hexArr2string(data);
|
|
515
578
|
// 充电起始时间 4BYTE [4,5,6,7]
|
|
@@ -605,7 +668,7 @@ export const getDDA420Async = async (deviceId) => {
|
|
|
605
668
|
'DDA429'
|
|
606
669
|
);
|
|
607
670
|
}
|
|
608
|
-
export const resolveDDA429 =
|
|
671
|
+
export const resolveDDA429 = (data) => {
|
|
609
672
|
if (!data) return null;
|
|
610
673
|
const dataStr = hexArr2string(data);
|
|
611
674
|
let n = 4; // 起始偏移
|
|
@@ -1,7 +1,8 @@
|
|
|
1
|
+
export * from './BaseParamProtocol';
|
|
1
2
|
export * from './BleCmdAnalysis';
|
|
2
|
-
export * from './BleCmdFFAA';
|
|
3
3
|
export * from './BleCmdDD';
|
|
4
|
-
export * from './
|
|
5
|
-
export * from './
|
|
6
|
-
export * from './BleCmdHVES'
|
|
7
|
-
export * from './ESHostProtocol'
|
|
4
|
+
export * from './BleCmdDDA4';
|
|
5
|
+
export * from './BleCmdFFAA';
|
|
6
|
+
export * from './BleCmdHVES';
|
|
7
|
+
export * from './ESHostProtocol';
|
|
8
|
+
export * from './readAndSetParam';
|
package/src/core/mqttServer.js
CHANGED
|
@@ -1,15 +1,15 @@
|
|
|
1
|
-
import
|
|
2
|
-
import
|
|
3
|
-
import CryptoJS from 'crypto-js/crypto-js.js';
|
|
4
|
-
import mqtt from 'mqtt/dist/mqtt.js';
|
|
1
|
+
import SHA256 from 'crypto-js/sha256';
|
|
2
|
+
import mqtt from 'mqtt/dist/mqtt.min.js';
|
|
5
3
|
import { set_PlanCMD_DD } from './BleCmdAnalysis/BleCmdDD';
|
|
6
4
|
import { getFFAA80Async, resolveFFAA80, set_PlanCMD_FFAA } from './BleCmdAnalysis/BleCmdFFAA';
|
|
7
|
-
import { Transfer } from './Transfer.js';
|
|
8
5
|
import { getCMDESInfoAsync } from './BleCmdAnalysis/BleCmdHVES.js';
|
|
6
|
+
import { sleep } from './BleDataProcess.js';
|
|
7
|
+
import { decrypt } from './rsaEncrypt.js';
|
|
8
|
+
import { Transfer } from './Transfer.js';
|
|
9
9
|
|
|
10
10
|
// 新的MQTT服务类
|
|
11
|
-
class MqttServer {
|
|
12
|
-
constructor({ mqttClient = {}, MQTT_HOST = '
|
|
11
|
+
export class MqttServer {
|
|
12
|
+
constructor({ mqttClient = {}, MQTT_HOST = 'wxs://mqtt.jiabaida.com/mqtt', DELAY_TIME = 300, networkModelUrl = 'https://cloud.jiabaida.com/bluetooth/server/device/networkModel', request }) {
|
|
13
13
|
this.timer = null;
|
|
14
14
|
this.productKey = 'bms_wifi';
|
|
15
15
|
this.is0f = false;
|
|
@@ -56,7 +56,7 @@ class MqttServer {
|
|
|
56
56
|
connectTimeout: 4000,
|
|
57
57
|
clientId,
|
|
58
58
|
username,
|
|
59
|
-
password:
|
|
59
|
+
password: SHA256(password).toString(),
|
|
60
60
|
deviceId: deviceObj.deviceId,
|
|
61
61
|
};
|
|
62
62
|
const client = mqtt.connect(this.MQTT_HOST, options);
|
|
@@ -293,4 +293,4 @@ class MqttServer {
|
|
|
293
293
|
}
|
|
294
294
|
}
|
|
295
295
|
|
|
296
|
-
export default MqttServer;
|
|
296
|
+
// export default MqttServer;
|
package/src/core/rsaEncrypt.js
CHANGED
package/src/index.js
CHANGED
|
@@ -2,10 +2,12 @@
|
|
|
2
2
|
export * from './core/array';
|
|
3
3
|
export * from './core/BleApiManager';
|
|
4
4
|
export * from './core/BleCmdAnalysis/index';
|
|
5
|
+
export * from './core/BleDataProcess';
|
|
5
6
|
export * from './core/commonfun';
|
|
7
|
+
export * from './core/dataJson/index.js';
|
|
6
8
|
export * from './core/keyAndPwdManager';
|
|
9
|
+
export * from './core/mqttServer.js';
|
|
7
10
|
export * from './core/OtaUpgrade';
|
|
11
|
+
export * from './core/rsaEncrypt';
|
|
8
12
|
export * from './core/TelinkApi';
|
|
9
13
|
export * from './core/Transfer';
|
|
10
|
-
export * from './core/BleDataProcess'
|
|
11
|
-
export * from './core/dataJson/index.js'
|