@ray-js/wechat-mqtt 0.3.4 → 0.3.6-beta-1
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/index.d.ts +1 -4
- package/index.esm.js +1 -1
- package/index.js +1 -1
- package/lib/decrypt.d.ts +11 -0
- package/lib/encrypt.d.ts +11 -0
- package/lib/interface.d.ts +5 -178
- package/lib/mqtt.d.ts +125 -0
- package/lib/util.d.ts +2 -0
- package/package.json +8 -3
- package/lib/adapter/blowser.d.ts +0 -1
- package/lib/adapter/index.d.ts +0 -2
- package/lib/adapter/wechat.d.ts +0 -1
- package/lib/auth.d.ts +0 -2
- package/lib/connect.d.ts +0 -2
- package/lib/constant.d.ts +0 -47
- package/lib/disconnect.d.ts +0 -2
- package/lib/factory.d.ts +0 -6
- package/lib/packet.d.ts +0 -35
- package/lib/parse.d.ts +0 -24
- package/lib/ping.d.ts +0 -2
- package/lib/publish.d.ts +0 -6
- package/lib/response.d.ts +0 -2
- package/lib/subscribe.d.ts +0 -31
package/index.d.ts
CHANGED
package/index.esm.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{stringToBytes as e,uintToBytes as o,uintToBytesBy128 as t,bytesToIntBy128 as r,bytesToUint as i,bytesToString as s,BaseApi as n}from"@ray-js/wechat-helper";import{createEmitter as c}from"@ray-js/wechat-event";function a(e,o,t,r){return new(t||(t=Promise))((function(i,s){function n(e){try{a(r.next(e))}catch(e){s(e)}}function c(e){try{a(r.throw(e))}catch(e){s(e)}}function a(e){var o;e.done?i(e.value):(o=e.value,o instanceof t?o:new t((function(e){e(o)}))).then(n,c)}a((r=r.apply(e,o||[])).next())}))}var l,d;!function(e){e[e.Reserved=0]="Reserved",e[e.CONNECT=1]="CONNECT",e[e.CONNACK=2]="CONNACK",e[e.PUBLISH=3]="PUBLISH",e[e.PUBACK=4]="PUBACK",e[e.PUBREC=5]="PUBREC",e[e.PUBREL=6]="PUBREL",e[e.PUBCOMP=7]="PUBCOMP",e[e.SUBSCRIBE=8]="SUBSCRIBE",e[e.SUBACK=9]="SUBACK",e[e.UNSUBSCRIBE=10]="UNSUBSCRIBE",e[e.UNSUBACK=11]="UNSUBACK",e[e.PINGREQ=12]="PINGREQ",e[e.PINGRESP=13]="PINGRESP",e[e.DISCONNECT=14]="DISCONNECT",e[e.AUTH=15]="AUTH"}(l||(l={})),function(e){e[e.sessionExpiryInterval=17]="sessionExpiryInterval",e[e.receiveMaximum=33]="receiveMaximum",e[e.maximumQoS=36]="maximumQoS",e[e.retainAvailable=37]="retainAvailable",e[e.maximumPacketSize=39]="maximumPacketSize",e[e.topicAliasMaximum=34]="topicAliasMaximum",e[e.topicAlias=35]="topicAlias",e[e.requestResponseInformation=25]="requestResponseInformation",e[e.requestProblemInformation=23]="requestProblemInformation",e[e.userProperties=38]="userProperties",e[e.authenticationMethod=21]="authenticationMethod",e[e.authenticationData=22]="authenticationData",e[e.willDelayInterval=24]="willDelayInterval",e[e.payloadFormatIndicator=1]="payloadFormatIndicator",e[e.messageExpiryInterval=2]="messageExpiryInterval",e[e.contentType=3]="contentType",e[e.responseTopic=8]="responseTopic",e[e.correlationData=9]="correlationData",e[e.subscriptionIdentifier=11]="subscriptionIdentifier",e[e.reasonString=31]="reasonString",e[e.assignedClientIdentifier=18]="assignedClientIdentifier",e[e.wildcardSubscriptionAvailable=40]="wildcardSubscriptionAvailable",e[e.subscriptionIdentifiersAvailable=41]="subscriptionIdentifiersAvailable",e[e.sharedSubscriptionAvailable=42]="sharedSubscriptionAvailable",e[e.serverKeepAlive=19]="serverKeepAlive",e[e.responseInformation=26]="responseInformation",e[e.serverReference=28]="serverReference"}(d||(d={}));const p=(r,i=0)=>{const s=r<<4|i;let n=new Uint8Array(100),c=0,a=new Uint8Array(100),l=0,d=new Uint8Array(100),p=0;const u=(r,i,s,n=!1,c=!1)=>{let a;a="string"==typeof s?e(s):"number"==typeof s?[s]:s;let l=new Uint8Array;n&&(l=c?t(a.length):o(a.length,2));return r=((e,o)=>{if(o>=e.length){const t=new Uint8Array(o+1);return t.set(e,0),t}return e})(r,i+(a.length+l.length)),n&&r.set(l,i),i+=l.length,r.set(a,i),[r,i+=a.length]};function f(e,o=!1,t=!1){const[r,i]=u(n,c,e,o,t);n=r,c=i}function m(e,o=!0,t=!1){const[r,i]=u(a,l,e,o,t);a=r,l=i}return{header:f,payload:m,cleanCache(){d=new Uint8Array(100),p=0},cache:(e,o=!1,t=!1)=>{const[r,i]=u(d,p,e,o,t);d=r,p=i},putHeader(){f(d.slice(0,p),!0,!0)},putPayload(){m(d.slice(0,p),!0,!0)},getCache:()=>d.slice(0,p),getPacket:()=>{const e=c,o=l,r=e+o,i=t(r),d=new Uint8Array(r+i.length+1);d[0]=s;let p=1;return d.set(i,p),p+=i.length,d.set(n.slice(0,e),p),p+=e,d.set(a.slice(0,o),p),d}}},u=t=>(r,i)=>{const s=e(r),n=o(s.length,2);i(t),i(n),i(s)},f=e=>(o,t)=>{t(e),t(o?1:0)},m=e=>(t,r)=>{r(e),r(o(t))},v=e=>(t,r)=>{r(e),r(o(t,2))},g=e=>(t,r)=>{const i=o(t.length,2);r(e),r(i),r(t)},h={sessionExpiryInterval:m(d.sessionExpiryInterval),receiveMaximum:v(d.receiveMaximum),maximumPacketSize:m(d.maximumPacketSize),topicAliasMaximum:v(d.topicAliasMaximum),topicAlias:v(d.topicAlias),requestResponseInformation:f(d.requestProblemInformation),requestProblemInformation:f(d.requestProblemInformation),userProperties:(C=d.userProperties,(o,t)=>{Object.keys(o).forEach((r=>{const i=o[r],s=e(r);Array.isArray(i)?i.forEach((o=>{t(C),t(s),t(e(o))})):(t(C),t(s),t(e(i)))}))}),authenticationMethod:u(d.authenticationMethod),authenticationData:g(d.authenticationData),willDelayInterval:m(d.willDelayInterval),payloadFormatIndicator:f(d.payloadFormatIndicator),messageExpiryInterval:m(d.messageExpiryInterval),contentType:u(d.contentType),responseTopic:u(d.responseTopic),correlationData:g(d.correlationData),subscriptionIdentifier:(e=>(o,r)=>{r(e),r(t(o))})(d.subscriptionIdentifier)};var C;const M=(e,o)=>{Object.keys(e||{}).map((t=>{h[t]&&h[t](e[t],o)}))},y=(e,o)=>{const{properties:t,reasonCode:r}=o,i=p(l.AUTH);if(i.header(r),!t)throw{errCode:63005,errMsg:"Properties must be given when protocol version is 5.x"};return M(t,i.cache),i.putHeader(),e.send(i.getPacket())},P=[],b=(e,o,t)=>{t?P.splice(0,0,[e,o]):P.push([e,o])};const T=(e,o)=>[i(e.slice(o,o+=2)),o],I=(e,o)=>[i(e.slice(o,o+=4)),o],w=(e,o)=>[1===e[o++],o],E=(e,o)=>{const t=i(e.slice(o,o+=2));return[s(e.slice(o,o+=t)),o]},A=(e,o)=>{const t=i(e.slice(o,o+=2));return[e.slice(o,o+=t),o]},U={sessionExpiryInterval:I,receiveMaximum:T,maximumPacketSize:I,topicAliasMaximum:T,topicAlias:T,requestResponseInformation:w,requestProblemInformation:w,userProperties:(e,o)=>{const[t,r]=E(e,o),[i,s]=E(e,r);return[[t,i],s]},authenticationMethod:E,authenticationData:A,willDelayInterval:I,payloadFormatIndicator:w,messageExpiryInterval:I,contentType:E,responseTopic:E,correlationData:A,subscriptionIdentifier:(e,o)=>{const{num:t,end:i}=r(e,o);return[t,i]}},S=e=>{let o=e.length>0,t=0;const r={};for(;o;){const i=e[t++],s=Object.keys(d).find((e=>d[e]===i));if(!s)throw{errCode:63013,errMsg:`Unrecognized property: ${i}`};{const n=U[s](e,t);if(i===d.userProperties){const e=r[s],o=n[0];void 0!==e[o[0]]?"string"==typeof e[o[0]]?e[o[0]]=[e[o[0]]]:e[o[0]].push(o[1]):e[o[0]]=o[1]}else r[s]=n[0];t=n[1],o=t<e.length}}return r},B=(e,o)=>{const{end:t}=r(e,1),s=e.slice(t),n=i(s.slice(0,2));let c,a=0;if(5===o.protocolVersion){a=s[2];const{num:o,end:t}=r(s,3);c=S(e.slice(t,o))}return{id:n,reasonCode:a,properties:c}},q=(t,r)=>a(void 0,void 0,void 0,(function*(){const{dup:i,qos:s=0,topicName:n,id:c,properties:a,payload:d}=r;let u=0|(i?0===s?0:8:0);u|=s<<1;const f=p(l.PUBLISH,u);f.header(e(n),!0),s>0&&f.header(o(c,2)),5===t.protocolVersion&&(M(a,f.cache),f.putHeader()),f.payload(d,!1);try{yield t.send(f.getPacket())}catch(e){return void t.emitError(e)}if(0!==s)if(1===s)try{yield D(t,r)}catch(e){q(t,r)}else try{const e=yield H(t,c);t.options.onPubrel?k(t,t.options.onPubrel(e)):k(t,{id:c,reasonCode:0}),yield K(t,r)}catch(e){q(t,r)}})),x=(e,t,r,i=0)=>a(void 0,void 0,void 0,(function*(){const{id:s,properties:n,reasonCode:c}=t,a=p(r,i);a.header(o(s,2)),5===e.protocolVersion&&(a.header(c||0),M(n,a.cache),a.putHeader()),e.send(a.getPacket())})),N=(e,o)=>a(void 0,void 0,void 0,(function*(){x(e,o,l.PUBACK)})),k=(e,o)=>a(void 0,void 0,void 0,(function*(){x(e,o,l.PUBREL,2)})),O=(e,o)=>a(void 0,void 0,void 0,(function*(){x(e,o,l.PUBREC,0)})),R=(e,o)=>a(void 0,void 0,void 0,(function*(){x(e,o,l.PUBCOMP,0)})),D=(e,o)=>a(void 0,void 0,void 0,(function*(){return new Promise(((t,r)=>{const i=n=>{if(n[0]>>4===l.PUBACK){const c=B(n,e);if(c.id===o.id)if(e.offMessage(i),clearTimeout(s),0===c.reasonCode)t(c);else{const o={errCode:63010,errMsg:`MQTT publish failure, code: ${c.reasonCode}`};r(o),e.emitError(o)}}};e.onMessage(i);const s=setTimeout((()=>{e.offMessage(i),e.close();const o={errCode:63009,errMsg:"Mqtt publish timeout"};r(o),e.emitError(o)}),1e4)}))})),H=(e,o)=>a(void 0,void 0,void 0,(function*(){return new Promise(((t,r)=>{const i=n=>{if(n[0]>>4===l.PUBREC){const c=B(n,e);if(c.id===o)if(e.offMessage(i),clearTimeout(s),0===c.reasonCode)t(c);else{const o={errCode:63010,errMsg:`MQTT publish failure, code: ${c.reasonCode}`};r(o),e.emitError(o)}}};e.onMessage(i);const s=setTimeout((()=>{e.offMessage(i),e.close();const o={errCode:63009,errMsg:"Mqtt publish timeout"};r(o),e.emitError(o)}),1e4)}))})),K=(e,o)=>a(void 0,void 0,void 0,(function*(){return new Promise(((t,r)=>{const i=n=>{if(n[0]>>4===l.PUBCOMP){const c=B(n,e);if(c.id===o.id)if(e.offMessage(i),clearTimeout(s),0===c.reasonCode)t(c);else{const o={errCode:63010,errMsg:`MQTT publish failure, code: ${c.reasonCode}`};r(o),e.emitError(o)}}};e.onMessage(i);const s=setTimeout((()=>{e.offMessage(i),e.close();const o={errCode:63009,errMsg:"Mqtt publish timeout"};r(o),e.emitError(o)}),1e4)}))}));b((()=>!(!window||!window.WebSocket)),((e,o)=>a(void 0,void 0,void 0,(function*(){const t=new WebSocket(e,4===o?["mqttv3.1"]:["mqtt"]);return{onOpen:e=>{t.addEventListener("open",e)},send:e=>{t.send(e)},close:()=>0===t.bufferedAmount?t.close():new Promise(((e,o)=>{let r=0;const i=setInterval((()=>{r++,200===r&&o(),0===t.bufferedAmount&&(clearInterval(i),t.close(),e(!0))}),16)})),onClose:e=>{t.addEventListener("close",e)},onMessage:e=>{t.addEventListener("message",e)},onError:e=>{t.addEventListener("error",e)}}}))));b((()=>!("undefined"==typeof wx||!n.hasBaseApi("connectSocket"))),((e,o)=>a(void 0,void 0,void 0,(function*(){const t=yield((e,o)=>a(void 0,void 0,void 0,(function*(){return new Promise(((t,r)=>{const i=n.connectSocket({url:e,protocols:4===o?["mqttv3.1"]:["mqtt"],fail:r});i&&t(i)}))})))(e,o);return{onOpen:e=>{t.onOpen(e)},send:e=>new Promise(((o,r)=>{t.send({data:e,fail:r,success:o})})),close:()=>{t.close()},onClose:e=>{t.onClose(e)},onMessage:e=>{t.onMessage(e)},onError:e=>{t.onError(e)}}}))));const V=(e,o)=>{const t=(e=>{let o=0;const t=e[o++],{num:i,end:s}=r(e,1);return{reasonCode:t,properties:S(e.slice(s,s+i))}})(e);if(24===t.reasonCode){if(void 0===o.options.onAuth)throw{errCode:63018,errMsg:"The option onAuth not set"};y(o,o.options.onAuth(t))}},L=(e,o)=>{const t=((e,o)=>{const t=e[0],s=(6&t)>>1,n=(8&t)>>3==1;let c=1;const{num:a,end:l}=r(e,c),d=l+a;c=l;const p=E(e,c),[u]=p;let f,m;if(c=p[1],s>0&&(f=i(e.slice(c,c+=2))),5===o.protocolVersion){const{num:o,end:t}=r(e,c);m=S(e.slice(t,o)),c=o+t}return{qos:s,dup:n,topicName:u,id:f,payload:e.slice(c,d),properties:m}})(e,o);let{topicName:s}=t;if(o.protocolVersion>=5&&t.properties){const{topicAlias:e}=t.properties;if(e)if(s)o.applyTopic(e,s);else if(s=o.getTopic(e),!s)return void o.emitError({errCode:63019,errMsg:"Received unregistered Topic Alias"})}if(o.checkTopic(s))switch(t.qos){case 0:o.emitMqttMessage({topic:s,payload:t.payload});break;case 1:o.options.onPuback?N(o,o.options.onPuback(t)):N(o,{id:t.id,reasonCode:0});break;case 2:o.options.onPubrec?O(o,o.options.onPubrec(t)):O(o,{id:t.id,reasonCode:0})}else o.emitError({errCode:63020,errMsg:"Received unsubscribe Topic"})},j=(e,o)=>{const t=B(e,o);o.options.onPubcomp?R(o,o.options.onPubcomp(t)):R(o,{id:t.id,reasonCode:0})},Q=e=>{const o=1e3*(e.options.keepalive||60),t=()=>a(void 0,void 0,void 0,(function*(){try{!e.isClose()&&(yield(e=>(e.send(new Uint8Array([l.PINGREQ<<4,0])),new Promise(((o,t)=>{const r=t=>{t[0]>>4===l.PINGRESP&&(e.offMessage(r),clearTimeout(i),o(!0))};e.onMessage(r);const i=setTimeout((()=>{e.offMessage(r),e.close(),t({errCode:63016,errMsg:"Mqtt ping timeout"})}),1e4)}))))(e)),setTimeout(t,o)}catch(o){console.warn("ping error",o),e.emitError(o),e.close(o)}}));setTimeout(t,o)},z=t=>a(void 0,void 0,void 0,(function*(){const s=yield(e=>a(void 0,void 0,void 0,(function*(){const{protocolVersion:o=4}=e,t=P.find((e=>e[0]()));if(t){let r=0;const i=c();let s=null,n=0;const l={},d=[];return{options:e,protocolVersion:o,sessionPresent:0,connect:(c=!1)=>a(void 0,void 0,void 0,(function*(){if(c&&s)try{s.close()}catch(e){}const a=++n;return r=0,s=yield t[1](e.url,o),new Promise(((e,o)=>{const t=setTimeout((()=>{r=2,o(new Error("ws connect time out"))}),1e4);s&&s.onError((e=>{if(0===r)clearTimeout(t),o(e);else if(a===n){const o=r;r=2,i.emit("error",e),2==o&&i.emit("close",e)}})),s&&s.onOpen((()=>{clearTimeout(t),r=1,s&&s.onClose((e=>{if(a===n){const o=r;r=2,2==o&&i.emit("close",e)}})),s&&s.onMessage((e=>{a===n&&i.emit("message",new Uint8Array(e.data))})),e(!0)}))}))})),isClose:()=>2===r,isOnline:()=>1===r,getStatus:()=>r,send:e=>{if(s&&1===r)return s.send(e.buffer);throw{errCode:63017,errMsg:"Websocket is closed"}},onClose:e=>{i.on("close",e)},offClose:e=>{i.off("close",e)},onError:e=>{i.on("error",e)},offError:e=>{i.off("error",e)},onMessage:e=>{i.on("message",e)},offMessage:e=>{i.off("message",e)},close:e=>{const o=r;r=2,2!==o&&i.emit("close",e),s&&s.close()},emitError:e=>{i.emit("error",e)},emitMqttMessage:e=>{i.emit("mqttMessage",e)},onMqttMessage:e=>{i.on("mqttMessage",e)},offMqttMessage:e=>{i.off("mqttMessage",e)},applyTopic:(e,o)=>{l[e]=o},getTopic:e=>l[e],addTopic:e=>{-1===d.indexOf(e)&&d.push(e)},removeTopic:e=>{const o=d.indexOf(e);o>=0&&d.splice(o,1)},clearTopic:()=>{d.length=0},checkTopic:e=>d.some((o=>function(e,o){const t=e.split("/"),r=e.split("/");if(e===o)return!0;for(let e=0;e<r.length;e++){const o=t[e];switch(o){case"#":return!0;case"+":continue;default:if(o!==r[e])return!1}}return!1}(o,e)))}}throw{errCode:63e3,errMsg:"The current environment does not support MQTT"}})))(t);yield s.connect(),s.onMessage((e=>{((e,o)=>{const t=e[0]>>4,{end:i,num:s}=r(e,1);switch(t){case l.AUTH:return V(e.slice(i,i+s),o);case l.PUBLISH:return L(e,o);case l.PUBCOMP:return j(e,o);case l.DISCONNECT:o.close()}})(e,s)})),yield((e,t)=>a(void 0,void 0,void 0,(function*(){const{protocolVersion:i=4,connectTimeout:s=10,username:n,password:c,will:a,keepalive:d=60,clean:u,clientId:f}=t,m=p(l.CONNECT);m.header([0,4,77,81,84,84]),m.header(i);let v=0;if(v|=n?128:0,v|=c?64:0,v|=a&&a.retain?32:0,v|=a&&a.qos?a.qos<<3:0,v|=a?4:0,v|=u?2:0,m.header(v),m.header(o(d,2)),5===i&&(M(t.properties,m.cache),m.putHeader()),i<4)throw{errCode:63001,errMsg:"ClientId must be supplied before 3.1.1"};if(!1===u)throw{errCode:63002,errMsg:"ClientId must be given if clean set to 0"};if(m.payload(f),a){if(5===i){if(!a.properties)throw{errCode:63006,errMsg:"Will properties must be given if will has seted, when protocol version is 5.x "};m.cleanCache(),M(a.properties,m.cache),m.putPayload()}if(!a.topic)throw{errCode:63003,errMsg:"Will topic must be given if will has seted"};if(m.payload(a.topic),!a.payload)throw{errCode:63004,errMsg:"Will payload must be given if will has seted"};m.payload(a.payload)}return n&&m.payload(n),c&&m.payload(c),e.send(m.getPacket()),new Promise(((o,t)=>{const i=s=>{if(s[0]>>4===l.CONNACK){e.offMessage(i),clearTimeout(n);const{end:c}=r(s,1),a=s.slice(c),l=1&a[0];e.sessionPresent=l;const d=a[1];return 0===d?void o(!0):void t({errCode:63008,errMsg:`MQTT connect failure, code: ${d}`})}};e.onMessage(i);const n=setTimeout((()=>{e.offMessage(i),e.close(),t({errCode:63007,errMsg:"Mqtt Connect timeout"})}),1e3*s)}))})))(s,t),Q(s);let n=0;const d=()=>(++n,16777215===n&&(n=1),n);return{getStatus:s.getStatus,onMessage:s.onMqttMessage,offMessage:s.offMqttMessage,subscribe:(e,t)=>a(void 0,void 0,void 0,(function*(){if((e=e.filter((e=>!s.checkTopic(e.topic)))).length){const n=yield((e,t)=>a(void 0,void 0,void 0,(function*(){const{id:s,properties:n,payload:c}=t,a=p(l.SUBSCRIBE,2);if(a.header(o(s,2)),5===e.protocolVersion){if(!n)throw{errCode:63005,errMsg:"Properties must be given when protocol version is 5.x"};M(n,a.cache),a.putHeader()}return c.forEach((o=>{a.payload(o.topic);let t=o.qos||0;if(5===e.protocolVersion){const{nl:e=0,rap:r=0,rh:i=0}=o;t|=e<<2,t|=r<<3,t|=i<<4}a.payload(t,!1)})),e.send(a.getPacket()),new Promise(((o,t)=>{const n=t=>{if(t[0]>>4===l.SUBACK){const a=r(t,1),l=a.end+a.num,d=t.slice(a.end,l);if(i(d.slice(0,2))===s){let t,i=2;if(5===e.protocolVersion){const{end:e,num:o}=r(d,i);i=e+o,t=S(d.slice(e,i))}const s=d.slice(i);e.offMessage(n),clearTimeout(c),o({reasonCode:s,properties:t})}}};e.onMessage(n);const c=setTimeout((()=>{e.offMessage(n),e.close(),t({errCode:63011,errMsg:"Mqtt subscribe timeout"})}),1e4)}))})))(s,{id:d(),properties:null==t?void 0:t.properties,payload:e}),c=e.reduce(((o,t,r)=>(n.reasonCode[r]>=128?o[t.topic]=n.reasonCode[r]:e.map((e=>s.addTopic(e.topic))),o)),{});return{properties:n.properties,err:Object.keys(c).length?c:void 0}}return{}})),unsubscribe:(e,t)=>a(void 0,void 0,void 0,(function*(){if((e=e.filter((e=>s.checkTopic(e)))).length){const n=yield((e,t)=>{const{id:s,properties:n,topics:c}=t,a=p(l.UNSUBSCRIBE,2);return a.header(o(s,2)),5===e.protocolVersion&&(M(n,a.cache),a.putHeader()),c.forEach((e=>{a.payload(e)})),e.send(a.getPacket()),new Promise(((o,t)=>{const n=t=>{if(t[0]>>4===l.UNSUBACK){const l=r(t,1),d=l.end+l.num,p=t.slice(l.end,d);if(i(p.slice(0,2))===s){let t,i=2;if(5===e.protocolVersion){const{end:e,num:o}=r(p,i);i=e+o,t=S(p.slice(e,i))}const s=p.slice(i);e.offMessage(n),clearTimeout(a),s.length?o({reasonCode:s,properties:t}):o({reasonCode:new Uint8Array(c.map((()=>0))),properties:t})}}};e.onMessage(n);const a=setTimeout((()=>{e.offMessage(n),e.close(),t({errCode:63014,errMsg:"Mqtt unsubscribe timeout"})}),1e4)}))})(s,{id:d(),properties:null==t?void 0:t.properties,topics:e}),c=e.reduce(((o,t,r)=>(n.reasonCode[r]>=128?o[t]=n.reasonCode[r]:e.map((e=>s.removeTopic(e))),o)),{});return{err:Object.keys(c).length?c:void 0}}return{}})),publish:(o,t,r)=>{const i=d();return q(s,Object.assign({id:i,topicName:o,payload:"string"==typeof t?e(t):t},r))},reAuth:e=>{y(s,Object.assign(Object.assign({},e),{reasonCode:25}))},disconnect:e=>{((e,o)=>{a(void 0,void 0,void 0,(function*(){const{reasonCode:t=0,properties:r}=o,i=p(l.DISCONNECT);5===e.protocolVersion&&(i.header(t),M(r,i.cache),i.putHeader()),yield e.send(i.getPacket()),e.close()}))})(s,e||{reasonCode:0})},onClose:s.onClose,onError:s.onError}}));export{z as createMQTT};
|
|
1
|
+
import{createMQTT as e}from"@ray-js/wechat-mqtt-core";import{createEmitter as t}from"@ray-js/wechat-event";import{hex as n}from"js-md5";import{AES_ECB as o,AES_GCM as c}from"@ray-js/wechat-tycrypto";import{bytesToString as i,hexToBytes as r,stringToBytes as s,bytesToInt as a,CRC32 as l,bytesToHex as d,randomBytes as p,getGlobal as u,BaseApi as g,sleep as f}from"@ray-js/wechat-helper";import{Base64 as v}from"js-base64";import{useChanel as h}from"@ray-js/wechat-debug";function y(e,t,n,o){return new(n||(n=Promise))((function(c,i){function r(e){try{a(o.next(e))}catch(e){i(e)}}function s(e){try{a(o.throw(e))}catch(e){i(e)}}function a(e){var t;e.done?c(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(r,s)}a((o=o.apply(e,t||[])).next())}))}const m=(e,t)=>{const o=Object.keys(e).sort(((e,t)=>e<t?-1:1)).reduce(((t,n)=>e[n]||0===e[n]?t.concat(`${n}=${e[n]}`):t),[]);o.push(t);const c=o.join("||");return n(c)},T=(e,t)=>{const{sign:n}=e,o=function(e,t){var n={};for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&t.indexOf(o)<0&&(n[o]=e[o]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var c=0;for(o=Object.getOwnPropertySymbols(e);c<o.length;c++)t.indexOf(o[c])<0&&Object.prototype.propertyIsEnumerable.call(e,o[c])&&(n[o[c]]=e[o[c]])}return n}(e,["sign"]);return m(o,t)===n},C={"2.0":(e,t)=>{const{localKey:n}=t,c=JSON.parse(i(e));if(16===c.protocol)return c;if(T(c,n)){const e=r(c.data),t=i(o.decrypt(e,s(n),!0)),a=JSON.parse(t);return Object.assign(Object.assign({},c),{data:a})}throw Error("check sign invalid")},2.1:(e,t)=>{const{localKey:n}=t,c=i(e.slice(0,3)),r=i(e.slice(3,19)),a=v.toUint8Array(i(e.slice(19)));if(r===m({data:a,pv:c},n).slice(8,24)){const e=i(o.decrypt(a,s(n),!0)),t=JSON.parse(e);return Object.assign({pv:c},t)}throw Error("check sign invalid")},2.2:(e,t)=>{const{localKey:n}=t,c=i(e.slice(0,3)),r=a(e.slice(3,7)),d=a(e.slice(7,11)),p=a(e.slice(11,15)),u=e.slice(15);if(l(e.slice(7))===r){const e=i(o.decrypt(u,s(n),!0)),t=JSON.parse(e);return Object.assign({pv:c,sn:d,source:p},t)}throw Error("check crc32 invalid")},2.3:(e,t)=>{const{localKey:n}=t,o=i(e.slice(0,3)),r=a(e.slice(3,7)),l=a(e.slice(7,11)),d=e.slice(12,24),p=e.slice(24),u=e.slice(0,12),g=i(c.decrypt(p,s(n),d,u)),f=JSON.parse(g);return Object.assign({pv:o,sn:r,source:l},f)}},w=e=>(e||(e=+new Date),e.toString().length>10?Math.floor(e/1e3):e),O={"2.0":(e,t)=>{const{localKey:n}=t,c=o.encrypt(s(JSON.stringify(e.data)),s(n),!0),i={protocol:e.protocol,pv:"2.0",t:w(e.time),data:d(c),gwId:e.devId};return i.sign=m(i,n),s(JSON.stringify(i))},2.1:(e,t)=>{const{localKey:n}=t,c={protocol:e.protocol,t:w(e.time),data:e.data},i=v.fromUint8Array(o.encrypt(s(JSON.stringify(c)),s(n),!0)),r=m({data:i,pv:"2.1"},n).slice(8,24);return s(`2.1${r}${i}`)},2.2:(e,t)=>{var n,c;const{localKey:i}=t,r=null!==(n=e.sn)&&void 0!==n?n:0,a=null!==(c=e.source)&&void 0!==c?c:0,d={protocol:e.protocol,t:w(e.time),data:e.data},p=o.encrypt(s(JSON.stringify(d)),s(i),!0),u=new Uint8Array(15+p.length),g=new DataView(u.buffer);u.set(s("2.2"),0),g.setInt32(7,r),g.setInt32(11,a),u.set(p,15);const f=l(u.slice(7));return g.setInt32(3,f),u},2.3:(e,t)=>{var n,o;const{localKey:i}=t,r=null!==(n=e.sn)&&void 0!==n?n:0,a=null!==(o=e.source)&&void 0!==o?o:0,l={protocol:e.protocol,t:w(e.time),data:e.data,gwId:t.devId},d=p(12),u=new Uint8Array(12),g=new DataView(u.buffer);u.set(s("2.3"),0),g.setInt32(3,r),g.setInt32(7,a),u[11]=0;const f=c.encrypt(s(JSON.stringify(l)),s(i),d,u),v=new Uint8Array(24+f.length);return v.set(u,0),v.set(d,12),v.set(f,24),v}},b=t({globalKey:"__mqttEvent"}),I=h("MQTT",{needCollection:!1});I.start();var N;!function(e){e[e.CONNECT_BREAK=0]="CONNECT_BREAK",e[e.CONNECTED=1]="CONNECTED",e[e.CONNECTING=2]="CONNECTING"}(N||(N={}));const S=u();S.mqttData||(S.mqttData={client:null,reconnectCount:0,reconnectEnabled:!0,isConnecting:!1,needManualReconnect:!1,currentOptions:{},topicData:{homeIds:new Set,deviceIds:new Set,devices:new Map},mqttType:"standard"});const E=S.mqttData;let D=()=>{};const j=(e,t)=>{if("standard"===E.mqttType)if(E.topicData.devices.has(e)){const n=E.topicData.devices.get(e);try{const o=((e,t)=>{let n="2.0";if("{"!==i(e.slice(0,1))&&(n=i(e.slice(0,3)),/\d\.\d/.test(n)||(n="2.0")),C[n])return C[n](e,t);throw new Error(`Not suppport pv ${n}`)})(t,n);o.t&&10===o.t.toString().length&&(o.t*=1e3),b.emit("message",{topic:e,payload:Object.assign({gwId:n.devId},o),mqttType:E.mqttType})}catch(e){I.log("decrypt error: ",e)}}else E.topicData.homeIds.has(e)&&b.emit("message",{topic:e,payload:JSON.parse(i(t)),mqttType:E.mqttType});else b.emit("message",{topic:e,payload:JSON.parse(i(t)),mqttType:E.mqttType})},M=()=>y(void 0,void 0,void 0,(function*(){if(I.log("Reconnect"),E.isConnecting)I.log("Has one Connecting");else if(E.needManualReconnect)I.log("Requires manual reconnection");else if(E.reconnectEnabled){E.reconnectCount++;const e=()=>y(void 0,void 0,void 0,(function*(){try{const e={homeIds:[],devices:[]};E.topicData.homeIds.forEach((t=>{e.homeIds.push(t)})),E.topicData.devices.forEach((t=>{e.devices.push(t)})),yield K({needReopen:!0,loadMQTTConfig:D}),E.topicData={homeIds:new Set,devices:new Map},J(e)}catch(e){if(6e4===e.code||6e4===e.errCode||63021===e.errCode)return;M()}}));E.reconnectCount<=3?e():($(),setTimeout((()=>{E.client||e()}),2e3*(E.reconnectCount-3)))}}));let q=0;const K=t=>y(void 0,void 0,void 0,(function*(){var n,o;if(E.isConnecting){I.log("Has one Connecting"),yield f(3e3,(()=>!!E.client&&E.client.getStatus()>0));const e=null===(n=E.client)||void 0===n?void 0:n.getStatus();if(1==e)return;if(2===e)throw{code:63008,errMsg:"MQTT connect failure"};if(E.isConnecting)return K(t)}if(E.needManualReconnect=!1,t.needReopen)E.client&&(I.log("Need destroy old one"),$());else if(E.client){if(1===E.client.getStatus())return void I.log("Already connected")}I.log("Start connecting"),E.isConnecting=!0,b.emit("stateChange",N.CONNECTING);const c=++q;try{const n=null!==(o=t.mqttType)&&void 0!==o?o:"standard";if(I.log("Get config"),!t.loadMQTTConfig)throw{errCode:63021,errMsg:"loadMQTTConfig callback function not set"};D=t.loadMQTTConfig;const i=yield D();I.log("Get config clientId:",i.clientId),E.currentOptions=i,I.log("Connecting MQTT"),E.client=yield e(Object.assign({},i)),I.log("Connected"),E.mqttType=n,E.client.onMessage((({topic:e,payload:t})=>{c===q&&j(e,t)})),E.client.onClose((e=>{c===q&&(I.log("Connect closed",e),b.emit("stateChange",N.CONNECT_BREAK),E.client&&M())})),b.emit("stateChange",N.CONNECTED),E.isConnecting=!1,E.reconnectCount=0}catch(e){throw I.error("Connect Failure",e),E.isConnecting=!1,e}})),J=e=>y(void 0,void 0,void 0,(function*(){var t,n;if(I.log("Will subscribe data",e),E.client){const{topicData:{homeIds:o,devices:c},currentOptions:{homeTopicTpl:i,deviceSubscribeTopicTpl:r}}=E,s=[];if(null===(t=e.homeIds)||void 0===t||t.forEach((e=>{const t=i.replace("{ownerId}",e.toString());o.has(t)||s.push({homeId:e,topic:t})})),null===(n=e.devices)||void 0===n||n.forEach((e=>{const t=r.replace("{devId}",e.devId);c.has(t)||s.push(Object.assign(Object.assign({},e),{topic:t}))})),I.log("Will subscribe topics",s),s.length)for(let e=0;e<s.length;e+=10){const t=s.slice(e,e+10),n=yield E.client.subscribe(t);n.err?I.warn("subscribe topic error",n):t.forEach((e=>{e.homeId?o.add(e.topic):e.devId&&c.set(e.topic,e)}))}}})),A=()=>y(void 0,void 0,void 0,(function*(){if(I.log("Clear topics"),E.client){const{topicData:{homeIds:e,devices:t},currentOptions:{homeTopicTpl:n,deviceSubscribeTopicTpl:o}}=E,c=[];t.forEach((e=>{c.push(o.replace("{devId}",e.devId))})),e.forEach((e=>{c.push(n.replace("{ownerId}",e.toString()))}));for(let e=0;e<c.length;e+=10)yield E.client.unsubscribe(c.slice(e,e+10))}E.topicData={homeIds:new Set,devices:new Map}})),R=e=>y(void 0,void 0,void 0,(function*(){var t,n;if(I.log("unsubscribe topics:",e),E.client){const{topicData:{homeIds:o,devices:c},currentOptions:{homeTopicTpl:i,deviceSubscribeTopicTpl:r}}=E,s=[];null===(t=e.homeIds)||void 0===t||t.forEach((e=>{const t=i.replace("{ownerId}",e.toString());o.has(t)&&(s.push(t),o.delete(t))})),null===(n=e.deviceIds)||void 0===n||n.forEach((e=>{const t=r.replace("{devId}",e);c.get(t)&&(s.push(t),c.delete(t))}));for(let e=0;e<s.length;e+=10)yield E.client.unsubscribe(s.slice(e,e+10))}})),Q=e=>{if(E.client&&G()){const{topicData:{devices:t},currentOptions:{deviceSubscribeTopicTpl:n}}=E,o=n.replace("{devId}",e);return t.has(o)}return!1},$=()=>{var e,t;1===(null===(e=E.client)||void 0===e?void 0:e.getStatus())&&(b.emit("stateChange",N.CONNECT_BREAK),null===(t=E.client)||void 0===t||t.disconnect()),E.client=null},_=e=>{b.on("message",e)},k=e=>{b.off("message",e)},U=e=>{b.on("stateChange",e)},x=e=>{b.off("stateChange",e)},G=()=>!!E.client&&1===E.client.getStatus(),B=e=>{const t=E.currentOptions.password.substring(8,24),c=s(t),{protocol:i,data:r,deviceId:a}=e;if(a){const e=o.encrypt(s(JSON.stringify(r)),c,!0),l={protocol:i,pv:"2.0",t:+new Date,data:v.fromUint8Array(e),client_id:E.currentOptions.clientId,sign:""};return l.sign=((e,t)=>{const o=Object.keys(e).sort(((e,t)=>e<t?-1:1)).reduce(((t,n)=>e[n]||0===e[n]?t.concat(`${n}=${e[n]}`):t),[]);o.push(t);const c=o.join("||");return n(c)})(l,t),E.client&&E.client.publish(E.currentOptions.deviceSendTopicTpl.replace("{devId}",a||""),JSON.stringify(l))}throw new Error("Not support this protocol")},P=e=>{const{protocol:t,data:n,deviceId:o,localKey:c,pv:i="2.0"}=e;if(o&&c){const e=((e,t,n)=>{if(O[n])return O[n](e,t);throw new Error(`Not suppport pv ${n}`)})({protocol:t,data:n,devId:o},{devId:o,localKey:c,pv:i},i);return E.client&&E.client.publish(E.currentOptions.deviceSendTopicTpl.replace("{devId}",o),e)}throw new Error("Not support this protocol")},H=e=>{if(I.log("Send message:",e),E.client)return"open"===E.mqttType?B(e):P(e);throw{errCode:60002,errMsg:"MQTT not connected"}};let V=!1,W=+new Date;g.onAppShow((()=>{if(!V)return;E.reconnectEnabled=!0,E.reconnectCount=0,V=!1;if(+new Date-W>3e3)M();else if(E.client)if(1===E.client.getStatus()){const e=()=>{k(e),clearTimeout(t)},t=setTimeout((()=>{k(e),M()}),6e4);_(e)}else M()})),g.onAppHide((()=>{V=!0,E.reconnectEnabled=!1,W=+new Date}));const F=()=>{I.log("Manual disconnect"),E.needManualReconnect=!0,$()};export{Q as checkSubscribeDevice,A as clearTopics,K as connect,F as destroy,G as getState,k as offMessage,x as offStateChange,_ as onMessage,U as onStateChange,H as publish,J as subscribeTopics,R as unsubscribeTopics};
|
package/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e,o,t=require("@ray-js/wechat-helper"),r=require("@ray-js/wechat-event");function s(e,o,t,r){return new(t||(t=Promise))((function(s,i){function n(e){try{a(r.next(e))}catch(e){i(e)}}function c(e){try{a(r.throw(e))}catch(e){i(e)}}function a(e){var o;e.done?s(e.value):(o=e.value,o instanceof t?o:new t((function(e){e(o)}))).then(n,c)}a((r=r.apply(e,o||[])).next())}))}!function(e){e[e.Reserved=0]="Reserved",e[e.CONNECT=1]="CONNECT",e[e.CONNACK=2]="CONNACK",e[e.PUBLISH=3]="PUBLISH",e[e.PUBACK=4]="PUBACK",e[e.PUBREC=5]="PUBREC",e[e.PUBREL=6]="PUBREL",e[e.PUBCOMP=7]="PUBCOMP",e[e.SUBSCRIBE=8]="SUBSCRIBE",e[e.SUBACK=9]="SUBACK",e[e.UNSUBSCRIBE=10]="UNSUBSCRIBE",e[e.UNSUBACK=11]="UNSUBACK",e[e.PINGREQ=12]="PINGREQ",e[e.PINGRESP=13]="PINGRESP",e[e.DISCONNECT=14]="DISCONNECT",e[e.AUTH=15]="AUTH"}(e||(e={})),function(e){e[e.sessionExpiryInterval=17]="sessionExpiryInterval",e[e.receiveMaximum=33]="receiveMaximum",e[e.maximumQoS=36]="maximumQoS",e[e.retainAvailable=37]="retainAvailable",e[e.maximumPacketSize=39]="maximumPacketSize",e[e.topicAliasMaximum=34]="topicAliasMaximum",e[e.topicAlias=35]="topicAlias",e[e.requestResponseInformation=25]="requestResponseInformation",e[e.requestProblemInformation=23]="requestProblemInformation",e[e.userProperties=38]="userProperties",e[e.authenticationMethod=21]="authenticationMethod",e[e.authenticationData=22]="authenticationData",e[e.willDelayInterval=24]="willDelayInterval",e[e.payloadFormatIndicator=1]="payloadFormatIndicator",e[e.messageExpiryInterval=2]="messageExpiryInterval",e[e.contentType=3]="contentType",e[e.responseTopic=8]="responseTopic",e[e.correlationData=9]="correlationData",e[e.subscriptionIdentifier=11]="subscriptionIdentifier",e[e.reasonString=31]="reasonString",e[e.assignedClientIdentifier=18]="assignedClientIdentifier",e[e.wildcardSubscriptionAvailable=40]="wildcardSubscriptionAvailable",e[e.subscriptionIdentifiersAvailable=41]="subscriptionIdentifiersAvailable",e[e.sharedSubscriptionAvailable=42]="sharedSubscriptionAvailable",e[e.serverKeepAlive=19]="serverKeepAlive",e[e.responseInformation=26]="responseInformation",e[e.serverReference=28]="serverReference"}(o||(o={}));const i=(e,o=0)=>{const r=e<<4|o;let s=new Uint8Array(100),i=0,n=new Uint8Array(100),c=0,a=new Uint8Array(100),l=0;const d=(e,o,r,s=!1,i=!1)=>{let n;n="string"==typeof r?t.stringToBytes(r):"number"==typeof r?[r]:r;let c=new Uint8Array;s&&(c=i?t.uintToBytesBy128(n.length):t.uintToBytes(n.length,2));return e=((e,o)=>{if(o>=e.length){const t=new Uint8Array(o+1);return t.set(e,0),t}return e})(e,o+(n.length+c.length)),s&&e.set(c,o),o+=c.length,e.set(n,o),[e,o+=n.length]};function u(e,o=!1,t=!1){const[r,n]=d(s,i,e,o,t);s=r,i=n}function p(e,o=!0,t=!1){const[r,s]=d(n,c,e,o,t);n=r,c=s}return{header:u,payload:p,cleanCache(){a=new Uint8Array(100),l=0},cache:(e,o=!1,t=!1)=>{const[r,s]=d(a,l,e,o,t);a=r,l=s},putHeader(){u(a.slice(0,l),!0,!0)},putPayload(){p(a.slice(0,l),!0,!0)},getCache:()=>a.slice(0,l),getPacket:()=>{const e=i,o=c,a=e+o,l=t.uintToBytesBy128(a),d=new Uint8Array(a+l.length+1);d[0]=r;let u=1;return d.set(l,u),u+=l.length,d.set(s.slice(0,e),u),u+=e,d.set(n.slice(0,o),u),d}}},n=e=>(o,r)=>{const s=t.stringToBytes(o),i=t.uintToBytes(s.length,2);r(e),r(i),r(s)},c=e=>(o,t)=>{t(e),t(o?1:0)},a=e=>(o,r)=>{r(e),r(t.uintToBytes(o))},l=e=>(o,r)=>{r(e),r(t.uintToBytes(o,2))},d=e=>(o,r)=>{const s=t.uintToBytes(o.length,2);r(e),r(s),r(o)},u={sessionExpiryInterval:a(o.sessionExpiryInterval),receiveMaximum:l(o.receiveMaximum),maximumPacketSize:a(o.maximumPacketSize),topicAliasMaximum:l(o.topicAliasMaximum),topicAlias:l(o.topicAlias),requestResponseInformation:c(o.requestProblemInformation),requestProblemInformation:c(o.requestProblemInformation),userProperties:(p=o.userProperties,(e,o)=>{Object.keys(e).forEach((r=>{const s=e[r],i=t.stringToBytes(r);Array.isArray(s)?s.forEach((e=>{o(p),o(i),o(t.stringToBytes(e))})):(o(p),o(i),o(t.stringToBytes(s)))}))}),authenticationMethod:n(o.authenticationMethod),authenticationData:d(o.authenticationData),willDelayInterval:a(o.willDelayInterval),payloadFormatIndicator:c(o.payloadFormatIndicator),messageExpiryInterval:a(o.messageExpiryInterval),contentType:n(o.contentType),responseTopic:n(o.responseTopic),correlationData:d(o.correlationData),subscriptionIdentifier:(e=>(o,r)=>{r(e),r(t.uintToBytesBy128(o))})(o.subscriptionIdentifier)};var p;const f=(e,o)=>{Object.keys(e||{}).map((t=>{u[t]&&u[t](e[t],o)}))},m=(o,t)=>{const{properties:r,reasonCode:s}=t,n=i(e.AUTH);if(n.header(s),!r)throw{errCode:63005,errMsg:"Properties must be given when protocol version is 5.x"};return f(r,n.cache),n.putHeader(),o.send(n.getPacket())},y=[],v=(e,o,t)=>{t?y.splice(0,0,[e,o]):y.push([e,o])};const g=(e,o)=>[t.bytesToUint(e.slice(o,o+=2)),o],h=(e,o)=>[t.bytesToUint(e.slice(o,o+=4)),o],C=(e,o)=>[1===e[o++],o],T=(e,o)=>{const r=t.bytesToUint(e.slice(o,o+=2));return[t.bytesToString(e.slice(o,o+=r)),o]},M=(e,o)=>{const r=t.bytesToUint(e.slice(o,o+=2));return[e.slice(o,o+=r),o]},b={sessionExpiryInterval:h,receiveMaximum:g,maximumPacketSize:h,topicAliasMaximum:g,topicAlias:g,requestResponseInformation:C,requestProblemInformation:C,userProperties:(e,o)=>{const[t,r]=T(e,o),[s,i]=T(e,r);return[[t,s],i]},authenticationMethod:T,authenticationData:M,willDelayInterval:h,payloadFormatIndicator:C,messageExpiryInterval:h,contentType:T,responseTopic:T,correlationData:M,subscriptionIdentifier:(e,o)=>{const{num:r,end:s}=t.bytesToIntBy128(e,o);return[r,s]}},P=e=>{let t=e.length>0,r=0;const s={};for(;t;){const i=e[r++],n=Object.keys(o).find((e=>o[e]===i));if(!n)throw{errCode:63013,errMsg:`Unrecognized property: ${i}`};{const c=b[n](e,r);if(i===o.userProperties){const e=s[n],o=c[0];void 0!==e[o[0]]?"string"==typeof e[o[0]]?e[o[0]]=[e[o[0]]]:e[o[0]].push(o[1]):e[o[0]]=o[1]}else s[n]=c[0];r=c[1],t=r<e.length}}return s},I=(e,o)=>{const{end:r}=t.bytesToIntBy128(e,1),s=e.slice(r),i=t.bytesToUint(s.slice(0,2));let n,c=0;if(5===o.protocolVersion){c=s[2];const{num:o,end:r}=t.bytesToIntBy128(s,3);n=P(e.slice(r,o))}return{id:i,reasonCode:c,properties:n}},B=(o,r)=>s(void 0,void 0,void 0,(function*(){const{dup:s,qos:n=0,topicName:c,id:a,properties:l,payload:d}=r;let u=0|(s?0===n?0:8:0);u|=n<<1;const p=i(e.PUBLISH,u);p.header(t.stringToBytes(c),!0),n>0&&p.header(t.uintToBytes(a,2)),5===o.protocolVersion&&(f(l,p.cache),p.putHeader()),p.payload(d,!1);try{yield o.send(p.getPacket())}catch(e){return void o.emitError(e)}if(0!==n)if(1===n)try{yield q(o,r)}catch(e){B(o,r)}else try{const e=yield x(o,a);o.options.onPubrel?U(o,o.options.onPubrel(e)):U(o,{id:a,reasonCode:0}),yield N(o,r)}catch(e){B(o,r)}})),E=(e,o,r,n=0)=>s(void 0,void 0,void 0,(function*(){const{id:s,properties:c,reasonCode:a}=o,l=i(r,n);l.header(t.uintToBytes(s,2)),5===e.protocolVersion&&(l.header(a||0),f(c,l.cache),l.putHeader()),e.send(l.getPacket())})),w=(o,t)=>s(void 0,void 0,void 0,(function*(){E(o,t,e.PUBACK)})),U=(o,t)=>s(void 0,void 0,void 0,(function*(){E(o,t,e.PUBREL,2)})),A=(o,t)=>s(void 0,void 0,void 0,(function*(){E(o,t,e.PUBREC,0)})),S=(o,t)=>s(void 0,void 0,void 0,(function*(){E(o,t,e.PUBCOMP,0)})),q=(o,t)=>s(void 0,void 0,void 0,(function*(){return new Promise(((r,s)=>{const i=c=>{if(c[0]>>4===e.PUBACK){const e=I(c,o);if(e.id===t.id)if(o.offMessage(i),clearTimeout(n),0===e.reasonCode)r(e);else{const t={errCode:63010,errMsg:`MQTT publish failure, code: ${e.reasonCode}`};s(t),o.emitError(t)}}};o.onMessage(i);const n=setTimeout((()=>{o.offMessage(i),o.close();const e={errCode:63009,errMsg:"Mqtt publish timeout"};s(e),o.emitError(e)}),1e4)}))})),x=(o,t)=>s(void 0,void 0,void 0,(function*(){return new Promise(((r,s)=>{const i=c=>{if(c[0]>>4===e.PUBREC){const e=I(c,o);if(e.id===t)if(o.offMessage(i),clearTimeout(n),0===e.reasonCode)r(e);else{const t={errCode:63010,errMsg:`MQTT publish failure, code: ${e.reasonCode}`};s(t),o.emitError(t)}}};o.onMessage(i);const n=setTimeout((()=>{o.offMessage(i),o.close();const e={errCode:63009,errMsg:"Mqtt publish timeout"};s(e),o.emitError(e)}),1e4)}))})),N=(o,t)=>s(void 0,void 0,void 0,(function*(){return new Promise(((r,s)=>{const i=c=>{if(c[0]>>4===e.PUBCOMP){const e=I(c,o);if(e.id===t.id)if(o.offMessage(i),clearTimeout(n),0===e.reasonCode)r(e);else{const t={errCode:63010,errMsg:`MQTT publish failure, code: ${e.reasonCode}`};s(t),o.emitError(t)}}};o.onMessage(i);const n=setTimeout((()=>{o.offMessage(i),o.close();const e={errCode:63009,errMsg:"Mqtt publish timeout"};s(e),o.emitError(e)}),1e4)}))}));v((()=>!(!window||!window.WebSocket)),((e,o)=>s(void 0,void 0,void 0,(function*(){const t=new WebSocket(e,4===o?["mqttv3.1"]:["mqtt"]);return{onOpen:e=>{t.addEventListener("open",e)},send:e=>{t.send(e)},close:()=>0===t.bufferedAmount?t.close():new Promise(((e,o)=>{let r=0;const s=setInterval((()=>{r++,200===r&&o(),0===t.bufferedAmount&&(clearInterval(s),t.close(),e(!0))}),16)})),onClose:e=>{t.addEventListener("close",e)},onMessage:e=>{t.addEventListener("message",e)},onError:e=>{t.addEventListener("error",e)}}}))));v((()=>!("undefined"==typeof wx||!t.BaseApi.hasBaseApi("connectSocket"))),((e,o)=>s(void 0,void 0,void 0,(function*(){const r=yield((e,o)=>s(void 0,void 0,void 0,(function*(){return new Promise(((r,s)=>{const i=t.BaseApi.connectSocket({url:e,protocols:4===o?["mqttv3.1"]:["mqtt"],fail:s});i&&r(i)}))})))(e,o);return{onOpen:e=>{r.onOpen(e)},send:e=>new Promise(((o,t)=>{r.send({data:e,fail:t,success:o})})),close:()=>{r.close()},onClose:e=>{r.onClose(e)},onMessage:e=>{r.onMessage(e)},onError:e=>{r.onError(e)}}}))));const k=(e,o)=>{const r=(e=>{let o=0;const r=e[o++],{num:s,end:i}=t.bytesToIntBy128(e,1);return{reasonCode:r,properties:P(e.slice(i,i+s))}})(e);if(24===r.reasonCode){if(void 0===o.options.onAuth)throw{errCode:63018,errMsg:"The option onAuth not set"};m(o,o.options.onAuth(r))}},O=(e,o)=>{const r=((e,o)=>{const r=e[0],s=(6&r)>>1,i=(8&r)>>3==1;let n=1;const{num:c,end:a}=t.bytesToIntBy128(e,n),l=a+c;n=a;const d=T(e,n),[u]=d;let p,f;if(n=d[1],s>0&&(p=t.bytesToUint(e.slice(n,n+=2))),5===o.protocolVersion){const{num:o,end:r}=t.bytesToIntBy128(e,n);f=P(e.slice(r,o)),n=o+r}return{qos:s,dup:i,topicName:u,id:p,payload:e.slice(n,l),properties:f}})(e,o);let{topicName:s}=r;if(o.protocolVersion>=5&&r.properties){const{topicAlias:e}=r.properties;if(e)if(s)o.applyTopic(e,s);else if(s=o.getTopic(e),!s)return void o.emitError({errCode:63019,errMsg:"Received unregistered Topic Alias"})}if(o.checkTopic(s))switch(r.qos){case 0:o.emitMqttMessage({topic:s,payload:r.payload});break;case 1:o.options.onPuback?w(o,o.options.onPuback(r)):w(o,{id:r.id,reasonCode:0});break;case 2:o.options.onPubrec?A(o,o.options.onPubrec(r)):A(o,{id:r.id,reasonCode:0})}else o.emitError({errCode:63020,errMsg:"Received unsubscribe Topic"})},R=(e,o)=>{const t=I(e,o);o.options.onPubcomp?S(o,o.options.onPubcomp(t)):S(o,{id:t.id,reasonCode:0})},D=o=>{const t=1e3*(o.options.keepalive||60),r=()=>s(void 0,void 0,void 0,(function*(){try{!o.isClose()&&(yield(o=>(o.send(new Uint8Array([e.PINGREQ<<4,0])),new Promise(((t,r)=>{const s=r=>{r[0]>>4===e.PINGRESP&&(o.offMessage(s),clearTimeout(i),t(!0))};o.onMessage(s);const i=setTimeout((()=>{o.offMessage(s),o.close(),r({errCode:63016,errMsg:"Mqtt ping timeout"})}),1e4)}))))(o)),setTimeout(r,t)}catch(e){console.warn("ping error",e),o.emitError(e),o.close(e)}}));setTimeout(r,t)};exports.createMQTT=o=>s(void 0,void 0,void 0,(function*(){const n=yield(e=>s(void 0,void 0,void 0,(function*(){const{protocolVersion:o=4}=e,t=y.find((e=>e[0]()));if(t){let i=0;const n=r.createEmitter();let c=null,a=0;const l={},d=[];return{options:e,protocolVersion:o,sessionPresent:0,connect:(r=!1)=>s(void 0,void 0,void 0,(function*(){if(r&&c)try{c.close()}catch(e){}const s=++a;return i=0,c=yield t[1](e.url,o),new Promise(((e,o)=>{const t=setTimeout((()=>{i=2,o(new Error("ws connect time out"))}),1e4);c&&c.onError((e=>{if(0===i)clearTimeout(t),o(e);else if(s===a){const o=i;i=2,n.emit("error",e),2==o&&n.emit("close",e)}})),c&&c.onOpen((()=>{clearTimeout(t),i=1,c&&c.onClose((e=>{if(s===a){const o=i;i=2,2==o&&n.emit("close",e)}})),c&&c.onMessage((e=>{s===a&&n.emit("message",new Uint8Array(e.data))})),e(!0)}))}))})),isClose:()=>2===i,isOnline:()=>1===i,getStatus:()=>i,send:e=>{if(c&&1===i)return c.send(e.buffer);throw{errCode:63017,errMsg:"Websocket is closed"}},onClose:e=>{n.on("close",e)},offClose:e=>{n.off("close",e)},onError:e=>{n.on("error",e)},offError:e=>{n.off("error",e)},onMessage:e=>{n.on("message",e)},offMessage:e=>{n.off("message",e)},close:e=>{const o=i;i=2,2!==o&&n.emit("close",e),c&&c.close()},emitError:e=>{n.emit("error",e)},emitMqttMessage:e=>{n.emit("mqttMessage",e)},onMqttMessage:e=>{n.on("mqttMessage",e)},offMqttMessage:e=>{n.off("mqttMessage",e)},applyTopic:(e,o)=>{l[e]=o},getTopic:e=>l[e],addTopic:e=>{-1===d.indexOf(e)&&d.push(e)},removeTopic:e=>{const o=d.indexOf(e);o>=0&&d.splice(o,1)},clearTopic:()=>{d.length=0},checkTopic:e=>d.some((o=>function(e,o){const t=e.split("/"),r=e.split("/");if(e===o)return!0;for(let e=0;e<r.length;e++){const o=t[e];switch(o){case"#":return!0;case"+":continue;default:if(o!==r[e])return!1}}return!1}(o,e)))}}throw{errCode:63e3,errMsg:"The current environment does not support MQTT"}})))(o);yield n.connect(),n.onMessage((o=>{((o,r)=>{const s=o[0]>>4,{end:i,num:n}=t.bytesToIntBy128(o,1);switch(s){case e.AUTH:return k(o.slice(i,i+n),r);case e.PUBLISH:return O(o,r);case e.PUBCOMP:return R(o,r);case e.DISCONNECT:r.close()}})(o,n)})),yield((o,r)=>s(void 0,void 0,void 0,(function*(){const{protocolVersion:s=4,connectTimeout:n=10,username:c,password:a,will:l,keepalive:d=60,clean:u,clientId:p}=r,m=i(e.CONNECT);m.header([0,4,77,81,84,84]),m.header(s);let y=0;if(y|=c?128:0,y|=a?64:0,y|=l&&l.retain?32:0,y|=l&&l.qos?l.qos<<3:0,y|=l?4:0,y|=u?2:0,m.header(y),m.header(t.uintToBytes(d,2)),5===s&&(f(r.properties,m.cache),m.putHeader()),s<4)throw{errCode:63001,errMsg:"ClientId must be supplied before 3.1.1"};if(!1===u)throw{errCode:63002,errMsg:"ClientId must be given if clean set to 0"};if(m.payload(p),l){if(5===s){if(!l.properties)throw{errCode:63006,errMsg:"Will properties must be given if will has seted, when protocol version is 5.x "};m.cleanCache(),f(l.properties,m.cache),m.putPayload()}if(!l.topic)throw{errCode:63003,errMsg:"Will topic must be given if will has seted"};if(m.payload(l.topic),!l.payload)throw{errCode:63004,errMsg:"Will payload must be given if will has seted"};m.payload(l.payload)}return c&&m.payload(c),a&&m.payload(a),o.send(m.getPacket()),new Promise(((r,s)=>{const i=n=>{if(n[0]>>4===e.CONNACK){o.offMessage(i),clearTimeout(c);const{end:e}=t.bytesToIntBy128(n,1),a=n.slice(e),l=1&a[0];o.sessionPresent=l;const d=a[1];return 0===d?void r(!0):void s({errCode:63008,errMsg:`MQTT connect failure, code: ${d}`})}};o.onMessage(i);const c=setTimeout((()=>{o.offMessage(i),o.close(),s({errCode:63007,errMsg:"Mqtt Connect timeout"})}),1e3*n)}))})))(n,o),D(n);let c=0;const a=()=>(++c,16777215===c&&(c=1),c);return{getStatus:n.getStatus,onMessage:n.onMqttMessage,offMessage:n.offMqttMessage,subscribe:(o,r)=>s(void 0,void 0,void 0,(function*(){if((o=o.filter((e=>!n.checkTopic(e.topic)))).length){const c=yield((o,r)=>s(void 0,void 0,void 0,(function*(){const{id:s,properties:n,payload:c}=r,a=i(e.SUBSCRIBE,2);if(a.header(t.uintToBytes(s,2)),5===o.protocolVersion){if(!n)throw{errCode:63005,errMsg:"Properties must be given when protocol version is 5.x"};f(n,a.cache),a.putHeader()}return c.forEach((e=>{a.payload(e.topic);let t=e.qos||0;if(5===o.protocolVersion){const{nl:o=0,rap:r=0,rh:s=0}=e;t|=o<<2,t|=r<<3,t|=s<<4}a.payload(t,!1)})),o.send(a.getPacket()),new Promise(((r,i)=>{const n=i=>{if(i[0]>>4===e.SUBACK){const e=t.bytesToIntBy128(i,1),a=e.end+e.num,l=i.slice(e.end,a);if(t.bytesToUint(l.slice(0,2))===s){let e,s=2;if(5===o.protocolVersion){const{end:o,num:r}=t.bytesToIntBy128(l,s);s=o+r,e=P(l.slice(o,s))}const i=l.slice(s);o.offMessage(n),clearTimeout(c),r({reasonCode:i,properties:e})}}};o.onMessage(n);const c=setTimeout((()=>{o.offMessage(n),o.close(),i({errCode:63011,errMsg:"Mqtt subscribe timeout"})}),1e4)}))})))(n,{id:a(),properties:null==r?void 0:r.properties,payload:o}),l=o.reduce(((e,t,r)=>(c.reasonCode[r]>=128?e[t.topic]=c.reasonCode[r]:o.map((e=>n.addTopic(e.topic))),e)),{});return{properties:c.properties,err:Object.keys(l).length?l:void 0}}return{}})),unsubscribe:(o,r)=>s(void 0,void 0,void 0,(function*(){if((o=o.filter((e=>n.checkTopic(e)))).length){const s=yield((o,r)=>{const{id:s,properties:n,topics:c}=r,a=i(e.UNSUBSCRIBE,2);return a.header(t.uintToBytes(s,2)),5===o.protocolVersion&&(f(n,a.cache),a.putHeader()),c.forEach((e=>{a.payload(e)})),o.send(a.getPacket()),new Promise(((r,i)=>{const n=i=>{if(i[0]>>4===e.UNSUBACK){const e=t.bytesToIntBy128(i,1),l=e.end+e.num,d=i.slice(e.end,l);if(t.bytesToUint(d.slice(0,2))===s){let e,s=2;if(5===o.protocolVersion){const{end:o,num:r}=t.bytesToIntBy128(d,s);s=o+r,e=P(d.slice(o,s))}const i=d.slice(s);o.offMessage(n),clearTimeout(a),i.length?r({reasonCode:i,properties:e}):r({reasonCode:new Uint8Array(c.map((()=>0))),properties:e})}}};o.onMessage(n);const a=setTimeout((()=>{o.offMessage(n),o.close(),i({errCode:63014,errMsg:"Mqtt unsubscribe timeout"})}),1e4)}))})(n,{id:a(),properties:null==r?void 0:r.properties,topics:o}),c=o.reduce(((e,t,r)=>(s.reasonCode[r]>=128?e[t]=s.reasonCode[r]:o.map((e=>n.removeTopic(e))),e)),{});return{err:Object.keys(c).length?c:void 0}}return{}})),publish:(e,o,r)=>{const s=a();return B(n,Object.assign({id:s,topicName:e,payload:"string"==typeof o?t.stringToBytes(o):o},r))},reAuth:e=>{m(n,Object.assign(Object.assign({},e),{reasonCode:25}))},disconnect:o=>{((o,t)=>{s(void 0,void 0,void 0,(function*(){const{reasonCode:r=0,properties:s}=t,n=i(e.DISCONNECT);5===o.protocolVersion&&(n.header(r),f(s,n.cache),n.putHeader()),yield o.send(n.getPacket()),o.close()}))})(n,o||{reasonCode:0})},onClose:n.onClose,onError:n.onError}}));
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("@ray-js/wechat-mqtt-core"),t=require("@ray-js/wechat-event"),n=require("js-md5"),o=require("@ray-js/wechat-tycrypto"),i=require("@ray-js/wechat-helper"),s=require("js-base64"),c=require("@ray-js/wechat-debug");function r(e,t,n,o){return new(n||(n=Promise))((function(i,s){function c(e){try{a(o.next(e))}catch(e){s(e)}}function r(e){try{a(o.throw(e))}catch(e){s(e)}}function a(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(c,r)}a((o=o.apply(e,t||[])).next())}))}const a=(e,t)=>{const o=Object.keys(e).sort(((e,t)=>e<t?-1:1)).reduce(((t,n)=>e[n]||0===e[n]?t.concat(`${n}=${e[n]}`):t),[]);o.push(t);const i=o.join("||");return n.hex(i)},l=(e,t)=>{const{sign:n}=e,o=function(e,t){var n={};for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&t.indexOf(o)<0&&(n[o]=e[o]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var i=0;for(o=Object.getOwnPropertySymbols(e);i<o.length;i++)t.indexOf(o[i])<0&&Object.prototype.propertyIsEnumerable.call(e,o[i])&&(n[o[i]]=e[o[i]])}return n}(e,["sign"]);return a(o,t)===n},d={"2.0":(e,t)=>{const{localKey:n}=t,s=JSON.parse(i.bytesToString(e));if(16===s.protocol)return s;if(l(s,n)){const e=i.hexToBytes(s.data),t=i.bytesToString(o.AES_ECB.decrypt(e,i.stringToBytes(n),!0)),c=JSON.parse(t);return Object.assign(Object.assign({},s),{data:c})}throw Error("check sign invalid")},2.1:(e,t)=>{const{localKey:n}=t,c=i.bytesToString(e.slice(0,3)),r=i.bytesToString(e.slice(3,19)),l=s.Base64.toUint8Array(i.bytesToString(e.slice(19)));if(r===a({data:l,pv:c},n).slice(8,24)){const e=i.bytesToString(o.AES_ECB.decrypt(l,i.stringToBytes(n),!0)),t=JSON.parse(e);return Object.assign({pv:c},t)}throw Error("check sign invalid")},2.2:(e,t)=>{const{localKey:n}=t,s=i.bytesToString(e.slice(0,3)),c=i.bytesToInt(e.slice(3,7)),r=i.bytesToInt(e.slice(7,11)),a=i.bytesToInt(e.slice(11,15)),l=e.slice(15);if(i.CRC32(e.slice(7))===c){const e=i.bytesToString(o.AES_ECB.decrypt(l,i.stringToBytes(n),!0)),t=JSON.parse(e);return Object.assign({pv:s,sn:r,source:a},t)}throw Error("check crc32 invalid")},2.3:(e,t)=>{const{localKey:n}=t,s=i.bytesToString(e.slice(0,3)),c=i.bytesToInt(e.slice(3,7)),r=i.bytesToInt(e.slice(7,11)),a=e.slice(12,24),l=e.slice(24),d=e.slice(0,12),p=i.bytesToString(o.AES_GCM.decrypt(l,i.stringToBytes(n),a,d)),u=JSON.parse(p);return Object.assign({pv:s,sn:c,source:r},u)}},p=e=>(e||(e=+new Date),e.toString().length>10?Math.floor(e/1e3):e),u={"2.0":(e,t)=>{const{localKey:n}=t,s=o.AES_ECB.encrypt(i.stringToBytes(JSON.stringify(e.data)),i.stringToBytes(n),!0),c={protocol:e.protocol,pv:"2.0",t:p(e.time),data:i.bytesToHex(s),gwId:e.devId};return c.sign=a(c,n),i.stringToBytes(JSON.stringify(c))},2.1:(e,t)=>{const{localKey:n}=t,c={protocol:e.protocol,t:p(e.time),data:e.data},r=s.Base64.fromUint8Array(o.AES_ECB.encrypt(i.stringToBytes(JSON.stringify(c)),i.stringToBytes(n),!0)),l=a({data:r,pv:"2.1"},n).slice(8,24);return i.stringToBytes(`2.1${l}${r}`)},2.2:(e,t)=>{var n,s;const{localKey:c}=t,r=null!==(n=e.sn)&&void 0!==n?n:0,a=null!==(s=e.source)&&void 0!==s?s:0,l={protocol:e.protocol,t:p(e.time),data:e.data},d=o.AES_ECB.encrypt(i.stringToBytes(JSON.stringify(l)),i.stringToBytes(c),!0),u=new Uint8Array(15+d.length),g=new DataView(u.buffer);u.set(i.stringToBytes("2.2"),0),g.setInt32(7,r),g.setInt32(11,a),u.set(d,15);const y=i.CRC32(u.slice(7));return g.setInt32(3,y),u},2.3:(e,t)=>{var n,s;const{localKey:c}=t,r=null!==(n=e.sn)&&void 0!==n?n:0,a=null!==(s=e.source)&&void 0!==s?s:0,l={protocol:e.protocol,t:p(e.time),data:e.data,gwId:t.devId},d=i.randomBytes(12),u=new Uint8Array(12),g=new DataView(u.buffer);u.set(i.stringToBytes("2.3"),0),g.setInt32(3,r),g.setInt32(7,a),u[11]=0;const y=o.AES_GCM.encrypt(i.stringToBytes(JSON.stringify(l)),i.stringToBytes(c),d,u),v=new Uint8Array(24+y.length);return v.set(u,0),v.set(d,12),v.set(y,24),v}},g=t.createEmitter({globalKey:"__mqttEvent"}),y=c.useChanel("MQTT",{needCollection:!1});y.start();var v;!function(e){e[e.CONNECT_BREAK=0]="CONNECT_BREAK",e[e.CONNECTED=1]="CONNECTED",e[e.CONNECTING=2]="CONNECTING"}(v||(v={}));const T=i.getGlobal();T.mqttData||(T.mqttData={client:null,reconnectCount:0,reconnectEnabled:!0,isConnecting:!1,needManualReconnect:!1,currentOptions:{},topicData:{homeIds:new Set,deviceIds:new Set,devices:new Map},mqttType:"standard"});const h=T.mqttData;let f=()=>{};const b=(e,t)=>{if("standard"===h.mqttType)if(h.topicData.devices.has(e)){const n=h.topicData.devices.get(e);try{const o=((e,t)=>{let n="2.0";if("{"!==i.bytesToString(e.slice(0,1))&&(n=i.bytesToString(e.slice(0,3)),/\d\.\d/.test(n)||(n="2.0")),d[n])return d[n](e,t);throw new Error(`Not suppport pv ${n}`)})(t,n);o.t&&10===o.t.toString().length&&(o.t*=1e3),g.emit("message",{topic:e,payload:Object.assign({gwId:n.devId},o),mqttType:h.mqttType})}catch(e){y.log("decrypt error: ",e)}}else h.topicData.homeIds.has(e)&&g.emit("message",{topic:e,payload:JSON.parse(i.bytesToString(t)),mqttType:h.mqttType});else g.emit("message",{topic:e,payload:JSON.parse(i.bytesToString(t)),mqttType:h.mqttType})},C=()=>r(void 0,void 0,void 0,(function*(){if(y.log("Reconnect"),h.isConnecting)y.log("Has one Connecting");else if(h.needManualReconnect)y.log("Requires manual reconnection");else if(h.reconnectEnabled){h.reconnectCount++;const e=()=>r(void 0,void 0,void 0,(function*(){try{const e={homeIds:[],devices:[]};h.topicData.homeIds.forEach((t=>{e.homeIds.push(t)})),h.topicData.devices.forEach((t=>{e.devices.push(t)})),yield m({needReopen:!0,loadMQTTConfig:f}),h.topicData={homeIds:new Set,devices:new Map},E(e)}catch(e){if(6e4===e.code||6e4===e.errCode||63021===e.errCode)return;C()}}));h.reconnectCount<=3?e():(I(),setTimeout((()=>{h.client||e()}),2e3*(h.reconnectCount-3)))}}));let S=0;const m=t=>r(void 0,void 0,void 0,(function*(){var n,o;if(h.isConnecting){y.log("Has one Connecting"),yield i.sleep(3e3,(()=>!!h.client&&h.client.getStatus()>0));const e=null===(n=h.client)||void 0===n?void 0:n.getStatus();if(1==e)return;if(2===e)throw{code:63008,errMsg:"MQTT connect failure"};if(h.isConnecting)return m(t)}if(h.needManualReconnect=!1,t.needReopen)h.client&&(y.log("Need destroy old one"),I());else if(h.client){if(1===h.client.getStatus())return void y.log("Already connected")}y.log("Start connecting"),h.isConnecting=!0,g.emit("stateChange",v.CONNECTING);const s=++S;try{const n=null!==(o=t.mqttType)&&void 0!==o?o:"standard";if(y.log("Get config"),!t.loadMQTTConfig)throw{errCode:63021,errMsg:"loadMQTTConfig callback function not set"};f=t.loadMQTTConfig;const i=yield f();y.log("Get config clientId:",i.clientId),h.currentOptions=i,y.log("Connecting MQTT"),h.client=yield e.createMQTT(Object.assign({},i)),y.log("Connected"),h.mqttType=n,h.client.onMessage((({topic:e,payload:t})=>{s===S&&b(e,t)})),h.client.onClose((e=>{s===S&&(y.log("Connect closed",e),g.emit("stateChange",v.CONNECT_BREAK),h.client&&C())})),g.emit("stateChange",v.CONNECTED),h.isConnecting=!1,h.reconnectCount=0}catch(e){throw y.error("Connect Failure",e),h.isConnecting=!1,e}})),E=e=>r(void 0,void 0,void 0,(function*(){var t,n;if(y.log("Will subscribe data",e),h.client){const{topicData:{homeIds:o,devices:i},currentOptions:{homeTopicTpl:s,deviceSubscribeTopicTpl:c}}=h,r=[];if(null===(t=e.homeIds)||void 0===t||t.forEach((e=>{const t=s.replace("{ownerId}",e.toString());o.has(t)||r.push({homeId:e,topic:t})})),null===(n=e.devices)||void 0===n||n.forEach((e=>{const t=c.replace("{devId}",e.devId);i.has(t)||r.push(Object.assign(Object.assign({},e),{topic:t}))})),y.log("Will subscribe topics",r),r.length)for(let e=0;e<r.length;e+=10){const t=r.slice(e,e+10),n=yield h.client.subscribe(t);n.err?y.warn("subscribe topic error",n):t.forEach((e=>{e.homeId?o.add(e.topic):e.devId&&i.set(e.topic,e)}))}}})),I=()=>{var e,t;1===(null===(e=h.client)||void 0===e?void 0:e.getStatus())&&(g.emit("stateChange",v.CONNECT_BREAK),null===(t=h.client)||void 0===t||t.disconnect()),h.client=null},O=e=>{g.on("message",e)},w=e=>{g.off("message",e)},N=()=>!!h.client&&1===h.client.getStatus(),B=e=>{const t=h.currentOptions.password.substring(8,24),c=i.stringToBytes(t),{protocol:r,data:a,deviceId:l}=e;if(l){const e=o.AES_ECB.encrypt(i.stringToBytes(JSON.stringify(a)),c,!0),d={protocol:r,pv:"2.0",t:+new Date,data:s.Base64.fromUint8Array(e),client_id:h.currentOptions.clientId,sign:""};return d.sign=((e,t)=>{const o=Object.keys(e).sort(((e,t)=>e<t?-1:1)).reduce(((t,n)=>e[n]||0===e[n]?t.concat(`${n}=${e[n]}`):t),[]);o.push(t);const i=o.join("||");return n.hex(i)})(d,t),h.client&&h.client.publish(h.currentOptions.deviceSendTopicTpl.replace("{devId}",l||""),JSON.stringify(d))}throw new Error("Not support this protocol")},M=e=>{const{protocol:t,data:n,deviceId:o,localKey:i,pv:s="2.0"}=e;if(o&&i){const e=((e,t,n)=>{if(u[n])return u[n](e,t);throw new Error(`Not suppport pv ${n}`)})({protocol:t,data:n,devId:o},{devId:o,localKey:i,pv:s},s);return h.client&&h.client.publish(h.currentOptions.deviceSendTopicTpl.replace("{devId}",o),e)}throw new Error("Not support this protocol")};let D=!1,j=+new Date;i.BaseApi.onAppShow((()=>{if(!D)return;h.reconnectEnabled=!0,h.reconnectCount=0,D=!1;if(+new Date-j>3e3)C();else if(h.client)if(1===h.client.getStatus()){const e=()=>{w(e),clearTimeout(t)},t=setTimeout((()=>{w(e),C()}),6e4);O(e)}else C()})),i.BaseApi.onAppHide((()=>{D=!0,h.reconnectEnabled=!1,j=+new Date}));exports.checkSubscribeDevice=e=>{if(h.client&&N()){const{topicData:{devices:t},currentOptions:{deviceSubscribeTopicTpl:n}}=h,o=n.replace("{devId}",e);return t.has(o)}return!1},exports.clearTopics=()=>r(void 0,void 0,void 0,(function*(){if(y.log("Clear topics"),h.client){const{topicData:{homeIds:e,devices:t},currentOptions:{homeTopicTpl:n,deviceSubscribeTopicTpl:o}}=h,i=[];t.forEach((e=>{i.push(o.replace("{devId}",e.devId))})),e.forEach((e=>{i.push(n.replace("{ownerId}",e.toString()))}));for(let e=0;e<i.length;e+=10)yield h.client.unsubscribe(i.slice(e,e+10))}h.topicData={homeIds:new Set,devices:new Map}})),exports.connect=m,exports.destroy=()=>{y.log("Manual disconnect"),h.needManualReconnect=!0,I()},exports.getState=N,exports.offMessage=w,exports.offStateChange=e=>{g.off("stateChange",e)},exports.onMessage=O,exports.onStateChange=e=>{g.on("stateChange",e)},exports.publish=e=>{if(y.log("Send message:",e),h.client)return"open"===h.mqttType?B(e):M(e);throw{errCode:60002,errMsg:"MQTT not connected"}},exports.subscribeTopics=E,exports.unsubscribeTopics=e=>r(void 0,void 0,void 0,(function*(){var t,n;if(y.log("unsubscribe topics:",e),h.client){const{topicData:{homeIds:o,devices:i},currentOptions:{homeTopicTpl:s,deviceSubscribeTopicTpl:c}}=h,r=[];null===(t=e.homeIds)||void 0===t||t.forEach((e=>{const t=s.replace("{ownerId}",e.toString());o.has(t)&&(r.push(t),o.delete(t))})),null===(n=e.deviceIds)||void 0===n||n.forEach((e=>{const t=c.replace("{devId}",e);i.get(t)&&(r.push(t),i.delete(t))}));for(let e=0;e<r.length;e+=10)yield h.client.unsubscribe(r.slice(e,e+10))}}));
|
package/lib/decrypt.d.ts
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { MQTTDevice } from './interface';
|
|
2
|
+
interface Message {
|
|
3
|
+
data: Record<string, any>;
|
|
4
|
+
protocol: number;
|
|
5
|
+
pv: string;
|
|
6
|
+
t: number;
|
|
7
|
+
sn?: number;
|
|
8
|
+
source?: number;
|
|
9
|
+
}
|
|
10
|
+
export declare const decryptMessage: (payload: Uint8Array, device: MQTTDevice) => Message;
|
|
11
|
+
export {};
|
package/lib/encrypt.d.ts
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { MQTTDevice } from './interface';
|
|
2
|
+
interface SendMessage {
|
|
3
|
+
devId?: string;
|
|
4
|
+
protocol: number;
|
|
5
|
+
data: Record<string, any>;
|
|
6
|
+
time?: number;
|
|
7
|
+
sn?: number;
|
|
8
|
+
source?: number;
|
|
9
|
+
}
|
|
10
|
+
export declare const encryptMessage: (message: SendMessage, device: MQTTDevice, pv: string) => Uint8Array;
|
|
11
|
+
export {};
|
package/lib/interface.d.ts
CHANGED
|
@@ -1,178 +1,5 @@
|
|
|
1
|
-
export
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
data: ArrayBuffer;
|
|
7
|
-
}) => void): void;
|
|
8
|
-
onOpen(cb: (data: any) => void): void;
|
|
9
|
-
onError(cb: (ev: any) => void): void;
|
|
10
|
-
}
|
|
11
|
-
export interface MQTTMessage {
|
|
12
|
-
topic: string;
|
|
13
|
-
payload: Uint8Array;
|
|
14
|
-
}
|
|
15
|
-
export interface ClientConntroller {
|
|
16
|
-
options: Options;
|
|
17
|
-
protocolVersion: number;
|
|
18
|
-
sessionPresent: number;
|
|
19
|
-
connect(isReconnect?: boolean): Promise<any>;
|
|
20
|
-
isClose(): boolean;
|
|
21
|
-
isOnline(): boolean;
|
|
22
|
-
getStatus(): 0 | 1 | 2;
|
|
23
|
-
close: (err?: any) => void;
|
|
24
|
-
onClose(cb: (ev: any) => void): void;
|
|
25
|
-
send(data: ArrayBuffer | ArrayBufferView): void;
|
|
26
|
-
onError(cb: (ev: any) => void): void;
|
|
27
|
-
onMessage(cb: (data: Uint8Array) => void): void;
|
|
28
|
-
offMessage(cb: (data: Uint8Array) => void): void;
|
|
29
|
-
offClose(cb: (ev: any) => void): void;
|
|
30
|
-
offError(cb: (ev: any) => void): void;
|
|
31
|
-
emitError(data: any): void;
|
|
32
|
-
emitMqttMessage(data: MQTTMessage): void;
|
|
33
|
-
onMqttMessage(cb: (data: MQTTMessage) => void): void;
|
|
34
|
-
offMqttMessage(cb: (data: MQTTMessage) => void): void;
|
|
35
|
-
applyTopic: (topicAlias: number, topicName: string) => void;
|
|
36
|
-
getTopic: (topicAlias: number) => string;
|
|
37
|
-
checkTopic: (topicName: string) => boolean;
|
|
38
|
-
addTopic: (topic: string) => void;
|
|
39
|
-
removeTopic: (topic: string) => void;
|
|
40
|
-
clearTopic: () => void;
|
|
41
|
-
}
|
|
42
|
-
export declare type QoS = 0 | 1 | 2;
|
|
43
|
-
export declare type UserProperties = Record<string, string | string[]>;
|
|
44
|
-
export interface Options {
|
|
45
|
-
url: string;
|
|
46
|
-
username?: string;
|
|
47
|
-
password?: string;
|
|
48
|
-
clientId: string;
|
|
49
|
-
protocolVersion?: number;
|
|
50
|
-
keepalive?: number;
|
|
51
|
-
clean?: boolean;
|
|
52
|
-
will?: {
|
|
53
|
-
topic: string;
|
|
54
|
-
payload: Uint8Array | string;
|
|
55
|
-
qos: QoS;
|
|
56
|
-
retain: boolean;
|
|
57
|
-
properties?: {
|
|
58
|
-
willDelayInterval?: number;
|
|
59
|
-
payloadFormatIndicator?: boolean;
|
|
60
|
-
sessionExpiryInterval?: number;
|
|
61
|
-
contentType?: string;
|
|
62
|
-
responseTopic?: string;
|
|
63
|
-
correlationData?: Uint8Array;
|
|
64
|
-
userProperties?: UserProperties;
|
|
65
|
-
};
|
|
66
|
-
};
|
|
67
|
-
properties?: {
|
|
68
|
-
sessionExpiryInterval?: number;
|
|
69
|
-
receiveMaximum?: number;
|
|
70
|
-
maximumPacketSize?: number;
|
|
71
|
-
topicAliasMaximum?: number;
|
|
72
|
-
requestResponseInformation?: boolean;
|
|
73
|
-
requestProblemInformation?: boolean;
|
|
74
|
-
userProperties?: UserProperties;
|
|
75
|
-
authenticationMethod?: string;
|
|
76
|
-
authenticationData?: Uint8Array;
|
|
77
|
-
};
|
|
78
|
-
connectTimeout?: number;
|
|
79
|
-
onAuth?: (options: AuthOptions) => AuthOptions;
|
|
80
|
-
onPuback?: (options: Message) => PuplishResponse;
|
|
81
|
-
onPubrel?: (options: PuplishResponse) => PuplishResponse;
|
|
82
|
-
onPubrec?: (options: Message) => PuplishResponse;
|
|
83
|
-
onPubcomp?: (options: PuplishResponse) => PuplishResponse;
|
|
84
|
-
}
|
|
85
|
-
export declare type QOS = 0 | 1 | 2;
|
|
86
|
-
export interface Message {
|
|
87
|
-
id?: number;
|
|
88
|
-
dup?: boolean;
|
|
89
|
-
qos?: QOS;
|
|
90
|
-
topicName: string;
|
|
91
|
-
properties?: {
|
|
92
|
-
payloadFormatIndicator?: boolean;
|
|
93
|
-
messageExpiryInterval?: number;
|
|
94
|
-
topicAlias?: number;
|
|
95
|
-
responseTopic?: string;
|
|
96
|
-
correlationData?: string;
|
|
97
|
-
userProperties?: UserProperties;
|
|
98
|
-
subscriptionIdentifier?: number;
|
|
99
|
-
contentType?: string;
|
|
100
|
-
};
|
|
101
|
-
payload: Uint8Array;
|
|
102
|
-
}
|
|
103
|
-
export interface MessageOption {
|
|
104
|
-
dup?: boolean;
|
|
105
|
-
qos?: QOS;
|
|
106
|
-
properties?: {
|
|
107
|
-
payloadFormatIndicator?: boolean;
|
|
108
|
-
messageExpiryInterval?: number;
|
|
109
|
-
topicAlias?: number;
|
|
110
|
-
responseTopic?: string;
|
|
111
|
-
correlationData?: string;
|
|
112
|
-
userProperties?: UserProperties;
|
|
113
|
-
subscriptionIdentifier?: number;
|
|
114
|
-
contentType?: string;
|
|
115
|
-
};
|
|
116
|
-
}
|
|
117
|
-
export interface DisconnectOptions {
|
|
118
|
-
reasonCode?: number;
|
|
119
|
-
properties?: {
|
|
120
|
-
sessionExpiryInterval?: number;
|
|
121
|
-
reasonString?: string;
|
|
122
|
-
userProperties?: UserProperties;
|
|
123
|
-
serverReference?: string;
|
|
124
|
-
};
|
|
125
|
-
}
|
|
126
|
-
export interface AuthOptions {
|
|
127
|
-
reasonCode: number;
|
|
128
|
-
properties?: {
|
|
129
|
-
authenticationMethod: string;
|
|
130
|
-
authenticationData: string;
|
|
131
|
-
reasonString?: string;
|
|
132
|
-
userProperties?: UserProperties;
|
|
133
|
-
};
|
|
134
|
-
}
|
|
135
|
-
export interface PuplishResponse {
|
|
136
|
-
id: number;
|
|
137
|
-
reasonCode?: number;
|
|
138
|
-
properties?: {
|
|
139
|
-
reasonString?: string;
|
|
140
|
-
userProperties?: UserProperties;
|
|
141
|
-
};
|
|
142
|
-
}
|
|
143
|
-
export interface Client {
|
|
144
|
-
getStatus(): 0 | 1 | 2;
|
|
145
|
-
onMessage(cb: (data: MQTTMessage) => void): void;
|
|
146
|
-
offMessage(cb: (data: MQTTMessage) => void): void;
|
|
147
|
-
publish(topic: string, message: string | Uint8Array, option?: MessageOption): void;
|
|
148
|
-
reAuth(option: AuthOptions): void;
|
|
149
|
-
disconnect(option?: DisconnectOptions): void;
|
|
150
|
-
onClose(cb: () => void): void;
|
|
151
|
-
onError(cb: (e: any) => void): void;
|
|
152
|
-
subscribe: (topics: Topic[], options?: SubscribeOption) => Promise<{
|
|
153
|
-
err?: Record<string, number>;
|
|
154
|
-
properties?: any;
|
|
155
|
-
}>;
|
|
156
|
-
unsubscribe: (topic: string[], options?: UnsubscribeOption) => Promise<{
|
|
157
|
-
err?: Record<string, number>;
|
|
158
|
-
properties?: any;
|
|
159
|
-
}>;
|
|
160
|
-
}
|
|
161
|
-
export interface Topic {
|
|
162
|
-
topic: string;
|
|
163
|
-
qos?: number;
|
|
164
|
-
nl?: 0 | 1;
|
|
165
|
-
rap?: 0 | 1;
|
|
166
|
-
rh?: number;
|
|
167
|
-
}
|
|
168
|
-
export interface SubscribeOption {
|
|
169
|
-
properties?: {
|
|
170
|
-
subscriptionIdentifier: number;
|
|
171
|
-
userProperties?: UserProperties;
|
|
172
|
-
};
|
|
173
|
-
}
|
|
174
|
-
export interface UnsubscribeOption {
|
|
175
|
-
properties?: {
|
|
176
|
-
userProperties?: UserProperties;
|
|
177
|
-
};
|
|
178
|
-
}
|
|
1
|
+
export declare type MQTTDevice = {
|
|
2
|
+
devId: string;
|
|
3
|
+
localKey: string;
|
|
4
|
+
pv: string;
|
|
5
|
+
};
|
package/lib/mqtt.d.ts
ADDED
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
import { MQTTDevice } from './interface';
|
|
2
|
+
declare enum CONNECT_STATE {
|
|
3
|
+
CONNECT_BREAK = 0,
|
|
4
|
+
CONNECTED = 1,
|
|
5
|
+
CONNECTING = 2
|
|
6
|
+
}
|
|
7
|
+
export interface ConnectSetting {
|
|
8
|
+
clientId: string;
|
|
9
|
+
username: string;
|
|
10
|
+
password: string;
|
|
11
|
+
keepalive: number;
|
|
12
|
+
url: string;
|
|
13
|
+
deviceSubscribeTopicTpl: string;
|
|
14
|
+
deviceSendTopicTpl: string;
|
|
15
|
+
homeTopicTpl: string;
|
|
16
|
+
}
|
|
17
|
+
export declare type MQTTType = 'standard' | 'open';
|
|
18
|
+
interface ConnectOptions {
|
|
19
|
+
needReopen?: boolean;
|
|
20
|
+
mqttType?: MQTTType;
|
|
21
|
+
loadMQTTConfig: () => Promise<ConnectSetting>;
|
|
22
|
+
}
|
|
23
|
+
export interface DpMessageData {
|
|
24
|
+
cid?: string;
|
|
25
|
+
dps: Record<number, number | string | boolean>;
|
|
26
|
+
}
|
|
27
|
+
export interface DeviceInfoData {
|
|
28
|
+
devId: string;
|
|
29
|
+
gwId: string;
|
|
30
|
+
lastOnlineChangeTime?: number;
|
|
31
|
+
meshId?: string;
|
|
32
|
+
online?: boolean;
|
|
33
|
+
name?: string;
|
|
34
|
+
customName?: string;
|
|
35
|
+
iconUrl?: string;
|
|
36
|
+
}
|
|
37
|
+
export interface DeviceAddOrDelData {
|
|
38
|
+
devId: string;
|
|
39
|
+
gwId: string;
|
|
40
|
+
isShare: boolean;
|
|
41
|
+
}
|
|
42
|
+
export interface OTAProgressData {
|
|
43
|
+
firmwareType: number;
|
|
44
|
+
progress: number;
|
|
45
|
+
cid: string;
|
|
46
|
+
gwId: string;
|
|
47
|
+
devId?: string;
|
|
48
|
+
}
|
|
49
|
+
export interface OATStatusData {
|
|
50
|
+
type: 1 | 2;
|
|
51
|
+
firmwareType: number;
|
|
52
|
+
otaStatus: number;
|
|
53
|
+
status: number;
|
|
54
|
+
statusText: string;
|
|
55
|
+
statusTitle: string;
|
|
56
|
+
gwId: string;
|
|
57
|
+
devId: string;
|
|
58
|
+
}
|
|
59
|
+
export interface OpenMessageData {
|
|
60
|
+
topic: string;
|
|
61
|
+
payload: {
|
|
62
|
+
data: {
|
|
63
|
+
bizCode?: string;
|
|
64
|
+
devId: string;
|
|
65
|
+
status?: {
|
|
66
|
+
code: string;
|
|
67
|
+
value: boolean | string | number;
|
|
68
|
+
[key: number]: boolean | string | number;
|
|
69
|
+
}[];
|
|
70
|
+
bizData: {
|
|
71
|
+
devId: string;
|
|
72
|
+
upgradeStatus: number;
|
|
73
|
+
firmwareType: number;
|
|
74
|
+
moduleType: number;
|
|
75
|
+
progress: number;
|
|
76
|
+
name: string;
|
|
77
|
+
};
|
|
78
|
+
};
|
|
79
|
+
protocol: number;
|
|
80
|
+
pv: string;
|
|
81
|
+
};
|
|
82
|
+
mqttType: 'open';
|
|
83
|
+
}
|
|
84
|
+
export interface MessageData {
|
|
85
|
+
topic: string;
|
|
86
|
+
payload: {
|
|
87
|
+
data: DpMessageData | DeviceInfoData | DeviceAddOrDelData | OTAProgressData | OATStatusData | Record<string, any>;
|
|
88
|
+
protocol: number;
|
|
89
|
+
pv: string;
|
|
90
|
+
type: 'del' | 'update' | 'all' | 'add';
|
|
91
|
+
sn: number;
|
|
92
|
+
source: number;
|
|
93
|
+
t: number;
|
|
94
|
+
gwId: string;
|
|
95
|
+
};
|
|
96
|
+
mqttType: 'standard';
|
|
97
|
+
}
|
|
98
|
+
declare const connect: (data: ConnectOptions) => Promise<void>;
|
|
99
|
+
declare const subscribeTopics: (data: {
|
|
100
|
+
homeIds?: string[];
|
|
101
|
+
devices?: MQTTDevice[];
|
|
102
|
+
}) => Promise<void>;
|
|
103
|
+
declare const clearTopics: () => Promise<void>;
|
|
104
|
+
declare const unsubscribeTopics: (data: {
|
|
105
|
+
homeIds?: string[];
|
|
106
|
+
deviceIds?: string[];
|
|
107
|
+
}) => Promise<void>;
|
|
108
|
+
declare const checkSubscribeDevice: (devId: string) => boolean;
|
|
109
|
+
declare const onMessage: (cb: (data: MessageData | OpenMessageData) => void) => void;
|
|
110
|
+
declare const offMessage: (cb: (data: MessageData | OpenMessageData) => void) => void;
|
|
111
|
+
declare const onStateChange: (cb: (data: CONNECT_STATE) => void) => void;
|
|
112
|
+
declare const offStateChange: (cb: (data: CONNECT_STATE) => void) => void;
|
|
113
|
+
declare const getState: () => boolean;
|
|
114
|
+
declare const publish: (option: {
|
|
115
|
+
deviceId?: string;
|
|
116
|
+
protocol: number;
|
|
117
|
+
data: Record<string, any>;
|
|
118
|
+
pv?: string;
|
|
119
|
+
localKey: string;
|
|
120
|
+
time?: number;
|
|
121
|
+
sn?: number;
|
|
122
|
+
source?: number;
|
|
123
|
+
}) => void | null;
|
|
124
|
+
declare const manualDestroy: () => void;
|
|
125
|
+
export { onMessage, offMessage, manualDestroy as destroy, connect, getState, publish, onStateChange, offStateChange, subscribeTopics, unsubscribeTopics, checkSubscribeDevice, clearTopics, };
|
package/lib/util.d.ts
ADDED
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ray-js/wechat-mqtt",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.6-beta-1",
|
|
4
4
|
"publishConfig": {
|
|
5
5
|
"access": "public",
|
|
6
6
|
"registry": "https://registry.npmjs.org"
|
|
@@ -25,8 +25,13 @@
|
|
|
25
25
|
}
|
|
26
26
|
},
|
|
27
27
|
"dependencies": {
|
|
28
|
-
"@ray-js/wechat-helper": "^0.3.
|
|
29
|
-
"@ray-js/wechat-
|
|
28
|
+
"@ray-js/wechat-helper": "^0.3.6-beta-1",
|
|
29
|
+
"@ray-js/wechat-tycrypto": "^0.3.6-beta-1",
|
|
30
|
+
"js-base64": "^3.7.2",
|
|
31
|
+
"@ray-js/wechat-mqtt-core": "^0.3.6-beta-1",
|
|
32
|
+
"@ray-js/wechat-event": "^0.3.6-beta-1",
|
|
33
|
+
"js-md5": "^0.7.3",
|
|
34
|
+
"@ray-js/wechat-debug": "^0.3.6-beta-1"
|
|
30
35
|
},
|
|
31
36
|
"peerDependencies": {}
|
|
32
37
|
}
|
package/lib/adapter/blowser.d.ts
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export {};
|
package/lib/adapter/index.d.ts
DELETED
package/lib/adapter/wechat.d.ts
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export {};
|
package/lib/auth.d.ts
DELETED
package/lib/connect.d.ts
DELETED
package/lib/constant.d.ts
DELETED
|
@@ -1,47 +0,0 @@
|
|
|
1
|
-
export declare enum PacketType {
|
|
2
|
-
Reserved = 0,
|
|
3
|
-
CONNECT = 1,
|
|
4
|
-
CONNACK = 2,
|
|
5
|
-
PUBLISH = 3,
|
|
6
|
-
PUBACK = 4,
|
|
7
|
-
PUBREC = 5,
|
|
8
|
-
PUBREL = 6,
|
|
9
|
-
PUBCOMP = 7,
|
|
10
|
-
SUBSCRIBE = 8,
|
|
11
|
-
SUBACK = 9,
|
|
12
|
-
UNSUBSCRIBE = 10,
|
|
13
|
-
UNSUBACK = 11,
|
|
14
|
-
PINGREQ = 12,
|
|
15
|
-
PINGRESP = 13,
|
|
16
|
-
DISCONNECT = 14,
|
|
17
|
-
AUTH = 15
|
|
18
|
-
}
|
|
19
|
-
export declare enum PropertySign {
|
|
20
|
-
sessionExpiryInterval = 17,
|
|
21
|
-
receiveMaximum = 33,
|
|
22
|
-
maximumQoS = 36,
|
|
23
|
-
retainAvailable = 37,
|
|
24
|
-
maximumPacketSize = 39,
|
|
25
|
-
topicAliasMaximum = 34,
|
|
26
|
-
topicAlias = 35,
|
|
27
|
-
requestResponseInformation = 25,
|
|
28
|
-
requestProblemInformation = 23,
|
|
29
|
-
userProperties = 38,
|
|
30
|
-
authenticationMethod = 21,
|
|
31
|
-
authenticationData = 22,
|
|
32
|
-
willDelayInterval = 24,
|
|
33
|
-
payloadFormatIndicator = 1,
|
|
34
|
-
messageExpiryInterval = 2,
|
|
35
|
-
contentType = 3,
|
|
36
|
-
responseTopic = 8,
|
|
37
|
-
correlationData = 9,
|
|
38
|
-
subscriptionIdentifier = 11,
|
|
39
|
-
reasonString = 31,
|
|
40
|
-
assignedClientIdentifier = 18,
|
|
41
|
-
wildcardSubscriptionAvailable = 40,
|
|
42
|
-
subscriptionIdentifiersAvailable = 41,
|
|
43
|
-
sharedSubscriptionAvailable = 42,
|
|
44
|
-
serverKeepAlive = 19,
|
|
45
|
-
responseInformation = 26,
|
|
46
|
-
serverReference = 28
|
|
47
|
-
}
|
package/lib/disconnect.d.ts
DELETED
package/lib/factory.d.ts
DELETED
|
@@ -1,6 +0,0 @@
|
|
|
1
|
-
import { Adapter, ClientConntroller, Options } from './interface';
|
|
2
|
-
declare type Judge = () => boolean;
|
|
3
|
-
declare type Connect = (url: string, version?: number) => Promise<Adapter>;
|
|
4
|
-
export declare const addAdapter: (judge: Judge, creater: Connect, priority?: boolean) => void;
|
|
5
|
-
export declare const createClient: (options: Options) => Promise<ClientConntroller>;
|
|
6
|
-
export {};
|
package/lib/packet.d.ts
DELETED
|
@@ -1,35 +0,0 @@
|
|
|
1
|
-
import { PropertySign } from "./constant";
|
|
2
|
-
declare type WriteData = (data: string | number | number[] | Uint8Array) => void;
|
|
3
|
-
export declare const createPacket: (cmd: number, fixHeader?: number) => {
|
|
4
|
-
header: (data: number | number[] | Uint8Array, needLen?: boolean, isVariable?: boolean) => void;
|
|
5
|
-
payload: (data: string | number | number[] | Uint8Array, needLen?: boolean, isVariable?: boolean) => void;
|
|
6
|
-
cleanCache(): void;
|
|
7
|
-
cache: (data: string | number | number[] | Uint8Array, needLen?: boolean, isVariable?: boolean) => void;
|
|
8
|
-
putHeader(): void;
|
|
9
|
-
putPayload(): void;
|
|
10
|
-
getCache(): Uint8Array;
|
|
11
|
-
getPacket: () => Uint8Array;
|
|
12
|
-
};
|
|
13
|
-
export declare const writeString: (sign: PropertySign) => (v: string, write: WriteData) => void;
|
|
14
|
-
export declare const writePair: (sign: PropertySign) => (properies: Record<string, string | string[]>, write: WriteData) => void;
|
|
15
|
-
export declare const writeProperty: {
|
|
16
|
-
sessionExpiryInterval: (value: number, write: WriteData) => void;
|
|
17
|
-
receiveMaximum: (value: number, write: WriteData) => void;
|
|
18
|
-
maximumPacketSize: (value: number, write: WriteData) => void;
|
|
19
|
-
topicAliasMaximum: (value: number, write: WriteData) => void;
|
|
20
|
-
topicAlias: (value: number, write: WriteData) => void;
|
|
21
|
-
requestResponseInformation: (value: boolean, write: WriteData) => void;
|
|
22
|
-
requestProblemInformation: (value: boolean, write: WriteData) => void;
|
|
23
|
-
userProperties: (properies: Record<string, string | string[]>, write: WriteData) => void;
|
|
24
|
-
authenticationMethod: (v: string, write: WriteData) => void;
|
|
25
|
-
authenticationData: (value: Uint8Array, write: WriteData) => void;
|
|
26
|
-
willDelayInterval: (value: number, write: WriteData) => void;
|
|
27
|
-
payloadFormatIndicator: (value: boolean, write: WriteData) => void;
|
|
28
|
-
messageExpiryInterval: (value: number, write: WriteData) => void;
|
|
29
|
-
contentType: (v: string, write: WriteData) => void;
|
|
30
|
-
responseTopic: (v: string, write: WriteData) => void;
|
|
31
|
-
correlationData: (value: Uint8Array, write: WriteData) => void;
|
|
32
|
-
subscriptionIdentifier: (value: number, write: WriteData) => void;
|
|
33
|
-
};
|
|
34
|
-
export declare const packetProperties: (properies: any, write: WriteData) => void;
|
|
35
|
-
export {};
|
package/lib/parse.d.ts
DELETED
|
@@ -1,24 +0,0 @@
|
|
|
1
|
-
import { AuthOptions, ClientConntroller, Message, PuplishResponse } from "./interface";
|
|
2
|
-
export declare const parseProperty: {
|
|
3
|
-
sessionExpiryInterval: (data: Uint8Array, offset: number) => number[];
|
|
4
|
-
receiveMaximum: (data: Uint8Array, offset: number) => number[];
|
|
5
|
-
maximumPacketSize: (data: Uint8Array, offset: number) => number[];
|
|
6
|
-
topicAliasMaximum: (data: Uint8Array, offset: number) => number[];
|
|
7
|
-
topicAlias: (data: Uint8Array, offset: number) => number[];
|
|
8
|
-
requestResponseInformation: (data: Uint8Array, offset: number) => (number | boolean)[];
|
|
9
|
-
requestProblemInformation: (data: Uint8Array, offset: number) => (number | boolean)[];
|
|
10
|
-
userProperties: (data: Uint8Array, offset: number) => [Array<string>, number];
|
|
11
|
-
authenticationMethod: (data: Uint8Array, offset: number) => [string, number];
|
|
12
|
-
authenticationData: (data: Uint8Array, offset: number) => [Uint8Array, number];
|
|
13
|
-
willDelayInterval: (data: Uint8Array, offset: number) => number[];
|
|
14
|
-
payloadFormatIndicator: (data: Uint8Array, offset: number) => (number | boolean)[];
|
|
15
|
-
messageExpiryInterval: (data: Uint8Array, offset: number) => number[];
|
|
16
|
-
contentType: (data: Uint8Array, offset: number) => [string, number];
|
|
17
|
-
responseTopic: (data: Uint8Array, offset: number) => [string, number];
|
|
18
|
-
correlationData: (data: Uint8Array, offset: number) => [Uint8Array, number];
|
|
19
|
-
subscriptionIdentifier: (data: Uint8Array, offset: number) => number[];
|
|
20
|
-
};
|
|
21
|
-
export declare const parseProperties: (data: Uint8Array) => Record<string, any>;
|
|
22
|
-
export declare const parseAuth: (data: Uint8Array) => AuthOptions;
|
|
23
|
-
export declare const parsePublish: (data: Uint8Array, client: ClientConntroller) => Message;
|
|
24
|
-
export declare const parsePublishResponse: (data: Uint8Array, client: ClientConntroller) => PuplishResponse;
|
package/lib/ping.d.ts
DELETED
package/lib/publish.d.ts
DELETED
|
@@ -1,6 +0,0 @@
|
|
|
1
|
-
import { ClientConntroller, Message, PuplishResponse } from "./interface";
|
|
2
|
-
export declare const publish: (client: ClientConntroller, message: Message) => Promise<void>;
|
|
3
|
-
export declare const puback: (client: ClientConntroller, message: PuplishResponse) => Promise<void>;
|
|
4
|
-
export declare const pubrel: (client: ClientConntroller, message: PuplishResponse) => Promise<void>;
|
|
5
|
-
export declare const pubrec: (client: ClientConntroller, message: PuplishResponse) => Promise<void>;
|
|
6
|
-
export declare const pubcomp: (client: ClientConntroller, message: PuplishResponse) => Promise<void>;
|
package/lib/response.d.ts
DELETED
package/lib/subscribe.d.ts
DELETED
|
@@ -1,31 +0,0 @@
|
|
|
1
|
-
import { ClientConntroller, UserProperties } from "./interface";
|
|
2
|
-
interface SubscribeOptions {
|
|
3
|
-
id: number;
|
|
4
|
-
properties?: {
|
|
5
|
-
subscriptionIdentifier: number;
|
|
6
|
-
userProperties?: UserProperties;
|
|
7
|
-
};
|
|
8
|
-
payload: {
|
|
9
|
-
topic: string;
|
|
10
|
-
qos?: number;
|
|
11
|
-
nl?: 0 | 1;
|
|
12
|
-
rap?: 0 | 1;
|
|
13
|
-
rh?: number;
|
|
14
|
-
}[];
|
|
15
|
-
}
|
|
16
|
-
interface UnSubscribeOptions {
|
|
17
|
-
id: number;
|
|
18
|
-
properties?: {
|
|
19
|
-
userProperties?: UserProperties;
|
|
20
|
-
};
|
|
21
|
-
topics: string[];
|
|
22
|
-
}
|
|
23
|
-
export declare const subscribe: (client: ClientConntroller, options: SubscribeOptions) => Promise<{
|
|
24
|
-
reasonCode: Uint8Array;
|
|
25
|
-
properties?: any;
|
|
26
|
-
}>;
|
|
27
|
-
export declare const unsubscribe: (client: ClientConntroller, subscribe: UnSubscribeOptions) => Promise<{
|
|
28
|
-
reasonCode: Uint8Array;
|
|
29
|
-
properties?: any;
|
|
30
|
-
}>;
|
|
31
|
-
export {};
|