"use strict";const e=require("../common/vendor.js"),t=require("./env.js"),o=require("./api.js"),c=require("./storage.js"),s=require("./basic.js"),i=require("./format.js"),n=require("./log.js"),a=12432,r=12433,l=12352,u=12289,d=12293,h=12292,k=12300,f=12336,I=2,g=3,m=19,w=41;let y,p,R,S=null,b=null;const v=e.defineStore("starCloud",{state:()=>({env:null,clientId:null,clientSecret:null,envVersion:"",lockInfo:null,serverTimestamp:0,timeDifference:0,searchDeviceList:[],userInfo:null,accountInfo:null,messageCount:1,isReportLog:!1}),actions:{initStarCloud(t){const{clientId:o,clientSecret:c,env:i}=t,n=e.index.getAccountInfoSync();this.envVersion=n.miniProgram.envVersion,this.isReportLog=t.isReportLog,this.env=i||"XHJ",this.clientId=o,this.clientSecret=c,s.onBLECharacteristicValueChange(this.listenCharacteristicValue)},async register(){const{code:e,data:t,message:c}=await o.starCloudCreateUser({clientId:this.clientId,clientSecret:this.clientSecret});return new s.Result(e,t,c)},logout(e){var t;const{uid:o}=e;(null==(t=this.accountInfo)?void 0:t.uid)===o&&(this.userInfo=null,this.accountInfo=null,this.lockInfo=null,c.removeStorage("starCloudToken"))},async selectLock(e){const{accountInfo:t,lockId:i}=e,n=await this.login(t);if(n.code!==s.Result.Success.code)return n;const{code:a,data:r,message:l}=await o.getLockDetailRequest({lockId:i});if(a===s.Result.Success.code){this.lockInfo=r;let e=c.getStorage("starLockList");if(e||(e={}),e[t.uid]){const o=e[t.uid].findIndex((e=>e.lockId===i));-1===o?e[t.uid].push(this.lockInfo):(this.lockInfo.token=e[t.uid][o].token,e[t.uid][o]=this.lockInfo),c.setStorage("starLockList",e)}else e[t.uid]=[this.lockInfo],c.setStorage("starLockList",e)}else{const e=c.getStorage("starLockList");if(e[t.uid]){const o=e[t.uid].findIndex((e=>e.lockId===i));if(-1!==o)return this.lockInfo=e[t.uid][o],new s.Result(s.Result.Success.code,this.lockInfo)}}return new s.Result(a,r,l)},async openDoor(t){const{accountInfo:o,type:c}=t;n.log.info(new s.Result(s.Result.Success.code,{lockName:this.lockInfo.bluetooth.bluetoothDeviceName,lockId:this.lockInfo.lockId,uid:o.uid,time:(new Date).getTime()},"开始开门"));const a=await this.login(o);if(a.code!==s.Result.Success.code)return a;if(n.log.info(new s.Result(a.code,{lockName:this.lockInfo.bluetooth.bluetoothDeviceName,lockId:this.lockInfo.lockId,uid:o.uid,time:(new Date).getTime()},`登录星云账号: ${a.message}`)),!t.connected){const e=await s.searchAndConnectDevice(this.lockInfo.bluetooth.bluetoothDeviceName);if(n.log.info(new s.Result(e.code,{lockName:this.lockInfo.bluetooth.bluetoothDeviceName,lockId:this.lockInfo.lockId,uid:o.uid,time:(new Date).getTime()},`连接设备: ${e.message}`)),e.code!==s.Result.Success.code)return e;this.updateLockInfo(e.data)}const r=await this.checkLockUser();if(r.code!==s.Result.Success.code)return r;n.log.info(new s.Result(r.code,{lockName:this.lockInfo.bluetooth.bluetoothDeviceName,lockId:this.lockInfo.lockId,uid:o.uid,time:(new Date).getTime()},`确认是否为锁用户: ${r.message}`));let l,u="";if(this.lockInfo.lockSetting.appUnlockOnline){const e=await this.getNetToken();if(e.code!==s.Result.Success.code)return e;u=e.data.token}n.log.info(new s.Result(r.code,{lockName:this.lockInfo.bluetooth.bluetoothDeviceName,lockId:this.lockInfo.lockId,uid:o.uid,time:(new Date).getTime()},`判断是否需要联网token: ${this.lockInfo.lockSetting.appUnlockOnline}`)),l="close"===c?this.lockInfo.lockSetting.appUnlockOnline?33:32:this.lockInfo.lockSetting.appUnlockOnline?1:0;const h=this.lockInfo.bluetooth.bluetoothDeviceName,k=this.accountInfo.uid.toString(),f=Math.ceil((new Date).getTime()/1e3)+this.timeDifference,I=this.createPackageHeader(3,104),g=new Uint8Array(104);g[0]=d/256,g[1]=d%256;for(let e=0;e{var c,i;const n=await s.getBluetoothDevices();if(n.code===s.Result.Success.code){const a=n.data;!1===o&&a.length>0&&(o=!0),(new Date).getTime()-t>1e4&&!o&&(R&&clearInterval(R),e(s.Result.NotAvailableWeChatNearbyDevicesEmpty));const r=[];for(let e=0;e(console.log("停止搜索"),R&&clearInterval(R),await s.stopBluetoothDevicesDiscovery()),async bindDevice(e){const{accountInfo:t,name:c}=e,i=await this.login(t);if(i.code!==s.Result.Success.code)return i;const n=this.searchDeviceList.find((e=>e.name===c)),a=await s.createBLEConnection(n.deviceId);if(a.code===s.Result.Success.code){this.updateLockInfo({...a.data,bluetooth:{bluetoothDeviceId:n.deviceId,bluetoothDeviceName:n.name}});const e=await this.getPublicKey();if(e.code!==s.Result.Success.code)return e;const t=await this.getCommKey();if(t.code!==s.Result.Success.code)return t;const c=await this.getLockStatus();if(c.code!==s.Result.Success.code)return c;const i=Math.ceil((new Date).getTime()/1e3),r=(Math.floor(9e5*Math.random())+1e5).toString(),l=await this.addLockUser({params:{name:this.lockInfo.bluetooth.bluetoothDeviceName,keyId:"0",authUid:this.accountInfo.uid.toString(),uid:this.accountInfo.uid.toString(),openMode:1,keyType:0,startDate:i,expireDate:4294967295,useCountLimit:65535,isRound:0,weekRound:0,startHour:0,startMin:0,endHour:0,endMin:0,role:255,password:r},disconnect:!0});if(l.code!==s.Result.Success.code)return l;s.offBluetoothAdapterStateChange(),s.closeBluetoothAdapter();const u={lockAlias:this.lockInfo.bluetooth.bluetoothDeviceName,lockInfo:{...this.lockInfo.lockConfig,adminPwd:r},bluetooth:this.lockInfo.bluetooth,lockUserNo:this.lockInfo.lockUserNo,pwdTimestamp:this.lockInfo.pwdTimestamp,featureValue:this.lockInfo.featureValue,featureSettingValue:this.lockInfo.featureSettingValue,featureSettingParams:this.lockInfo.featureSettingParams},d=await o.bindLockRequest(u);return d.code===s.Result.Success.code&&this.updateLockInfo({lockId:d.data.lockId,keyId:d.data.keyId,adminPwd:r}),new s.Result(d.code,{lock:this.lockInfo},d.message)}return a},async removeBadLock(e){const{accountInfo:t,lockIds:i}=e,n=await this.login(t);if(n.code!==s.Result.Success.code)return n;const{code:a,message:r}=await o.removeBadLockRequest({lockIds:e.lockIds});if(a===s.Result.Success.code){const e=c.getStorage("starLockList");e[t.uid]&&(i.forEach((o=>{const c=e[t.uid].findIndex((e=>e.lockId===o));-1!==c&&e[t.uid].splice(c,1)})),c.setStorage("starLockList",e))}return new s.Result(a,{},r)},async deleteLock(t){const{accountInfo:o}=t,c=await this.login(o);if(c.code!==s.Result.Success.code)return c;if(!t.connected){const e=await s.searchAndConnectDevice(this.lockInfo.bluetooth.bluetoothDeviceName);if(e.code!==s.Result.Success.code)return e;this.updateLockInfo(e.data)}const n=await this.checkLockUser();if(n.code!==s.Result.Success.code)return n;const{token:a,bluetooth:{publicKey:r,privateKey:l}}=this.lockInfo,u=this.lockInfo.uid.toString(),d=this.lockInfo.bluetooth.bluetoothDeviceName,k=this.createPackageHeader(3,83),f=new Uint8Array(83);f[0]=h/256,f[1]=h%256;for(let e=0;e{})),s.Result.Success;const{code:n,data:a,message:r}=await o.getStarCloudToken({username:e.username,password:e.password,clientId:this.clientId,clientSecret:this.clientSecret});return n===s.Result.Success.code&&(this.userInfo=a,this.accountInfo={username:e.username,password:e.password,token:a.access_token,uid:a.uid},c.setStorage("starCloudToken",a.access_token),t[a.uid]={uid:a.uid,username:e.username,password:e.password,token:a.access_token},c.setStorage("starCloudAccount",t),i[a.uid]=a,c.setStorage("starCloudUser",a),this.getServerTimestamp().then((()=>{}))),new s.Result(n,{},r)},async getPublicKey(){const e=this.createPackageHeader(0,42),t=new Uint8Array(42);t[0]=a/256,t[1]=a%256;const o=this.lockInfo.bluetooth.bluetoothDeviceName;for(let s=0;s{const c=setTimeout((()=>{o(s.Result.Fail)}),2e4);S=async i=>{if(i.code===s.Result.NotTokenLock.code)n.log.info(new s.Result(i.code,{lockName:this.lockInfo.bluetooth.bluetoothDeviceName,lockId:this.lockInfo.lockId,time:(new Date).getTime()},`token过期:${i.message}`)),o(await e({...t,connected:!0}));else if(i.code===s.Result.NotRegisteredLock.code){const i=await this.checkLockUser(!0);i.code===s.Result.Success.code?o(await e({...t,connected:!0})):(clearTimeout(c),o(i))}else clearTimeout(c),t.disconnect&&await this.disconnectDevice(),console.log("写入结果",i,e,t),n.log.info(new s.Result(i.code,{lockName:this.lockInfo.bluetooth.bluetoothDeviceName,lockId:this.lockInfo.lockId,time:(new Date).getTime()},`开门结果:${i.message}`)),o(i)}}))},async checkLockUser(e=!1){if(0===this.lockInfo.lockUserNo||e){const e=Math.floor((new Date).getTime()/1e3),t=(Math.floor(9e5*Math.random())+1e5).toString();console.log("用户未添加,开始添加用户");const c={name:this.lockInfo.bluetooth.bluetoothDeviceName,keyId:this.lockInfo.keyId.toString(),authUid:this.lockInfo.uid.toString(),uid:this.accountInfo.uid.toString(),openMode:1,keyType:0,startDate:0===this.lockInfo.startDate?e:Math.floor(this.lockInfo.startDate/1e3),expireDate:0===this.lockInfo.endDate?4294967295:Math.floor(this.lockInfo.endDate/1e3),useCountLimit:3===this.lockInfo.keyType?1:65535,isRound:4===this.lockInfo.keyType?1:0,weekRound:4===this.lockInfo.keyType?i.convertWeekdaysToNumber(this.lockInfo.weekDays):0,startHour:4===this.lockInfo.keyType?new Date(this.lockInfo.startDate).getHours():0,startMin:4===this.lockInfo.keyType?new Date(this.lockInfo.startDate).getMinutes():0,endHour:4===this.lockInfo.keyType?new Date(this.lockInfo.endDate).getHours():0,endMin:4===this.lockInfo.keyType?new Date(this.lockInfo.endDate).getMinutes():0,role:0,password:t},n=await this.addLockUser({params:c,disconnect:!1});if(console.log("添加用户蓝牙结果",n),n.code===s.Result.Success.code){const{code:e}=await o.updateLockUserNoRequest({keyId:this.lockInfo.keyId,lockUserNo:this.lockInfo.lockUserNo});return console.log("添加用户请求结果",e),s.Result.Success}if(n.code===s.Result.NotMoreKeyLock.code){console.log("用户达上限,开始清理用户");const{code:e}=await this.cleanLockUser();return console.log("清理用户蓝牙结果",e),e===s.Result.Success.code?await this.checkLockUser():s.Result.Fail}return n.code===s.Result.ReadyHasKeyLock.code?s.Result.Success:s.Result.Fail}return s.Result.Success},updateLockInfo(e){this.lockInfo={...this.lockInfo,...e};const t=c.getStorage("starLockList");if(t[this.accountInfo.uid]){const e=t[this.accountInfo.uid].findIndex((e=>e.lockId===this.lockInfo.lockId));-1!==e&&(t[this.accountInfo.uid][e]=this.lockInfo),c.setStorage("starLockList",t)}},listenCharacteristicValue(e){if(e.deviceId===this.lockInfo.deviceId){let t=new Uint8Array(e.value);if(239===t[0]&&1===t[1]&&238===t[2]&&2===t[3])p=256*t[8]+t[9],p+14>t.length?y=t:this.parsingCharacteristicValue(t).then((()=>{}));else if(y){const e=new Uint8Array(y.length+t.length);e.set(y,0),e.set(t,y.length),y=e,p+14===y.length&&(this.parsingCharacteristicValue(y).then((()=>{})),y=null)}}},async parsingCharacteristicValue(t){if(32===t[7])256*t[12]+t[13]===a&&(t[14]===s.Result.Success.code&&this.updateLockInfo({bluetooth:{...this.lockInfo.bluetooth,publicKey:[...t.slice(15,31)]}}),S(new s.Result(t[14])));else if(34===t[7]){const o=t.slice(12,t.length-2),c=new Uint8Array(16);for(let e=0;e0){const e=[],t=a[6]||0;for(let o=0;o0===e))?null:i.uint8ArrayToString(t);const c={type:a[7+17*o],user:256*a[8+17*o]+a[9+17*o],date:1e3*i.arrayToTimestamp(a.slice(10+17*o,14+17*o)),success:1,password:t};e.push(c)}const{code:c,message:n}=await o.uploadRecordRequest({records:e,lockId:this.lockInfo.lockId});S(new s.Result(c,{count:t},n))}else S(new s.Result(a[2]))}break;case d:this.updateLockInfo({token:a.slice(2,6),electricQuantity:a[7],electricQuantityStandby:a[9]}),a[6]===s.Result.Success.code&&o.updateElectricQuantityRequest({lockId:this.lockInfo.lockId,electricQuantity:a[7],electricQuantityStandby:a[9]}),S(new s.Result(a[6],{lock:this.lockInfo}));break;case h:if(this.updateLockInfo({token:a.slice(2,6)}),a[6]===s.Result.Success.code){const{code:e,message:t}=await o.deleteLockRequest({lockId:this.lockInfo.lockId});if(e===s.Result.Success.code){const e=c.getStorage("starLockList");if(e[this.accountInfo.uid]){const t=e[this.accountInfo.uid].findIndex((e=>e.lockId===this.lockInfo.lockId));-1!==t&&e[this.accountInfo.uid].splice(t,1),c.setStorage("starLockList",e)}}S(new s.Result(e,{},t))}else S(new s.Result(a[6]));break;default:this.updateLockInfo({token:a.slice(2,6)}),console.log("默认结果",a[6],this.lockInfo.token),S(new s.Result(a[6]))}}},getConfig(){return{...t.configs[this.env],version:t.version,buildNumber:t.buildNumber}},createPackageHeader(e,t){let o=new Uint8Array(12);if(o[0]=239,o[1]=1,o[2]=238,o[3]=2,o[4]=1,o[5]=this.messageCount/256,o[6]=this.messageCount%256,this.messageCount++,o[7]=0===e?32:2===e?34:35,0===e)o[8]=t/256,o[9]=t%256;else{const e=16*Math.ceil(t/16);o[8]=e/256,o[9]=e%256}return o[10]=t/256,o[11]=t%256,o},async disconnectDevice(){return await s.closeBLEConnection(this.lockInfo.deviceId)}}});exports.useStarCloudStore=v;