2 lines
28 KiB
JavaScript
2 lines
28 KiB
JavaScript
"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<h.length;e++)g[e+2]=h.charCodeAt(e);for(let e=0;e<k.length;e++)g[e+42]=k.charCodeAt(e);g[62]=l,g.set(i.timestampToArray(f),63),console.log("开门时token",this.lockInfo.token),g.set(this.lockInfo.token||i.timestampToArray(f),67),g[71]=16;const m=i.md5Encrypt(h+k,this.lockInfo.token||i.timestampToArray(f),this.lockInfo.bluetooth.signKey);g.set(m,72);for(let e=0;e<u.length;e++)g[e+88]=u.charCodeAt(e);const w=e.src.sm4.encrypt(g,this.lockInfo.bluetooth.privateKey,{mode:"ecb",output:"array"}),y=i.createPackageEnd(I,w);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 p=await s.writeBLECharacteristicValue(this.lockInfo.deviceId,this.lockInfo.serviceId,this.lockInfo.writeCharacteristicId,y);return p.code!==s.Result.Success.code?p:(n.log.info(new s.Result(p.code,{lockName:this.lockInfo.bluetooth.bluetoothDeviceName,lockId:this.lockInfo.lockId,uid:o.uid,time:(new Date).getTime()},`写入完成:${p.message}`)),this.getWriteResult(this.openDoor,t))},async getOfflinePassword(e){const{accountInfo:t,password:c}=e,i=await this.login(t);return i.code!==s.Result.Success.code?i:await o.getOfflinePasswordRequest({...c,lockId:this.lockInfo.lockId})},async customPassword(t){const{accountInfo:o,password:c}=t,n=await this.login(o);if(n.code!==s.Result.Success.code)return n;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 a=await this.checkLockUser();if(a.code!==s.Result.Success.code)return a;b=c;let{pwdNo:r,operate:l,keyboardPwd:u,startDate:d,endDate:h,pwdRight:k}=c;const I=this.accountInfo.uid.toString(),m=this.lockInfo.keyId.toString(),w=k;d=Math.floor(d/1e3),h=Math.floor(h/1e3),u=u.toString(),r||(r=0);const y=this.createPackageHeader(3,119),p=new Uint8Array(119);p[0]=f/256,p[1]=f%256,p[2]=g,p[3]=116;for(let e=0;e<m.length;e++)p[e+4]=m.charCodeAt(e);for(let e=0;e<I.length;e++)p[e+44]=I.charCodeAt(e);p[64]=r/256,p[65]=r%256,p[66]=l,p[67]=w;for(let e=0;e<u.length;e++)p[e+68]=u.charCodeAt(e);p[88]=65535/256,p[89]=255,p.set(this.lockInfo.token||new Uint8Array([0,0,0,0]),90),p.set(i.timestampToArray(d),94),p.set(i.timestampToArray(h),98),p[102]=16;const R=i.md5Encrypt(m+I,this.lockInfo.token||new Uint8Array([0,0,0,0]),this.lockInfo.bluetooth.signKey);p.set(R,103);const S=e.src.sm4.encrypt(p,this.lockInfo.bluetooth.privateKey,{mode:"ecb",output:"array"}),v=i.createPackageEnd(y,S),D=await s.writeBLECharacteristicValue(this.lockInfo.deviceId,this.lockInfo.serviceId,this.lockInfo.writeCharacteristicId,v);return D.code!==s.Result.Success.code?D:this.getWriteResult(this.customPassword,t)},async searchDevice(e){const t=await s.startBluetoothDevicesDiscovery();if(t.code===s.Result.Success.code){const t=(new Date).getTime();let o=!1;R=setInterval((async()=>{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<a.length;e++)if(null==(c=a[e])?void 0:c.advertisServiceUUIDs){const t=null==(i=a[e])?void 0:i.advertisServiceUUIDs[0];t&&"758824"===t.slice(2,8)&&"00"===t.slice(30,32)&&r.push(a[e])}this.searchDeviceList=r,e(new s.Result(s.Result.Success.code,{list:r}))}else e(n)}),1e3)}else e(t)},stopSearchDevice:async()=>(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<d.length;e++)f[e+2]=d.charCodeAt(e);for(let e=0;e<u.length;e++)f[e+42]=u.charCodeAt(e);f.set(a||new Uint8Array([0,0,0,0]),62),f[66]=16;const I=i.md5Encrypt(d,a||new Uint8Array([0,0,0,0]),r);f.set(I,67);const g=e.src.sm4.encrypt(f,l,{mode:"ecb",output:"array"}),m=i.createPackageEnd(k,g),w=await s.writeBLECharacteristicValue(this.lockInfo.deviceId,this.lockInfo.serviceId,this.lockInfo.writeCharacteristicId,m);return w.code!==s.Result.Success.code?w:this.getWriteResult(this.deleteLock,t)},async updateAdminPassword(t){const{adminPwd:o,accountInfo:c}=t,n=await this.login(c);if(n.code!==s.Result.Success.code)return n;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 a=await this.checkLockUser();if(a.code!==s.Result.Success.code)return a;b=t;const r=this.lockInfo.uid.toString(),l=this.lockInfo.keyId.toString(),u=Math.floor(this.lockInfo.startDate/1e3),d=Math.floor(this.lockInfo.endDate/1e3),h=this.createPackageHeader(3,117),k=new Uint8Array(117);k[0]=f/256,k[1]=f%256,k[2]=I,k[3]=114;for(let e=0;e<l.length;e++)k[e+4]=l.charCodeAt(e);for(let e=0;e<r.length;e++)k[e+44]=r.charCodeAt(e);k[64]=1/256,k[65]=1;for(let e=0;e<o.length;e++)k[e+66]=o.charCodeAt(e);k[86]=255/256,k[87]=255,k.set(this.lockInfo.token||new Uint8Array([0,0,0,0]),88),k.set(i.timestampToArray(u),92),k.set(i.timestampToArray(d),96),k[100]=16;const g=i.md5Encrypt(l+r,this.lockInfo.token||new Uint8Array([0,0,0,0]),this.lockInfo.bluetooth.signKey);k.set(g,101);const m=e.src.sm4.encrypt(k,this.lockInfo.bluetooth.privateKey,{mode:"ecb",output:"array"}),w=i.createPackageEnd(h,m),y=await s.writeBLECharacteristicValue(this.lockInfo.deviceId,this.lockInfo.serviceId,this.lockInfo.writeCharacteristicId,w);return y.code!==s.Result.Success.code?y:this.getWriteResult(this.updateAdminPassword,t)},async syncAllOpenRecord(e){const{accountInfo:t,disconnect:o}=e,{code:c,data:i,message:n}=await this.syncOpenRecord({accountInfo:t,disconnect:!1});return c===s.Result.Success.code?10===i.count?await this.syncAllOpenRecord({accountInfo:t,disconnect:o}):(o&&await this.disconnectDevice(),new s.Result(c,i,n)):new s.Result(c,i,n)},async syncOpenRecord(t){const{accountInfo:c}=t,n=await this.login(c);if(n.code!==s.Result.Success.code)return n;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 a=await this.checkLockUser();if(a.code!==s.Result.Success.code)return a;const r=this.lockInfo.uid.toString(),l=this.lockInfo.keyId.toString(),u=await o.getLastRecordTimeRequest({lockId:this.lockInfo.lockId});if(u.code!==s.Result.Success.code)return u;const d=Math.ceil(u.data.operateDate/1e3),h=Math.ceil(u.data.currentDate/1e3),k=this.createPackageHeader(3,91),I=new Uint8Array(91);I[0]=f/256,I[1]=f%256,I[2]=w,I[3]=88;for(let e=0;e<l.length;e++)I[e+4]=l.charCodeAt(e);for(let e=0;e<r.length;e++)I[e+44]=r.charCodeAt(e);I[64]=10/256,I[65]=10,I.set(i.timestampToArray(d),66),I.set(i.timestampToArray(h),70),I[74]=16;const g=i.md5Encrypt(r+l,this.lockInfo.token||new Uint8Array([0,0,0,0]),this.lockInfo.bluetooth.publicKey);I.set(g,75);const m=e.src.sm4.encrypt(I,this.lockInfo.bluetooth.privateKey,{mode:"ecb",output:"array"}),y=i.createPackageEnd(k,m),p=await s.writeBLECharacteristicValue(this.lockInfo.deviceId,this.lockInfo.serviceId,this.lockInfo.writeCharacteristicId,y);return p.code!==s.Result.Success.code?p:this.getWriteResult(this.syncOpenRecord,t)},async getServerTimestamp(){const{code:e,data:t,message:c}=await o.getServerDatetimeRequest({});return e===s.Result.Success.code&&(this.serverTimestamp=Math.ceil(t.date/1e3),this.timeDifference=Math.ceil((t.date-(new Date).getTime())/1e3)),new s.Result(e,t,c)},async cleanLockUser(){const t=await s.searchAndConnectDevice(this.lockInfo.bluetooth.bluetoothDeviceName);if(t.code!==s.Result.Success.code)return t;this.updateLockInfo(t.data);let{uid:c,keyId:n,token:a,bluetooth:r}=this.lockInfo,{uid:l}=this.userInfo;c=c.toString(),l=l.toString(),n=n.toString();const u=r.bluetoothDeviceName,{code:d,data:h}=await o.getUserNoListRequest({lockId:this.lockInfo.lockId});if(console.log("获取用户列表请求结果",d,h),0!==d)return s.Result.Fail;const f=h.userNos,I=124+f.length+4+1+16,g=this.createPackageHeader(3,I),m=new Uint8Array(I);m[0]=k/256,m[1]=k%256;for(let e=0;e<u.length;e++)m[e+2]=u.charCodeAt(e);for(let e=0;e<c.length;e++)m[e+42]=c.charCodeAt(e);for(let e=0;e<n.length;e++)m[e+62]=n.charCodeAt(e);for(let e=0;e<l.length;e++)m[e+102]=l.charCodeAt(e);m[122]=f.length/256,m[123]=f.length%256;for(let e=0;e<f.length;e++)m[e+124]=f[e];m.set(a||new Uint8Array([0,0,0,0]),124+f.length),m[128+f.length]=16;const w=i.md5Encrypt(c+n,a||new Uint8Array([0,0,0,0]),r.publicKey);m.set(w,129+f.length);const y=e.src.sm4.encrypt(m,r.privateKey,{mode:"ecb",output:"array"}),p=i.createPackageEnd(g,y),R=await s.writeBLECharacteristicValue(this.lockInfo.deviceId,this.lockInfo.serviceId,this.lockInfo.writeCharacteristicId,p);return R.code!==s.Result.Success.code?R:this.getWriteResult(this.cleanLockUser,{disconnect:!1})},async login(e){let t=c.getStorage("starCloudAccount"),i=c.getStorage("starCloudUser");if(t||(t={}),i||(i={}),this.accountInfo=t[e.uid],this.accountInfo&&this.accountInfo.token)return this.userInfo=i[e.uid],c.setStorage("starCloudToken",this.accountInfo.token),this.getServerTimestamp().then((()=>{})),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<o.length;s++)t[s+2]=o.charCodeAt(s);const c=i.createPackageEnd(e,t),n=await s.writeBLECharacteristicValue(this.lockInfo.deviceId,this.lockInfo.serviceId,this.lockInfo.writeCharacteristicId,c);return n.code!==s.Result.Success.code?n:this.getWriteResult(this.getPublicKey,{disconnect:!1})},async getCommKey(){const t=this.createPackageHeader(2,123),o=new Uint8Array(123);o[0]=r/256,o[1]=r%256;const c=this.lockInfo.bluetooth.bluetoothDeviceName,n=this.accountInfo.uid.toString();await this.getServerTimestamp();const a=this.serverTimestamp;for(let e=0;e<c.length;e++)o[e+2]=c.charCodeAt(e);for(let e=0;e<1;e++)o[e+42]="0".charCodeAt(e);for(let e=0;e<n.length;e++)o[e+82]=n.charCodeAt(e);o.set(i.timestampToArray(a),102),o[106]=16;const l=i.md5Encrypt(n+"0",o.slice(102,106),this.lockInfo.bluetooth.publicKey);o.set(l,107);const u=e.src.sm4.encrypt(o,o.slice(2,18),{mode:"ecb",output:"array"}),d=i.createPackageEnd(t,u),h=await s.writeBLECharacteristicValue(this.lockInfo.deviceId,this.lockInfo.serviceId,this.lockInfo.writeCharacteristicId,d);return h.code!==s.Result.Success.code?h:this.getWriteResult(this.getCommKey,{disconnect:!1})},async getLockStatus(){const t=this.createPackageHeader(3,70),o=new Uint8Array(70);o[0]=l/256,o[1]=l%256;const c=this.lockInfo.bluetooth.bluetoothDeviceName,n=this.accountInfo.uid.toString();await this.getServerTimestamp();const a=this.serverTimestamp,r=new Date,u=this.serverTimestamp-60*r.getTimezoneOffset();for(let e=0;e<c.length;e++)o[e+2]=c.charCodeAt(e);for(let e=0;e<n.length;e++)o[e+42]=n.charCodeAt(e);o.set(i.timestampToArray(a),62),o.set(i.timestampToArray(u),66);const d=e.src.sm4.encrypt(o,this.lockInfo.bluetooth.privateKey,{mode:"ecb",output:"array"}),h=i.createPackageEnd(t,d),k=await s.writeBLECharacteristicValue(this.lockInfo.deviceId,this.lockInfo.serviceId,this.lockInfo.writeCharacteristicId,h);return k.code!==s.Result.Success.code?k:this.getWriteResult(this.getLockStatus,{disconnect:!1})},async getNetToken(){const{code:e,data:t,message:c}=await o.getLockNetTokenRequest({lockId:this.lockInfo.lockId});return new s.Result(e,t,c)},async addLockUser(t){const{params:o}=t;if(!t.connected){const e=await s.searchAndConnectDevice(this.lockInfo.bluetooth.bluetoothDeviceName,255!==o.role);if(e.code!==s.Result.Success.code)return e;this.updateLockInfo(e.data)}const{name:c,authUid:n,uid:a,keyId:r,openMode:l,keyType:d,startDate:h,expireDate:k,useCountLimit:f,isRound:I,weekRound:g,startHour:m,startMin:w,endHour:y,endMin:p,role:R,password:S}=o,b=this.createPackageHeader(3,182),v=new Uint8Array(182);v[0]=u/256,v[1]=u%256;for(let e=0;e<c.length;e++)v[e+2]=c.charCodeAt(e);for(let e=0;e<n.length;e++)v[e+42]=n.charCodeAt(e);for(let e=0;e<r.length;e++)v[e+62]=r.charCodeAt(e);for(let e=0;e<a.length;e++)v[e+102]=a.charCodeAt(e);v[122]=l,v[123]=d,v.set(i.timestampToArray(h),124),v.set(i.timestampToArray(k),128),v[132]=f/256,v[133]=f%256,v[134]=I,v[135]=g,v[136]=m,v[137]=w,v[138]=y,v[139]=p,v[140]=R;for(let e=0;e<S.length;e++)v[e+141]=S.charCodeAt(e);v.set(this.lockInfo.token||i.timestampToArray(h),161),v[165]=16;const D=i.md5Encrypt(n+r,this.lockInfo.token||i.timestampToArray(h),this.lockInfo.bluetooth.publicKey);v.set(D,166);const A=e.src.sm4.encrypt(v,this.lockInfo.bluetooth.privateKey,{mode:"ecb",output:"array"}),L=i.createPackageEnd(b,A),C=await s.writeBLECharacteristicValue(this.lockInfo.deviceId,this.lockInfo.serviceId,this.lockInfo.writeCharacteristicId,L);return C.code!==s.Result.Success.code?C:this.getWriteResult(this.addLockUser,t)},getWriteResult(e,t){return new Promise((o=>{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;e<this.lockInfo.bluetooth.bluetoothDeviceName.length;e++)c[e]=this.lockInfo.bluetooth.bluetoothDeviceName.charCodeAt(e);const n=e.src.sm4.decrypt(o,c,{mode:"ecb",output:"array"});console.log("ecb解密后的数据",n),256*n[0]+n[1]===r&&(n[2]===s.Result.Success.code&&(this.updateLockInfo({bluetooth:{...this.lockInfo.bluetooth,privateKey:n.slice(3,19),signKey:n.slice(19,35)},pwdTimestamp:1e3*i.arrayToTimestamp(n.slice(35,39))}),console.log("privateKey",Array.from(this.lockInfo.bluetooth.privateKey)),console.log("signKey",Array.from(this.lockInfo.bluetooth.signKey))),S(new s.Result(n[2])))}else{const n=t.slice(12,t.length-2),a=e.src.sm4.decrypt(n,this.lockInfo.bluetooth.privateKey,{mode:"ecb",output:"array"});console.log("ecb解密后的数据",a);switch(256*a[0]+a[1]){case l:if(a[2]===s.Result.Success.code){const e={vendor:i.uint8ArrayToString(a.slice(3,23)),product:a[23],model:i.uint8ArrayToString(a.slice(24,44)),fwVersion:i.uint8ArrayToString(a.slice(44,64)),hwVersion:i.uint8ArrayToString(a.slice(64,84)),serialNum0:i.uint8ArrayToString(a.slice(84,100)),serialNum1:i.uint8ArrayToString(a.slice(100,116)),btDeviceName:i.uint8ArrayToString(a.slice(116,132)),electricQuantity:a[132],electricQuantityStandby:a[133],restoreCount:256*a[134]+a[135],restoreDate:i.arrayToTimestamp(a.slice(136,140)),icPartNo:i.uint8ArrayToString(a.slice(140,150)),indate:i.arrayToTimestamp(a.slice(150,154)),mac:i.uint8ArrayToString(a.slice(154,174)),timezoneOffset:60*(new Date).getTimezoneOffset()};this.updateLockInfo({featureValue:i.uint8ArrayToString(a.slice(175,175+a[174])),featureSettingValue:i.uint8ArrayToString(a.slice(176+a[174],176+a[174]+a[175+a[174]])),featureSettingParams:Array.from(a.slice(176+a[174]+a[175+a[174]])),lockConfig:e}),console.log("获取锁状态成功",this.lockInfo.lockConfig)}S(new s.Result(a[2]));break;case u:this.updateLockInfo({token:a.slice(42,46)}),a[46]===s.Result.Success.code&&this.updateLockInfo({lockUserNo:256*a[47]+a[48]}),console.log("添加用户结果",a[46],this.lockInfo.lockUserNo),S(new s.Result(a[46]));break;case f:switch(a[3]){case I:if(this.updateLockInfo({token:a.slice(5,9)}),a[2]===s.Result.Success.code){const e=await o.changeAdminKeyboardPwdRequest({password:b.adminPwd,lockId:this.lockInfo.lockId});return S(new s.Result(e.code))}S(new s.Result(a[2]));break;case m:this.updateLockInfo({token:a.slice(5,9)}),S(new s.Result(a[4]));break;case g:if(this.updateLockInfo({token:a.slice(5,9)}),a[2]===s.Result.Success.code)if(a[11]===s.Result.Success.code){const e=256*a[9]+a[10];if(0===b.operate){const t=await o.addCustomPasswordRequest({...b,pwdUserNo:e,lockId:this.lockInfo.lockId});t.code===s.Result.Success.code?S(new s.Result(t.code,{pwdNo:e,keyboardPwdId:t.data.keyboardPwdId,keyboardPwd:t.data.keyboardPwd,keyboardPwdStatus:t.data.keyboardPwdStatus,pwdUserNo:e})):S(new s.Result(t.code,t.data,t.message))}else if(1===b.operate){const e=await o.updatePasswordRequest(b);e.code===s.Result.Success.code?S(new s.Result(e.code)):S(new s.Result(e.code,e.data,e.message))}else if(3===b.operate){const e=await o.deletePasswordRequest(b);e.code===s.Result.Success.code?S(new s.Result(e.code)):S(new s.Result(e.code,e.data,e.message))}}else S(new s.Result(a[11]));else S(new s.Result(a[2]));break;case w:if(a[2]===s.Result.Success.code&&a[6]>0){const e=[],t=a[6]||0;for(let o=0;o<t;o++){let t=a.slice(14+17*o,14+17*o+10);t=t.every((e=>0===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;
|