qcloud-iotexplorer-appdev-sdk
Advanced tools
Comparing version 0.0.1 to 0.0.2
@@ -6,2 +6,6 @@ const { QcloudIotExplorerAppDevSdk } = require('./qcloud-iotexplorer-appdev-sdk'); | ||
onLaunch() { | ||
wx.cloud.init({ | ||
env: 'dev-c712j', | ||
}); | ||
this.sdk = new QcloudIotExplorerAppDevSdk({ | ||
@@ -25,12 +29,12 @@ debug: true, | ||
login() { | ||
return pify(wx.login)() | ||
.then(({ code }) => { | ||
return pify(wx.getUserInfo)({ withCredentials: true }) | ||
.then(userInfo => pify(wx.request)({ | ||
url: 'http://127.0.0.1:7788/api/login', | ||
method: 'POST', | ||
data: { code, ...userInfo }, | ||
})); | ||
}) | ||
.then(({ data: { code, data, msg } }) => { | ||
return pify(wx.getUserInfo)({ withCredentials: true }) | ||
.then(({ cloudID }) => wx.cloud.callFunction({ | ||
// 云函数名称 | ||
name: 'login', | ||
// 传给云函数的参数 | ||
data: { | ||
userInfo: wx.cloud.CloudID(cloudID), | ||
}, | ||
})) | ||
.then(({ result: { code, data, msg } }) => { | ||
if (code) { | ||
@@ -40,6 +44,2 @@ return Promise.reject({ code, msg }); | ||
if (data.Error) { | ||
return Promise.reject({ code: data.Error.Code, msg: data.Error.Message }); | ||
} | ||
return data; | ||
@@ -46,0 +46,0 @@ }); |
@@ -5,2 +5,3 @@ const pify = require('../../libs/pify'); | ||
const { getErrorMsg } = require('../../libs/utils'); | ||
const { ErrorCode } = require('../../qcloud-iotexplorer-appdev-sdk'); | ||
@@ -30,3 +31,3 @@ Page({ | ||
console.error(err); | ||
if (err.code === 'UserNeedAuth') { | ||
if (err.code === ErrorCode.GET_USERINFO_NEED_AUTH) { | ||
this.setData({ needAuth: true }); | ||
@@ -39,2 +40,3 @@ } | ||
if (!(detail && detail.errMsg && detail.errMsg.indexOf('auth deny') > -1)) { | ||
this.setData({ needAuth: false }); | ||
this.sdk.init() | ||
@@ -41,0 +43,0 @@ .then(() => this.getData()); |
@@ -1,1 +0,1 @@ | ||
!function(e,t){if("object"==typeof exports&&"object"==typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var r=t();for(var n in r)("object"==typeof exports?exports:e)[n]=r[n]}}(window,(function(){return function(e){var t={};function r(n){if(t[n])return t[n].exports;var o=t[n]={i:n,l:!1,exports:{}};return e[n].call(o.exports,o,o.exports,r),o.l=!0,o.exports}return r.m=e,r.c=t,r.d=function(e,t,n){r.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:n})},r.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},r.t=function(e,t){if(1&t&&(e=r(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var n=Object.create(null);if(r.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var o in e)r.d(n,o,function(t){return e[t]}.bind(null,o));return n},r.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return r.d(t,"a",t),t},r.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},r.p="",r(r.s=11)}([function(e,t,r){"use strict";r.r(t),r.d(t,"__extends",(function(){return o})),r.d(t,"__assign",(function(){return i})),r.d(t,"__rest",(function(){return s})),r.d(t,"__decorate",(function(){return a})),r.d(t,"__param",(function(){return u})),r.d(t,"__metadata",(function(){return c})),r.d(t,"__awaiter",(function(){return f})),r.d(t,"__generator",(function(){return d})),r.d(t,"__exportStar",(function(){return l})),r.d(t,"__values",(function(){return p})),r.d(t,"__read",(function(){return h})),r.d(t,"__spread",(function(){return _})),r.d(t,"__spreadArrays",(function(){return v})),r.d(t,"__await",(function(){return g})),r.d(t,"__asyncGenerator",(function(){return y})),r.d(t,"__asyncDelegator",(function(){return m})),r.d(t,"__asyncValues",(function(){return w})),r.d(t,"__makeTemplateObject",(function(){return b})),r.d(t,"__importStar",(function(){return E})),r.d(t,"__importDefault",(function(){return I}));var n=function(e,t){return(n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)};function o(e,t){function r(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}var i=function(){return(i=Object.assign||function(e){for(var t,r=1,n=arguments.length;r<n;r++)for(var o in t=arguments[r])Object.prototype.hasOwnProperty.call(t,o)&&(e[o]=t[o]);return e}).apply(this,arguments)};function s(e,t){var r={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(r[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var o=0;for(n=Object.getOwnPropertySymbols(e);o<n.length;o++)t.indexOf(n[o])<0&&Object.prototype.propertyIsEnumerable.call(e,n[o])&&(r[n[o]]=e[n[o]])}return r}function a(e,t,r,n){var o,i=arguments.length,s=i<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,r):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(o=e[a])&&(s=(i<3?o(s):i>3?o(t,r,s):o(t,r))||s);return i>3&&s&&Object.defineProperty(t,r,s),s}function u(e,t){return function(r,n){t(r,n,e)}}function c(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)}function f(e,t,r,n){return new(r||(r=Promise))((function(o,i){function s(e){try{u(n.next(e))}catch(e){i(e)}}function a(e){try{u(n.throw(e))}catch(e){i(e)}}function u(e){e.done?o(e.value):new r((function(t){t(e.value)})).then(s,a)}u((n=n.apply(e,t||[])).next())}))}function d(e,t){var r,n,o,i,s={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function a(i){return function(a){return function(i){if(r)throw new TypeError("Generator is already executing.");for(;s;)try{if(r=1,n&&(o=2&i[0]?n.return:i[0]?n.throw||((o=n.return)&&o.call(n),0):n.next)&&!(o=o.call(n,i[1])).done)return o;switch(n=0,o&&(i=[2&i[0],o.value]),i[0]){case 0:case 1:o=i;break;case 4:return s.label++,{value:i[1],done:!1};case 5:s.label++,n=i[1],i=[0];continue;case 7:i=s.ops.pop(),s.trys.pop();continue;default:if(!(o=(o=s.trys).length>0&&o[o.length-1])&&(6===i[0]||2===i[0])){s=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]<o[3])){s.label=i[1];break}if(6===i[0]&&s.label<o[1]){s.label=o[1],o=i;break}if(o&&s.label<o[2]){s.label=o[2],s.ops.push(i);break}o[2]&&s.ops.pop(),s.trys.pop();continue}i=t.call(e,s)}catch(e){i=[6,e],n=0}finally{r=o=0}if(5&i[0])throw i[1];return{value:i[0]?i[1]:void 0,done:!0}}([i,a])}}}function l(e,t){for(var r in e)t.hasOwnProperty(r)||(t[r]=e[r])}function p(e){var t="function"==typeof Symbol&&e[Symbol.iterator],r=0;return t?t.call(e):{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}}}function h(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var n,o,i=r.call(e),s=[];try{for(;(void 0===t||t-- >0)&&!(n=i.next()).done;)s.push(n.value)}catch(e){o={error:e}}finally{try{n&&!n.done&&(r=i.return)&&r.call(i)}finally{if(o)throw o.error}}return s}function _(){for(var e=[],t=0;t<arguments.length;t++)e=e.concat(h(arguments[t]));return e}function v(){for(var e=0,t=0,r=arguments.length;t<r;t++)e+=arguments[t].length;var n=Array(e),o=0;for(t=0;t<r;t++)for(var i=arguments[t],s=0,a=i.length;s<a;s++,o++)n[o]=i[s];return n}function g(e){return this instanceof g?(this.v=e,this):new g(e)}function y(e,t,r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n,o=r.apply(e,t||[]),i=[];return n={},s("next"),s("throw"),s("return"),n[Symbol.asyncIterator]=function(){return this},n;function s(e){o[e]&&(n[e]=function(t){return new Promise((function(r,n){i.push([e,t,r,n])>1||a(e,t)}))})}function a(e,t){try{(r=o[e](t)).value instanceof g?Promise.resolve(r.value.v).then(u,c):f(i[0][2],r)}catch(e){f(i[0][3],e)}var r}function u(e){a("next",e)}function c(e){a("throw",e)}function f(e,t){e(t),i.shift(),i.length&&a(i[0][0],i[0][1])}}function m(e){var t,r;return t={},n("next"),n("throw",(function(e){throw e})),n("return"),t[Symbol.iterator]=function(){return this},t;function n(n,o){t[n]=e[n]?function(t){return(r=!r)?{value:g(e[n](t)),done:"return"===n}:o?o(t):t}:o}}function w(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t,r=e[Symbol.asyncIterator];return r?r.call(e):(e=p(e),t={},n("next"),n("throw"),n("return"),t[Symbol.asyncIterator]=function(){return this},t);function n(r){t[r]=e[r]&&function(t){return new Promise((function(n,o){(function(e,t,r,n){Promise.resolve(n).then((function(t){e({value:t,done:r})}),t)})(n,o,(t=e[r](t)).done,t.value)}))}}}function b(e,t){return Object.defineProperty?Object.defineProperty(e,"raw",{value:t}):e.raw=t,e}function E(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t}function I(e){return e&&e.__esModule?e:{default:e}}},function(e,t,r){"use strict";var n,o,i,s=r(17),a="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-";function u(){i=!1}function c(e){if(e){if(e!==n){if(e.length!==a.length)throw new Error("Custom alphabet for shortid must be "+a.length+" unique characters. You submitted "+e.length+" characters: "+e);var t=e.split("").filter((function(e,t,r){return t!==r.lastIndexOf(e)}));if(t.length)throw new Error("Custom alphabet for shortid must be "+a.length+" unique characters. These characters were not unique: "+t.join(", "));n=e,u()}}else n!==a&&(n=a,u())}function f(){return i||(i=function(){n||c(a);for(var e,t=n.split(""),r=[],o=s.nextValue();t.length>0;)o=s.nextValue(),e=Math.floor(o*t.length),r.push(t.splice(e,1)[0]);return r.join("")}())}e.exports={get:function(){return n||a},characters:function(e){return c(e),n},seed:function(e){s.seed(e),o!==e&&(u(),o=e)},lookup:function(e){return f()[e]},shuffled:f}},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(0).__importDefault(r(10));t.appendParams=function(e,t){void 0===t&&(t={});var r=[];return Object.keys(t).forEach((function(e){var o=t[e];void 0!==o&&(n.default(o)&&(o=JSON.stringify(o)),r.push(e+"="+encodeURIComponent(o)))})),r.length?(e.indexOf("?")>-1?e+"&":e+"?")+r.join("&"):e},t.delay=function(e){return new Promise((function(t){return setTimeout(t,e)}))},t.genPromise=function(){var e,t;return{promise:new Promise((function(r,n){e=r,t=n})),resolve:e,reject:t}},t.noop=function(){},t.getErrorMsg=function(e){if(e){var t="";return"string"==typeof e?e:(t=e.msg||e.Message||e.message||e.errMsg||"连接服务器失败,请稍后再试",e.reqId&&(t+="("+e.reqId+")"),t||(t="连接服务器失败,请稍后再试"),t)}}},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(0);t.LogLevel={log:"log",debug:"log",info:"info",warn:"warn",error:"error"};var o={debug:!1},i=function(e){for(var r=[],i=1;i<arguments.length;i++)r[i-1]=arguments[i];e in t.LogLevel||(e=t.LogLevel.debug),o.debug&&console[t.LogLevel[e]].apply(console,n.__spread(r))};t.default={config:function(e){return void 0===e&&(e={}),Object.assign(o,e)},info:function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return i.apply(void 0,n.__spread(["info"],e))},debug:function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return i.apply(void 0,n.__spread(["debug"],e))},warn:function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return i.apply(void 0,n.__spread(["warn"],e))},error:function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return i.apply(void 0,n.__spread(["error"],e))}}},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=Object.defineProperty,o=Object.create,i=Object.prototype.hasOwnProperty,s={configurable:!0,enumerable:!1,writable:!0,value:null};function a(e){if("function"!=typeof e)throw new TypeError(e+" is not a function");return e}var u=function(){function e(){}return e.prototype.on=function(e,t){var r;return a(t),i.call(this,"__ee__")?r=this.__ee__:(r=s.value=o(null),n(this,"__ee__",s),s.value=null),r[e]?r[e].push(t):r[e]=[t],this},e.prototype.once=function(e,t){var r,n=this;return a(t),this.on.call(this,e,r=function(){for(var o=[],i=0;i<arguments.length;i++)o[i]=arguments[i];n.off.call(void 0,e,r),t.apply(n,o)}),this},e.prototype.off=function(e,t){if(!i.call(this,"__ee__"))return this;var r=this.__ee__;if(!r[e])return this;if(t){var n=r[e]||[],o=n.indexOf(t);o>-1&&n.splice(o,1)}else r[e].length=0;return this},e.prototype.emit=function(e){for(var t=this,r=[],n=1;n<arguments.length;n++)r[n-1]=arguments[n];if(i.call(this,"__ee__")){var o=this.__ee__[e];o&&o.length&&o.forEach((function(e){return e.apply(t,r)}))}},e}();t.default=u},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(0);t.pify=function(e,t){return void 0===t&&(t=wx),function(r){for(var o=[],i=1;i<arguments.length;i++)o[i-1]=arguments[i];return new Promise((function(i,s){e?e.call.apply(e,n.__spread([t,n.__assign(n.__assign({},r),{success:i,fail:s})],o)):wx.showModal({title:"提示",content:"当前微信版本过低,无法使用该功能,请升级到最新微信版本后重试",complete:function(){return s()},confirmColor:"#006eff",showCancel:!1})}))}}},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(0);t.normalizeError=function(e){return e&&(e.errMsg&&["auth deny","scope unauthorized"].some((function(t){return String(e.errMsg).indexOf(t)>-1}))?Object.assign(e,{code:"UserNeedAuth",msg:"尚未开启微信基本信息授权,请授权后使用"}):t.isVerifyLoginError(e)&&(e=t.genVerifyLoginFailError(e))),e},t.genVerifyLoginFailError=function(e){e||(e={});e.code,e.msg;var t=e.reqId,r=n.__rest(e,["code","msg","reqId"]);return n.__assign({code:"VERIFY_LOGIN_FAILED",msg:"登录态验证失败,请重新登录",reqId:t},r)},t.isVerifyLoginError=function(e){return e&&(e.code||"").indexOf("InvalidAccessToken")>-1},t.handleVerifyLoginError=function(e){if(t.isVerifyLoginError(e))throw t.genVerifyLoginFailError(e)}},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(0);n.__exportStar(r(8),t),n.__exportStar(r(16),t)},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(0),o=n.__importDefault(r(15)),i=r(5),s=0;t.request=function(e){return n.__awaiter(void 0,void 0,void 0,(function(){var t,r=e.url,a=e.data,u=e.header,c=void 0===u?{}:u,f=e.method,d=void 0===f?"get":f,l=e.dataType,p=e.responseType,h=n.__rest(e,["url","data","header","method","dataType","responseType"]);return n.__generator(this,(function(e){switch(e.label){case 0:e.trys.push([0,5,6,7]),e.label=1;case 1:return s>=10?[4,o.default.startBlocking()]:[3,3];case 2:return e.sent(),[3,1];case 3:return s++,[4,i.pify(wx.request)(n.__assign({url:r,data:a,header:c,method:d,dataType:l,responseType:p},h))];case 4:return[2,e.sent()];case 5:return t=e.sent(),[2,Promise.reject(t)];case 6:return s--,o.default.resolveFirstBlock(),[7];case 7:return[2]}}))}))}},function(e,t,r){"use strict";var n=r(1),o=r(18),i=r(22),s=r(23)||0;function a(){return o(s)}e.exports=a,e.exports.generate=a,e.exports.seed=function(t){return n.seed(t),e.exports},e.exports.worker=function(t){return s=t,e.exports},e.exports.characters=function(e){return void 0!==e&&n.characters(e),n.shuffled()},e.exports.isValid=i},function(e,t,r){"use strict";function n(e){return!0==(null!=(t=e)&&"object"==typeof t&&!1===Array.isArray(t))&&"[object Object]"===Object.prototype.toString.call(e);var t}function o(e){var t,r;return!1!==n(e)&&("function"==typeof(t=e.constructor)&&(!1!==n(r=t.prototype)&&!1!==r.hasOwnProperty("isPrototypeOf")))}r.r(t),r.d(t,"default",(function(){return o}))},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(0);r(12),n.__exportStar(r(13),t)},function(e,t){},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(0),o=r(14),i=n.__importDefault(r(4)),s=r(25),a=n.__importDefault(r(3)),u=r(29),c=r(30),f=r(2),d=r(7),l=r(6),p=r(31),h=function(e){function t(t){var r=t.getAccessToken,i=void 0===r?f.noop:r,u=t.appKey,d=void 0===u?"":u,l=t.apiPlatform,p=void 0===l?"":l,h=t.debug,_=void 0!==h&&h,v=t.wsConfig,g=void 0===v?{}:v,y=g.autoReconnect,m=void 0===y||y,w=g.disconnectWhenAppHide,b=void 0===w||w,E=g.connectWhenAppShow,I=void 0===E||E,P=n.__rest(g,["autoReconnect","disconnectWhenAppHide","connectWhenAppShow"]),S=e.call(this)||this;return S.isManuallyClose=!1,S._defaultFamilyIdPromise=null,a.default.config({debug:_}),S.ws=new s.IotWebsocket(S,n.__assign(n.__assign({},P),{apiPlatform:p})),S.loginManager=new o.LoginManager(S,{getAccessToken:i,appKey:d}),S._apiPlatform=p,S.ws.on("error",(function(e){a.default.debug("websocket error",e),S.emit(c.EventTypes.wsError,e),m&&S._reconnectWs()})),S.ws.on("close",(function(e){var t=void 0===e?{}:e,r=t.code,n=t.reason;a.default.debug("websocket close",{code:r,reason:n}),S.emit(c.EventTypes.wsClose,{code:r,reason:n}),m&&S._onWebsocketClose()})),S.ws.on("push",(function(e){return S._handlePushEvent(e)})),wx.onAppHide((function(){b&&(S.isManuallyClose=!0,S.ws.disconnect())})),wx.onAppShow((function(){I&&S.isLogin&&S.ws.connect()})),S}return n.__extends(t,e),Object.defineProperty(t.prototype,"userInfo",{get:function(){return this.loginManager.userInfo},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"isLogin",{get:function(){return this.loginManager.isLogin},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"userId",{get:function(){return this.loginManager.userId},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"nickName",{get:function(){return this.loginManager.nickName},enumerable:!0,configurable:!0}),t.prototype.init=function(e){return void 0===e&&(e=!1),n.__awaiter(this,void 0,void 0,(function(){var t=this;return n.__generator(this,(function(r){return e&&(this._initPromise=null),[2,this._initPromise||(this._initPromise=new Promise((function(e,r){return n.__awaiter(t,void 0,void 0,(function(){var t;return n.__generator(this,(function(n){switch(n.label){case 0:return n.trys.push([0,3,,4]),[4,this.loginManager.login()];case 1:return n.sent(),[4,this.ws.connect()];case 2:return n.sent(),e(),[3,4];case 3:return t=n.sent(),r(l.normalizeError(t)),this._initPromise=null,[3,4];case 4:return[2]}}))}))})))]}))}))},t.prototype.getDefaultFamilyId=function(){var e=this;return this._defaultFamilyIdPromise||(this._defaultFamilyIdPromise=new Promise((function(t,r){return n.__awaiter(e,void 0,void 0,(function(){var e,o,i,s;return n.__generator(this,(function(n){switch(n.label){case 0:return n.trys.push([0,4,,5]),[4,this.requestApi("AppGetFamilyList",{Offset:0,Limit:100})];case 1:return e=n.sent(),o=e.FamilyList,e.Total?[3,3]:[4,this.requestApi("AppCreateFamily",{Name:this.loginManager.nickName})];case 2:return i=n.sent().Data.FamilyId,[2,t(i)];case 3:return t(o[0].FamilyId),[3,5];case 4:return s=n.sent(),r(s),this._defaultFamilyIdPromise=null,[3,5];case 5:return[2]}}))}))})))},t.prototype.sendWebsocketMessage=function(e,t,r){void 0===t&&(t={});var o=(void 0===r?{}:r).reqId;return n.__awaiter(this,void 0,void 0,(function(){return n.__generator(this,(function(r){switch(r.label){case 0:return[4,this.init()];case 1:return r.sent(),[2,this.ws.send(e,t,{reqId:o})]}}))}))},t.prototype.connectWebsocket=function(){return n.__awaiter(this,void 0,void 0,(function(){return n.__generator(this,(function(e){switch(e.label){case 0:return[4,this.init()];case 1:return e.sent(),[4,this.ws.connect()];case 2:return e.sent(),[2]}}))}))},t.prototype.disconnectWebsocket=function(){this.ws.disconnect()},t.prototype.subscribeDevices=function(e){return void 0===e&&(e=[]),n.__awaiter(this,void 0,void 0,(function(){return n.__generator(this,(function(t){return this.ws.subscribe(e.map((function(e){return"string"==typeof e?e:e&&e.DeviceId?e.DeviceId:void 0})).filter(Boolean)),[2]}))}))},t.prototype.requestApi=function(e,t,r){void 0===t&&(t={}),void 0===r&&(r={});var o=r.doNotRetry,i=void 0!==o&&o,s=r.needLogin,u=void 0===s||s,c=n.__rest(r,["doNotRetry","needLogin"]);return n.__awaiter(this,void 0,void 0,(function(){var r,o,s,f,p,h,_;return n.__generator(this,(function(v){switch(v.label){case 0:return v.trys.push([0,6,,13]),u?[4,this.loginManager.checkLogin()]:[3,2];case 1:v.sent(),v.label=2;case 2:return r=this.loginManager,o=r.accessToken,s=r.userId,t&&"default"===t.FamilyId?(f=t,[4,this.getDefaultFamilyId()]):[3,4];case 3:f.FamilyId=v.sent(),v.label=4;case 4:return p=n.__assign({uin:s},t),o&&(p.AccessToken=o),this._apiPlatform&&(p.Platform=this._apiPlatform),[4,d.requestTokenApi(e,p,c)];case 5:return[2,v.sent()];case 6:if(h=v.sent(),a.default.debug("requestApi fail",h),!l.isVerifyLoginError(h))return[3,12];if(i)return[3,11];v.label=7;case 7:return v.trys.push([7,9,,10]),[4,this.loginManager.reLogin()];case 8:return v.sent(),[3,10];case 9:return _=v.sent(),a.default.error("reLogin fail",_),[2,Promise.reject(l.genVerifyLoginFailError(h))];case 10:return[2,this.requestApi(e,t,n.__assign({doNotRetry:!0},c))];case 11:return[2,Promise.reject(l.genVerifyLoginFailError(h))];case 12:return[2,Promise.reject(l.normalizeError(h))];case 13:return[2]}}))}))},t.prototype.connectSoftAp=function(e){return p.connectSoftAp(this,e)},t.prototype._handlePushEvent=function(e){e||(e={}),this.emit(c.EventTypes.wsPush,e);var t=e.action,r=e.params;r||(r={}),a.default.debug("actions updateDeviceDataByPush",e);var n=r.DeviceId,o=r.Type,i=r.SubType,s=r.Payload,f=r.Time,d=new Date(f).getTime();switch(t){case"DeviceChange":switch(o){case"Property":case"Shadow":case"Template":switch(i){case"Report":var l={};try{var p=JSON.parse(u.decodeBase64(s));if(a.default.debug("actions updateDeviceData payload",p),p){var h=p.type,_=p.state,v=p.method,g=p.params;if(h&&"update"===h&&_&&_.reported&&(v="report",g=_.reported),g||(g={}),"report"===v)for(var y in g)l[y]={Value:g[y],lastUpdate:d}}}catch(e){a.default.error("handle report event error",e)}this.emit(c.EventTypes.wsReport,{deviceId:n,deviceData:l});break;case"Push":l={};try{if(s){h=s.type,p=s.payload,v=s.method,g=s.params;if(h&&"delta"===h&&p&&p.state&&(v="control",g=p.state),"control"===v&&g){for(var y in g)l[y]={Value:g[y],LastUpdate:d};this.emit(c.EventTypes.wsControl,{deviceId:n,deviceData:l})}}}catch(e){a.default.error(e)}}break;case"StatusChange":var m="Online"===i?1:0;this.emit(c.EventTypes.wsStatusChange,{deviceId:n,deviceStatus:m})}}},t.prototype._onWebsocketClose=function(){if(!this.isManuallyClose)return this._reconnectWs();this.isManuallyClose=!1},t.prototype._reconnectWs=function(){return n.__awaiter(this,void 0,void 0,(function(){var e;return n.__generator(this,(function(t){switch(t.label){case 0:return t.trys.push([0,3,,4]),a.default.debug("websocket reconnecting in 2 seconds"),[4,f.delay(2e3)];case 1:return t.sent(),[4,this.ws.connect()];case 2:return t.sent(),[3,4];case 3:return e=t.sent(),a.default.error("error when reconnect ws",e),[2,Promise.reject(e)];case 4:return[2]}}))}))},t.EventTypes=c.EventTypes,t}(i.default);t.QcloudIotExplorerAppDevSdk=h},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(0),o=n.__importDefault(r(4)),i=r(7),s=n.__importDefault(r(24)),a=r(6),u=n.__importDefault(r(3)),c="__qcloud-iotexplorer-appdev-sdk-accessToken",f=function(e){function t(t,r){var n=r.getAccessToken,o=r.appKey,i=e.call(this)||this;return i.accessToken="",i.appKey="",i.isLogin=!1,i.userInfo=null,i.sdk=t,i.getAccessToken=n,i.appKey=o,i}return n.__extends(t,e),t.prototype.login=function(){return n.__awaiter(this,void 0,void 0,(function(){var e,t,r,o,f;return n.__generator(this,(function(n){switch(n.label){case 0:e=!1,n.label=1;case 1:return n.trys.push([1,7,,10]),[4,s.default.getItem(c)];case 2:return(t=n.sent())?[3,4]:[4,this.getAccessToken()];case 3:return r=n.sent().Token,t=r,[3,5];case 4:e=!0,n.label=5;case 5:return[4,i.requestTokenApi("AppGetUser",{AccessToken:t})];case 6:return o=n.sent().Data,s.default.setItem(c,t),this.accessToken=t,this.userInfo=o,this.isLogin=!0,[3,10];case 7:return f=n.sent(),a.isVerifyLoginError(f)?[4,this.logout()]:[3,9];case 8:if(n.sent(),e)return u.default.debug("Cached Token expired, retrying..."),[2,this.login()];n.label=9;case 9:return[2,Promise.reject(f)];case 10:return[2]}}))}))},Object.defineProperty(t.prototype,"userId",{get:function(){return this.userInfo?this.userInfo.UserID:""},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"nickName",{get:function(){return this.userInfo?this.userInfo.NickName:""},enumerable:!0,configurable:!0}),t.prototype.checkLogin=function(){if(!this.isLogin)throw a.genVerifyLoginFailError()},t.prototype.logout=function(){return n.__awaiter(this,void 0,void 0,(function(){return n.__generator(this,(function(e){switch(e.label){case 0:return[4,s.default.removeItem(c)];case 1:return e.sent(),this.accessToken="",this.isLogin=!1,[2]}}))}))},t.prototype.reLogin=function(){return n.__awaiter(this,void 0,void 0,(function(){return n.__generator(this,(function(e){switch(e.label){case 0:return[4,this.logout()];case 1:return e.sent(),[4,this.login()];case 2:return e.sent(),[2]}}))}))},t}(o.default);t.LoginManager=f},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=[];t.default={resolveFirstBlock:function(){n.length&&(n[0].resolve(),n.shift())},startBlocking:function(){var e,t=new Promise((function(t){e=t}));return n.push({promise:t,resolve:e}),t}}},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(0),o=n.__importDefault(r(9)),i=r(2),s=r(8);t.requestTokenApi=function(e,t,r){return void 0===t&&(t={}),void 0===r&&(r={}),n.__awaiter(void 0,void 0,void 0,(function(){var a,u,c,f,d,l,p,h,_,v=t.uin,g=t.AccessToken,y=n.__rest(t,["uin","AccessToken"]),m=r.method,w=void 0===m?"POST":m,b=n.__rest(r,["method"]);return n.__generator(this,(function(t){switch(t.label){case 0:return u=o.default(),c={uin:v,cmd:e},y=Object.assign({},y,{Action:e,RequestId:u,AccessToken:g}),f=i.appendParams(b.url||"https://iot.cloud.tencent.com/api/exploreropen/tokenapi",c),a=n.__assign({url:f,data:y,method:w},b),[4,s.request(a)];case 1:if(d=t.sent().data,l=d.code,p=d.msg,h=d.data,_=void 0===h?{}:h,l){if(_){if(_.Error)throw{code:_.Error.Code,msg:_.Error.Message,reqId:u};throw{code:l,msg:p,reqId:u}}throw{code:l,msg:p}}return[2,_]}}))}))}},function(e,t,r){"use strict";var n=1;e.exports={nextValue:function(){return(n=(9301*n+49297)%233280)/233280},seed:function(e){n=e}}},function(e,t,r){"use strict";var n,o,i=r(19),s=(r(1),1459707606518),a=6;e.exports=function(e){var t="",r=Math.floor(.001*(Date.now()-s));return r===o?n++:(n=0,o=r),t+=i(a),t+=i(e),n>0&&(t+=i(n)),t+=i(r)}},function(e,t,r){"use strict";var n=r(1),o=r(20),i=r(21);e.exports=function(e){for(var t,r=0,s="";!t;)s+=i(o,n.get(),1),t=e<Math.pow(16,r+1),r++;return s}},function(e,t,r){"use strict";var n,o="object"==typeof window&&(window.crypto||window.msCrypto);n=o&&o.getRandomValues?function(e){return o.getRandomValues(new Uint8Array(e))}:function(e){for(var t=[],r=0;r<e;r++)t.push(Math.floor(256*Math.random()));return t},e.exports=n},function(e,t){e.exports=function(e,t,r){for(var n=(2<<Math.log(t.length-1)/Math.LN2)-1,o=Math.ceil(1.6*n*r/t.length),i="";;)for(var s=e(o),a=0;a<o;a++){var u=s[a]&n;if(t[u]&&(i+=t[u]).length===r)return i}}},function(e,t,r){"use strict";var n=r(1);e.exports=function(e){return!(!e||"string"!=typeof e||e.length<6)&&!new RegExp("[^"+n.get().replace(/[|\\{}()[\]^$+*?.-]/g,"\\$&")+"]").test(e)}},function(e,t,r){"use strict";e.exports=0},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(0),o=r(5);t.default={getItem:function(e){return n.__awaiter(this,void 0,void 0,(function(){return n.__generator(this,(function(t){switch(t.label){case 0:return t.trys.push([0,2,,3]),[4,o.pify(wx.getStorage)({key:e})];case 1:return[2,t.sent().data];case 2:return t.sent(),[2,null];case 3:return[2]}}))}))},setItem:function(e,t){return n.__awaiter(this,void 0,void 0,(function(){var r;return n.__generator(this,(function(n){switch(n.label){case 0:return n.trys.push([0,2,,3]),[4,o.pify(wx.setStorage)({key:e,data:t})];case 1:return n.sent(),[3,3];case 2:return r=n.sent(),console.error("setStorage error",r),[3,3];case 3:return[2]}}))}))},removeItem:function(e){return n.__awaiter(this,void 0,void 0,(function(){var t;return n.__generator(this,(function(r){switch(r.label){case 0:return r.trys.push([0,2,,3]),[4,o.pify(wx.removeStorage)({key:e})];case 1:return r.sent(),[3,3];case 2:return t=r.sent(),console.error("removeStorage error",t),[3,3];case 3:return[2]}}))}))}}},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(0),o=n.__importDefault(r(4)),i=n.__importDefault(r(9)),s=r(2),a=r(26),u=n.__importDefault(r(3)),c=n.__importDefault(r(10)),f=r(6),d={url:"wss://iot.cloud.tencent.com/ws/explorer",heartbeatInterval:6e4},l=function(e){function t(t,r){var n=e.call(this)||this;return n.sdk=t,n.requestHandlerMap=new Map,n.options=Object.assign({},d,r),n._connected=!1,n._subscribeDeviceIdList=[],n._heartBeatTimer=null,n}return n.__extends(t,e),t.prototype.isConnected=function(){return!!this._connected},t.prototype.doConnectWs=function(){return n.__awaiter(this,void 0,void 0,(function(){var e=this;return n.__generator(this,(function(t){return[2,this._doConnectWsPromise||(this._doConnectWsPromise=new Promise((function(t,r){return n.__awaiter(e,void 0,void 0,(function(){var e,o,i=this;return n.__generator(this,(function(c){e=function(e){r(e),i.emit("error",e),i.disconnect()};try{o=this.options.url,this.ws=new a.WebSocket(s.appendParams(o,{uin:this.sdk.loginManager.userId})),this.ws.onOpen((function(){u.default.debug("websocket connected"),i._connected=!0,i.emit("connect"),t()})),this.ws.onError(e),this.ws.onMessage((function(e){var t=e.data;i.emit("message",t);try{t=JSON.parse(t)}catch(e){return void u.default.warn("onMessage parse event.data error: "+t)}t.push?i.emit("push",t):void 0!==t.reqId&&i.requestHandlerMap.has(t.reqId)&&i.requestHandlerMap.get(t.reqId)(null,t)})),this.ws.onClose((function(e){return n.__awaiter(i,void 0,void 0,(function(){return n.__generator(this,(function(t){return u.default.debug("websocket closed"),this.disconnect(),this.emit("close",e),[2]}))}))}))}catch(t){e(t)}return[2]}))}))})))]}))}))},t.prototype.connect=function(){return n.__awaiter(this,void 0,void 0,(function(){return n.__generator(this,(function(e){switch(e.label){case 0:return[4,this.sdk.loginManager.checkLogin()];case 1:return e.sent(),this.isConnected()?[3,3]:[4,this.doConnectWs()];case 2:e.sent(),e.label=3;case 3:return[2,this.activePush()]}}))}))},t.prototype.subscribe=function(e){return this.activePush(e)},t.prototype.disconnect=function(){if(this.ws){this.ws.close({}),this._connected=!1,this._doConnectWsPromise=null,this.ws=null,clearInterval(this._heartBeatTimer),this._heartBeatTimer=null}},t.prototype.send=function(e,t,r){void 0===t&&(t={});var o=(void 0===r?{}:r).reqId;return n.__awaiter(this,void 0,void 0,(function(){var r=this;return n.__generator(this,(function(n){switch(n.label){case 0:if(o||(o=i.default()),!this.ws)return[3,5];this.ws.send({data:JSON.stringify({action:e,reqId:o,params:t})}),n.label=1;case 1:return n.trys.push([1,,3,4]),[4,Promise.race([new Promise((function(e,t){r.requestHandlerMap.set(o,(function(r,n){if(!r)return n.data||!n.error&&!n.error_message?e(n.data):t({code:n.error,msg:n.error_message});t(r)}))})),new Promise((function(e,t){setTimeout((function(){t({code:"TIMEOUT"})}),2e4)}))])];case 2:return[2,n.sent()];case 3:return this.requestHandlerMap.delete(o),[7];case 4:return[3,6];case 5:u.default.warn("Try send ws message but no ws instance",e,t),n.label=6;case 6:return[2]}}))}))},t.prototype.callYunApi=function(e,t,r){void 0===t&&(t={});var o=(void 0===r?{}:r).doNotRetry;return n.__awaiter(this,void 0,void 0,(function(){var r,s,a,d,l,p,h,_,v,g,y,m;return n.__generator(this,(function(n){switch(n.label){case 0:r=i.default(),s=this.sdk.loginManager,a=s.accessToken,d=s.appKey,(t=Object.assign({},t,{RequestId:r})).AccessToken=a,l={Action:e,ActionParams:t},this.options.apiPlatform?l.Platform=this.options.apiPlatform:l.AppKey=d,u.default.debug("yunapi start("+r+") => ",l),n.label=1;case 1:return n.trys.push([1,3,,11]),[4,this.send("YunApi",l,{reqId:r})];case 2:if(!(p=n.sent()))throw u.default.error("empty response",l),{msg:"连接服务器失败,请稍后重试"};if(!(h=p.Response))throw u.default.error("empty response",l,h),{msg:"连接服务器失败,请稍后重试"};if(_=h.Error,v=h.error,g=h.error_message,_)throw{code:_.Code,msg:_.Message};if(v)throw{code:v,msg:g};return u.default.debug("yunapi success("+r+") => ",l,h),[2,h];case 3:if(y=n.sent(),u.default.error("yunapi fail("+r+") => ",y),!f.isVerifyLoginError(y))return[3,10];if(o)return[3,8];n.label=4;case 4:return n.trys.push([4,6,,7]),[4,this.sdk.loginManager.reLogin()];case 5:return n.sent(),[3,7];case 6:return m=n.sent(),u.default.error("reLogin fail",m),[2,Promise.reject(f.genVerifyLoginFailError(y))];case 7:return[2,this.callYunApi(e,t,{doNotRetry:!0})];case 8:return[4,this.sdk.loginManager.logout()];case 9:return n.sent(),[2,f.genVerifyLoginFailError(y)];case 10:return c.default(y)&&(y.reqId=r),[2,Promise.reject(y)];case 11:return[2]}}))}))},t.prototype.sendWsHeatBeat=function(){if(this._subscribeDeviceIdList&&this._subscribeDeviceIdList.length)return this.callYunApi("AppDeviceTraceHeartBeat",{DeviceIds:this._subscribeDeviceIdList})},t.prototype.activePush=function(e){var t=this;e&&(this._subscribeDeviceIdList=e);var r=this.sdk.loginManager,n=r.isLogin,o=r.accessToken,i=r.appKey;n&&o&&this._subscribeDeviceIdList&&(this.send("ActivePush",{DeviceIds:this._subscribeDeviceIdList,AccessToken:o,AppKey:i}),this.sendWsHeatBeat(),clearInterval(this._heartBeatTimer),this._heartBeatTimer=setInterval((function(){return t.sendWsHeatBeat()}),this.options.heartbeatInterval))},t}(o.default);t.IotWebsocket=l},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(0).__importStar(r(27)),o=function(){function e(e){this.url=e,this.ws=null,this.initWs()}return e.prototype.initWs=function(){n.isMiniProgram?this.ws=wx.connectSocket({url:this.url}):this.ws=new e(this.url)},e.prototype.send=function(e){var t=e.data;n.isMiniProgram?this.ws.send({data:t}):this.ws.send(t)},e.prototype.close=function(e){var t=void 0===e?{}:e,r=t.code,o=t.reason;n.isMiniProgram?this.ws.close({code:r,reason:o}):this.ws.close(r,o)},e.prototype.onOpen=function(e){n.isMiniProgram?this.ws.onOpen(e):this.ws.addEventListener("open",e)},e.prototype.onClose=function(e){n.isMiniProgram?this.ws.onClose(e):this.ws.addEventListener("close",e)},e.prototype.onMessage=function(e){n.isMiniProgram?this.ws.onMessage(e):this.ws.addEventListener("message",e)},e.prototype.onError=function(e){n.isMiniProgram?this.ws.onError(e):this.ws.addEventListener("error",e)},e}();t.WebSocket=o},function(e,t,r){"use strict";(function(e){Object.defineProperty(t,"__esModule",{value:!0}),t.isMiniProgram=function(){try{return!!(wx&&wx.request&&wx.connectSocket)}catch(e){return!1}}(),t.isBrowser=function(){try{return"undefined"!=typeof window&&void 0!==window.document}catch(e){return!1}}(),t.isNode=function(){try{return!!e.versions.node}catch(e){return!1}}(),t.isRN=function(){try{return"ReactNative"===navigator.product}catch(e){return!1}}()}).call(this,r(28))},function(e,t){var r,n,o=e.exports={};function i(){throw new Error("setTimeout has not been defined")}function s(){throw new Error("clearTimeout has not been defined")}function a(e){if(r===setTimeout)return setTimeout(e,0);if((r===i||!r)&&setTimeout)return r=setTimeout,setTimeout(e,0);try{return r(e,0)}catch(t){try{return r.call(null,e,0)}catch(t){return r.call(this,e,0)}}}!function(){try{r="function"==typeof setTimeout?setTimeout:i}catch(e){r=i}try{n="function"==typeof clearTimeout?clearTimeout:s}catch(e){n=s}}();var u,c=[],f=!1,d=-1;function l(){f&&u&&(f=!1,u.length?c=u.concat(c):d=-1,c.length&&p())}function p(){if(!f){var e=a(l);f=!0;for(var t=c.length;t;){for(u=c,c=[];++d<t;)u&&u[d].run();d=-1,t=c.length}u=null,f=!1,function(e){if(n===clearTimeout)return clearTimeout(e);if((n===s||!n)&&clearTimeout)return n=clearTimeout,clearTimeout(e);try{n(e)}catch(t){try{return n.call(null,e)}catch(t){return n.call(this,e)}}}(e)}}function h(e,t){this.fun=e,this.array=t}function _(){}o.nextTick=function(e){var t=new Array(arguments.length-1);if(arguments.length>1)for(var r=1;r<arguments.length;r++)t[r-1]=arguments[r];c.push(new h(e,t)),1!==c.length||f||a(p)},h.prototype.run=function(){this.fun.apply(null,this.array)},o.title="browser",o.browser=!0,o.env={},o.argv=[],o.version="",o.versions={},o.on=_,o.addListener=_,o.once=_,o.off=_,o.removeListener=_,o.removeAllListeners=_,o.emit=_,o.prependListener=_,o.prependOnceListener=_,o.listeners=function(e){return[]},o.binding=function(e){throw new Error("process.binding is not supported")},o.cwd=function(){return"/"},o.chdir=function(e){throw new Error("process.chdir is not supported")},o.umask=function(){return 0}},function(e,t){const r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";t.encodeBase64=e=>{if(!e)return!1;let t,n,o,i,s,a,u,c="",f=0;do{t=e.charCodeAt(f++),n=e.charCodeAt(f++),o=e.charCodeAt(f++),i=t>>2,s=(3&t)<<4|n>>4,a=(15&n)<<2|o>>6,u=63&o,isNaN(n)?a=u=64:isNaN(o)&&(u=64),c+=r.charAt(i)+r.charAt(s)+r.charAt(a)+r.charAt(u)}while(f<e.length);return c},t.decodeBase64=e=>{if(!e)return!1;e=e.replace(/[^A-Za-z0-9\+\/\=]/g,"");let t,n,o,i,s="",a=0;do{t=r.indexOf(e.charAt(a++)),n=r.indexOf(e.charAt(a++)),o=r.indexOf(e.charAt(a++)),i=r.indexOf(e.charAt(a++)),s+=String.fromCharCode(t<<2|n>>4),64!=o&&(s+=String.fromCharCode((15&n)<<4|o>>2)),64!=i&&(s+=String.fromCharCode((3&o)<<6|i))}while(a<e.length);return s}},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e){e.ready="ready",e.error="error",e.wsError="ws_error",e.wsClose="ws_close",e.wsPush="wsPush",e.wsReport="wsReport",e.wsControl="wsControl",e.wsStatusChange="wsStatusChange"}(t.EventTypes||(t.EventTypes={}))},function(e,t,r){"use strict";var n;Object.defineProperty(t,"__esModule",{value:!0});var o=r(0),i=r(2),s=r(5),a=o.__importDefault(r(3));t.SoftApErrorCodes={UDP_NOT_RESPONSED:"UDP_NOT_RESPONSED",SSID_NOT_MATCH:"SSID_NOT_MATCH",CONNECT_SOFTAP_FAIL:"CONNECT_SOFTAP_FAIL",CONNECT_WIFI_FAIL:"CONNECT_WIFI_FAIL",UDP_ERROR:"UDP_ERROR",UDP_CLOSED:"UDP_CLOSED",DEVICE_ERROR:"DEVICE_ERROR",INVALID_RESPONSE:"INVALID_RESPONSE",DEVICE_CONNECT_MQTT_FAIL:"DEVICE_CONNECT_MQTT_FAIL",DEVICE_CONNECT_WIFI_FAIL:"DEVICE_CONNECT_WIFI_FAIL",ADD_DEVICE_FAIL:"ADD_DEVICE_FAIL",SEND_UDP_MSG_FAIL:"SEND_UDP_MSG_FAIL"},t.SoftApErrorMsgs=((n={})[t.SoftApErrorCodes.UDP_NOT_RESPONSED]="超时未收到设备响应",n[t.SoftApErrorCodes.CONNECT_SOFTAP_FAIL]="手机连接设备热点失败",n[t.SoftApErrorCodes.CONNECT_WIFI_FAIL]="手机连接WiFi路由器失败",n[t.SoftApErrorCodes.UDP_ERROR]="连接设备失败",n[t.SoftApErrorCodes.UDP_CLOSED]="连接设备中断",n[t.SoftApErrorCodes.DEVICE_ERROR]="设备配网异常",n[t.SoftApErrorCodes.INVALID_RESPONSE]="设备响应报文格式错误",n[t.SoftApErrorCodes.DEVICE_CONNECT_MQTT_FAIL]="连接云端失败",n[t.SoftApErrorCodes.DEVICE_CONNECT_WIFI_FAIL]="设备连接WiFi路由器失败",n[t.SoftApErrorCodes.ADD_DEVICE_FAIL]="添加设备失败",n[t.SoftApErrorCodes.SEND_UDP_MSG_FAIL]="发送配网消息失败",n),t.SoftApStepCodes={};var u=function(e){var t=new Uint8Array(e),r=String.fromCharCode.apply(null,t);return decodeURIComponent(escape(r))},c=["手机与设备连接成功","向设备发送信息成功","设备连接云端成功","初始化成功"],f=function(e,t,r){return void 0===t&&(t=""),void 0===r&&(r={}),o.__awaiter(void 0,void 0,void 0,(function(){return o.__generator(this,(function(n){switch(n.label){case 0:return wx.hideToast(),[4,s.pify(wx.showModal)(o.__assign({title:e,content:t},r)).then((function(e){return!!e.confirm})).catch((function(){return!1}))];case 1:return[2,n.sent()]}}))}))};t.connectSoftAp=function(e,r){var n=r.targetWifiInfo,d=r.softApInfo,l=r.familyId,p=void 0===l?"default":l,h=r.udpAddress,_=void 0===h?"192.168.4.1":h,v=r.udpPort,g=void 0===v?8266:v,y=r.waitUdpResponseDuration,m=void 0===y?2e3:y,w=r.udpCommunicationRetryTime,b=void 0===w?5:w,E=r.stepDurationGap,I=void 0===E?3e3:E,P=r.onProgress,S=void 0===P?i.noop:P,C=r.onError,A=void 0===C?i.noop:C,O=r.onComplete,T=void 0===O?i.noop:O;return o.__awaiter(this,void 0,void 0,(function(){var r,l,h,v,y,w,E,P,C,O=this;return o.__generator(this,(function(D){switch(D.label){case 0:return D.trys.push([0,7,,8]),l=function(e){a.default.debug("softap-receive-unhandled-msg",{data:{message:e}})},h=function(e){var t=e.step,r=e.data,n=void 0===r?{}:r;S({step:t,msg:c[t-1],data:n})},v=function(e){"string"!=typeof e&&(e=JSON.stringify(e)),console.log("udpInstance.send",{address:_,port:g,message:e}),r.send({address:_,port:g,message:e})},y=function(e){return o.__awaiter(O,void 0,void 0,(function(){var r=this;return o.__generator(this,(function(n){return[2,new Promise((function(n,s){return o.__awaiter(r,void 0,void 0,(function(){var r,u,c,f;return o.__generator(this,(function(o){switch(o.label){case 0:o.trys.push([0,4,,5]),r=!0,u=0,l=function(e){try{r=!1,n(e)}catch(e){s(e)}},(c=function(){u++,a.default.debug("softap-udp-send-msg",{data:{msg:e,retryCount:u}}),v(e)})(),o.label=1;case 1:return r&&u<=b?[4,i.delay(m)]:[3,3];case 2:return o.sent(),r?(c(),[3,1]):[2];case 3:return s({code:t.SoftApErrorCodes.UDP_NOT_RESPONSED}),[3,5];case 4:return f=o.sent(),s({code:t.SoftApErrorCodes.SEND_UDP_MSG_FAIL,detail:{error:f}}),[3,5];case 5:return[2]}}))}))}))]}))}))},w=function(e){var r=e.SSID,n=e.password;return o.__awaiter(O,void 0,void 0,(function(){return o.__generator(this,(function(e){switch(e.label){case 0:return[4,s.pify(wx.connectWifi)({SSID:r,password:n})];case 1:return e.sent(),[4,s.pify(wx.getConnectedWifi)()];case 2:if(e.sent().wifi.SSID!==r)throw{code:t.SoftApErrorCodes.SSID_NOT_MATCH};return a.default.debug("softap-connect-wifi-success"),[2]}}))}))},E=function(){return o.__awaiter(O,void 0,void 0,(function(){var s,c,d,_,v,g,m=this;return o.__generator(this,(function(b){switch(b.label){case 0:s=!1,b.label=1;case 1:return b.trys.push([1,3,,4]),a.default.debug("softap-connect-start"),(r=wx.createUDPSocket()).bind(),c=i.genPromise(),d=i.genPromise(),_=i.genPromise(),r.onError((function(e){return c.reject({code:t.SoftApErrorCodes.UDP_ERROR,detail:{errMsg:e}})})),r.onMessage((function(e){try{var r=JSON.parse(u(e.message));a.default.debug("softap-udp-on-message",{data:{message:r}}),2==+r.cmdType&&("Current_Error"===r.deviceReply?_.reject({code:t.SoftApErrorCodes.DEVICE_ERROR,detail:r}):"Previous_Error"===r.deviceReply?a.default.debug("softap-receive-prev-error",{data:{message:r}}):l(r))}catch(e){a.default.debug("softap-udp-parse-message-error",{error:e})}})),v=function(){return o.__awaiter(m,void 0,void 0,(function(){var u,c,d,l,_,v,g,m,b,E=this;return o.__generator(this,(function(P){switch(P.label){case 0:return[4,(u=function(e){return void 0===e&&(e=I),o.__awaiter(E,void 0,void 0,(function(){return o.__generator(this,(function(t){switch(t.label){case 0:return[4,i.delay(e)];case 1:if(t.sent(),s)throw a.default.debug("connection aborted"),null;return[2]}}))}))})()];case 1:return P.sent(),a.default.debug("softap-create-udp-connection-success"),h({step:1}),a.default.debug("softap-send-target-wifi-start"),[4,y({cmdType:1,ssid:n.SSID,password:n.password})];case 2:if(c=P.sent(),a.default.debug("softap-send-target-wifi-success",{data:c}),"dataRecived"!==c.deviceReply)throw{code:t.SoftApErrorCodes.INVALID_RESPONSE,detail:c};return[4,u(5e3)];case 3:return P.sent(),h({step:2,data:c}),a.default.debug("softap-send-timestamp-start"),[4,y({cmdType:0,timestamp:parseInt(String(Date.now()/1e3))})];case 4:if(d=P.sent(),l=d.mqttState,_=d.wifiState,v=o.__rest(d,["mqttState","wifiState"]),"connected"!==l)throw{code:t.SoftApErrorCodes.DEVICE_CONNECT_MQTT_FAIL};if("connected"!==_)throw{code:t.SoftApErrorCodes.DEVICE_CONNECT_WIFI_FAIL};return a.default.debug("softap-send-timestamp-success",{data:v}),r.close(),[4,u()];case 5:P.sent(),h({step:3,data:o.__assign({mqttState:l,wifiState:_},v)}),a.default.debug("softap-reconnect-wifi-start"),P.label=6;case 6:return P.trys.push([6,8,,10]),[4,w(n)];case 7:return P.sent(),[3,10];case 8:return g=P.sent(),[4,f("手机连接路由Wi-Fi失败,请将手机手动切换到能够正常访问的网络环境后继续配网操作","",{confirmText:"继续",confirmColor:"#0052d9",cancelText:"取消",cancelColor:"#ff584c"})];case 9:if(!P.sent())throw{code:t.SoftApErrorCodes.CONNECT_WIFI_FAIL,detail:{error:g}};return[3,10];case 10:return a.default.debug("softap-reconnect-wifi-success"),[4,u()];case 11:return P.sent(),a.default.debug("softap-add-device-start",{data:{Signature:v.signature,DeviceTimestamp:v.timestamp,ProductId:v.productId,DeviceName:v.deviceName,ConnId:v.connId}}),[4,(m=function(){return o.__awaiter(E,void 0,void 0,(function(){var r;return o.__generator(this,(function(n){switch(n.label){case 0:return n.trys.push([0,2,,7]),[4,e.requestApi("AppSigBindDeviceInFamily",{Signature:v.signature,DeviceTimestamp:v.timestamp,ProductId:v.productId,DeviceName:v.deviceName,ConnId:v.connId,FamilyId:p||"default"})];case 1:return[2,n.sent()];case 2:return(r=n.sent())?r.errMsg&&/request:fail/.test(r.errMsg)?[4,f("手机切换到该网络环境后依然无法正常上网访问,请继续切换网络重试或取消配网操作","",{confirmText:"重试",confirmColor:"#0052d9",cancelText:"取消",cancelColor:"#ff584c"})]:[3,4]:[3,6];case 3:return n.sent()?[2,m()]:[2,Promise.reject({code:t.SoftApErrorCodes.ADD_DEVICE_FAIL,detail:{error:r}})];case 4:return[4,f(i.getErrorMsg(r),"",{confirmText:"重试",confirmColor:"#0052d9",cancelText:"取消",cancelColor:"#ff584c"})];case 5:return n.sent()?[2,m()]:(r.code=t.SoftApErrorCodes.ADD_DEVICE_FAIL,[2,Promise.reject({code:t.SoftApErrorCodes.ADD_DEVICE_FAIL,detail:{error:r},msg:i.getErrorMsg(r),reqId:r.reqId})]);case 6:return[2,Promise.reject(r)];case 7:return[2]}}))}))})()];case 12:return b=P.sent(),a.default.debug("softap-connect-success"),h({step:4,data:b}),[2]}}))}))},[4,Promise.race([v(),c.promise,d.promise,_.promise])];case 2:return b.sent(),[3,4];case 3:return g=b.sent(),s=!0,a.default.debug("softap-connect-fail",{error:g}),g&&g.code in t.SoftApErrorCodes&&(g.msg=t.SoftApErrorMsgs[g.code]),[2,Promise.reject(g)];case 4:return[2]}}))}))},[4,s.pify(wx.startWifi)()];case 1:if(D.sent(),!d)return[3,5];D.label=2;case 2:return D.trys.push([2,4,,5]),[4,w(d)];case 3:return D.sent(),[3,5];case 4:if((P=D.sent()).code===t.SoftApErrorCodes.SSID_NOT_MATCH)throw{code:t.SoftApErrorCodes.CONNECT_SOFTAP_FAIL};throw P;case 5:return[4,E()];case 6:return D.sent(),T(),[3,8];case 7:return C=D.sent(),A(C),[3,8];case 8:return[2]}}))}))}}])})); | ||
!function(e,t){if("object"==typeof exports&&"object"==typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var r=t();for(var n in r)("object"==typeof exports?exports:e)[n]=r[n]}}(window,(function(){return function(e){var t={};function r(n){if(t[n])return t[n].exports;var o=t[n]={i:n,l:!1,exports:{}};return e[n].call(o.exports,o,o.exports,r),o.l=!0,o.exports}return r.m=e,r.c=t,r.d=function(e,t,n){r.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:n})},r.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},r.t=function(e,t){if(1&t&&(e=r(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var n=Object.create(null);if(r.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var o in e)r.d(n,o,function(t){return e[t]}.bind(null,o));return n},r.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return r.d(t,"a",t),t},r.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},r.p="",r(r.s=11)}([function(e,t,r){"use strict";r.r(t),r.d(t,"__extends",(function(){return o})),r.d(t,"__assign",(function(){return i})),r.d(t,"__rest",(function(){return s})),r.d(t,"__decorate",(function(){return a})),r.d(t,"__param",(function(){return c})),r.d(t,"__metadata",(function(){return u})),r.d(t,"__awaiter",(function(){return f})),r.d(t,"__generator",(function(){return l})),r.d(t,"__exportStar",(function(){return d})),r.d(t,"__values",(function(){return _})),r.d(t,"__read",(function(){return p})),r.d(t,"__spread",(function(){return h})),r.d(t,"__spreadArrays",(function(){return g})),r.d(t,"__await",(function(){return v})),r.d(t,"__asyncGenerator",(function(){return E})),r.d(t,"__asyncDelegator",(function(){return y})),r.d(t,"__asyncValues",(function(){return C})),r.d(t,"__makeTemplateObject",(function(){return m})),r.d(t,"__importStar",(function(){return T})),r.d(t,"__importDefault",(function(){return I}));var n=function(e,t){return(n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)};function o(e,t){function r(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}var i=function(){return(i=Object.assign||function(e){for(var t,r=1,n=arguments.length;r<n;r++)for(var o in t=arguments[r])Object.prototype.hasOwnProperty.call(t,o)&&(e[o]=t[o]);return e}).apply(this,arguments)};function s(e,t){var r={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(r[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var o=0;for(n=Object.getOwnPropertySymbols(e);o<n.length;o++)t.indexOf(n[o])<0&&Object.prototype.propertyIsEnumerable.call(e,n[o])&&(r[n[o]]=e[n[o]])}return r}function a(e,t,r,n){var o,i=arguments.length,s=i<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,r):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(o=e[a])&&(s=(i<3?o(s):i>3?o(t,r,s):o(t,r))||s);return i>3&&s&&Object.defineProperty(t,r,s),s}function c(e,t){return function(r,n){t(r,n,e)}}function u(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)}function f(e,t,r,n){return new(r||(r=Promise))((function(o,i){function s(e){try{c(n.next(e))}catch(e){i(e)}}function a(e){try{c(n.throw(e))}catch(e){i(e)}}function c(e){e.done?o(e.value):new r((function(t){t(e.value)})).then(s,a)}c((n=n.apply(e,t||[])).next())}))}function l(e,t){var r,n,o,i,s={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function a(i){return function(a){return function(i){if(r)throw new TypeError("Generator is already executing.");for(;s;)try{if(r=1,n&&(o=2&i[0]?n.return:i[0]?n.throw||((o=n.return)&&o.call(n),0):n.next)&&!(o=o.call(n,i[1])).done)return o;switch(n=0,o&&(i=[2&i[0],o.value]),i[0]){case 0:case 1:o=i;break;case 4:return s.label++,{value:i[1],done:!1};case 5:s.label++,n=i[1],i=[0];continue;case 7:i=s.ops.pop(),s.trys.pop();continue;default:if(!(o=(o=s.trys).length>0&&o[o.length-1])&&(6===i[0]||2===i[0])){s=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]<o[3])){s.label=i[1];break}if(6===i[0]&&s.label<o[1]){s.label=o[1],o=i;break}if(o&&s.label<o[2]){s.label=o[2],s.ops.push(i);break}o[2]&&s.ops.pop(),s.trys.pop();continue}i=t.call(e,s)}catch(e){i=[6,e],n=0}finally{r=o=0}if(5&i[0])throw i[1];return{value:i[0]?i[1]:void 0,done:!0}}([i,a])}}}function d(e,t){for(var r in e)t.hasOwnProperty(r)||(t[r]=e[r])}function _(e){var t="function"==typeof Symbol&&e[Symbol.iterator],r=0;return t?t.call(e):{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}}}function p(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var n,o,i=r.call(e),s=[];try{for(;(void 0===t||t-- >0)&&!(n=i.next()).done;)s.push(n.value)}catch(e){o={error:e}}finally{try{n&&!n.done&&(r=i.return)&&r.call(i)}finally{if(o)throw o.error}}return s}function h(){for(var e=[],t=0;t<arguments.length;t++)e=e.concat(p(arguments[t]));return e}function g(){for(var e=0,t=0,r=arguments.length;t<r;t++)e+=arguments[t].length;var n=Array(e),o=0;for(t=0;t<r;t++)for(var i=arguments[t],s=0,a=i.length;s<a;s++,o++)n[o]=i[s];return n}function v(e){return this instanceof v?(this.v=e,this):new v(e)}function E(e,t,r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n,o=r.apply(e,t||[]),i=[];return n={},s("next"),s("throw"),s("return"),n[Symbol.asyncIterator]=function(){return this},n;function s(e){o[e]&&(n[e]=function(t){return new Promise((function(r,n){i.push([e,t,r,n])>1||a(e,t)}))})}function a(e,t){try{(r=o[e](t)).value instanceof v?Promise.resolve(r.value.v).then(c,u):f(i[0][2],r)}catch(e){f(i[0][3],e)}var r}function c(e){a("next",e)}function u(e){a("throw",e)}function f(e,t){e(t),i.shift(),i.length&&a(i[0][0],i[0][1])}}function y(e){var t,r;return t={},n("next"),n("throw",(function(e){throw e})),n("return"),t[Symbol.iterator]=function(){return this},t;function n(n,o){t[n]=e[n]?function(t){return(r=!r)?{value:v(e[n](t)),done:"return"===n}:o?o(t):t}:o}}function C(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t,r=e[Symbol.asyncIterator];return r?r.call(e):(e=_(e),t={},n("next"),n("throw"),n("return"),t[Symbol.asyncIterator]=function(){return this},t);function n(r){t[r]=e[r]&&function(t){return new Promise((function(n,o){(function(e,t,r,n){Promise.resolve(n).then((function(t){e({value:t,done:r})}),t)})(n,o,(t=e[r](t)).done,t.value)}))}}}function m(e,t){return Object.defineProperty?Object.defineProperty(e,"raw",{value:t}):e.raw=t,e}function T(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t}function I(e){return e&&e.__esModule?e:{default:e}}},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.appendParams=function(e,r){void 0===r&&(r={});var n=[];return Object.keys(r).forEach((function(e){var o=r[e];if(void 0!==o){if(t.isPlainObject(o))try{o=JSON.stringify(o)}catch(e){}n.push(e+"="+encodeURIComponent(o))}})),n.length?(e.indexOf("?")>-1?e+"&":e+"?")+n.join("&"):e},t.delay=function(e){return new Promise((function(t){return setTimeout(t,e)}))},t.genPromise=function(){var e,t;return{promise:new Promise((function(r,n){e=r,t=n})),resolve:e,reject:t}},t.noop=function(){},t.getErrorMsg=function(e){if(e){var t="";return"string"==typeof e?e:(t=e.msg||e.Message||e.message||e.errMsg||"连接服务器失败,请稍后再试",e.reqId&&(t+="("+e.reqId+")"),t||(t="连接服务器失败,请稍后再试"),t)}},t.isPlainObject=function(e){if("object"!=(void 0===e?"undefined":typeof e)||null===e)return!1;for(var t=e;null!==Object.getPrototypeOf(t);)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}},function(e,t,r){"use strict";var n,o,i,s;Object.defineProperty(t,"__esModule",{value:!0}),function(e){e.Ready="ready",e.Error="error",e.WsError="ws_error",e.WsClose="ws_close",e.WsPush="wsPush",e.WsReport="wsReport",e.WsControl="wsControl",e.WsStatusChange="wsStatusChange"}(t.EventTypes||(t.EventTypes={})),function(e){e.WX_API_NEED_AUTH="WX_API_NEED_AUTH",e.GET_USERINFO_NEED_AUTH="GET_USERINFO_NEED_AUTH",e.WX_API_FAIL="WX_API_FAIL",e.VERIFY_LOGIN_FAIL="VERIFY_LOGIN_FAIL",e.INTERNAL_ERROR="INTERNAL_ERROR"}(t.ErrorCode||(t.ErrorCode={})),function(e){e.UDP_NOT_RESPONSED="UDP_NOT_RESPONSED",e.SSID_NOT_MATCH="SSID_NOT_MATCH",e.CONNECT_SOFTAP_FAIL="CONNECT_SOFTAP_FAIL",e.CONNECT_TARGET_WIFI_FAIL="CONNECT_TARGET_WIFI_FAIL",e.UDP_ERROR="UDP_ERROR",e.DEVICE_ERROR="DEVICE_ERROR",e.INVALID_UDP_RESPONSE="INVALID_UDP_RESPONSE",e.DEVICE_CONNECT_MQTT_FAIL="DEVICE_CONNECT_MQTT_FAIL",e.DEVICE_CONNECT_WIFI_FAIL="DEVICE_CONNECT_WIFI_FAIL",e.ADD_DEVICE_FAIL="ADD_DEVICE_FAIL",e.SEND_UDP_MSG_FAIL="SEND_UDP_MSG_FAIL"}(i=t.ConnectDeviceErrorCode||(t.ConnectDeviceErrorCode={})),t.SoftApErrorMsg=((n={})[i.UDP_NOT_RESPONSED]="超时未收到设备响应",n[i.CONNECT_SOFTAP_FAIL]="手机连接设备热点失败",n[i.CONNECT_TARGET_WIFI_FAIL]="手机连接WiFi路由器失败",n[i.UDP_ERROR]="连接设备失败",n[i.DEVICE_ERROR]="设备配网异常",n[i.INVALID_UDP_RESPONSE]="设备响应报文格式错误",n[i.DEVICE_CONNECT_MQTT_FAIL]="连接云端失败",n[i.DEVICE_CONNECT_WIFI_FAIL]="设备连接WiFi路由器失败",n[i.ADD_DEVICE_FAIL]="添加设备失败",n[i.SEND_UDP_MSG_FAIL]="发送配网消息失败",n),function(e){e.CONNECT_DEVICE_START="CONNECT_DEVICE_START",e.CONNECT_SOFTAP_START="CONNECT_SOFTAP_START",e.CONNECT_SOFTAP_SUCCESS="CONNECT_SOFTAP_SUCCESS",e.CREATE_UDP_CONNECTION_START="CREATE_UDP_CONNECTION_START",e.CREATE_UDP_CONNECTION_SUCCESS="CREATE_UDP_CONNECTION_SUCCESS",e.SEND_TARGET_WIFIINFO_START="SEND_TARGET_WIFIINFO_START",e.SEND_TARGET_WIFIINFO_SUCCESS="SEND_TARGET_WIFIINFO_SUCCESS",e.GET_DEVICE_SIGNATURE_START="GET_DEVICE_SIGNATURE_START",e.GET_DEVICE_SIGNATURE_SUCCESS="GET_DEVICE_SIGNATURE_SUCCESS",e.CONNECT_TARGET_WIFI_START="RECONNECT_TARGET_WIFI_START",e.CONNECT_TARGET_WIFI_SUCCESS="RECONNECT_TARGET_WIFI_SUCCESS",e.ADD_DEVICE_START="ADD_DEVICE_START",e.ADD_DEVICE_SUCCESS="ADD_DEVICE_SUCCESS",e.CONNECT_DEVICE_SUCCESS="CONNECT_DEVICE_SUCCESS"}(s=t.ConnectDeviceStepCode||(t.ConnectDeviceStepCode={})),t.SoftApStepMsg=((o={})[s.CONNECT_DEVICE_START]="开始配网",o[s.CONNECT_SOFTAP_START]="开始连接设备热点",o[s.CONNECT_SOFTAP_SUCCESS]="连接设备热点成功",o[s.CREATE_UDP_CONNECTION_START]="开始与设备建立UDP连接",o[s.CREATE_UDP_CONNECTION_SUCCESS]="与设备建立UDP连接成功",o[s.SEND_TARGET_WIFIINFO_START]="开始发送目标WiFi信息至设备",o[s.SEND_TARGET_WIFIINFO_SUCCESS]="发送目标WiFi信息至设备成功",o[s.GET_DEVICE_SIGNATURE_START]="开始获取设备签名",o[s.GET_DEVICE_SIGNATURE_SUCCESS]="获取设备签名成功",o[s.CONNECT_TARGET_WIFI_START]="手机开始连接目标WiFi",o[s.CONNECT_TARGET_WIFI_SUCCESS]="手机连接目标WiFi成功",o[s.ADD_DEVICE_START]="开始添加设备",o[s.ADD_DEVICE_SUCCESS]="添加设备成功",o[s.CONNECT_DEVICE_SUCCESS]="配网成功",o)},function(e,t,r){"use strict";var n,o,i,s=r(17),a="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-";function c(){i=!1}function u(e){if(e){if(e!==n){if(e.length!==a.length)throw new Error("Custom alphabet for shortid must be "+a.length+" unique characters. You submitted "+e.length+" characters: "+e);var t=e.split("").filter((function(e,t,r){return t!==r.lastIndexOf(e)}));if(t.length)throw new Error("Custom alphabet for shortid must be "+a.length+" unique characters. These characters were not unique: "+t.join(", "));n=e,c()}}else n!==a&&(n=a,c())}function f(){return i||(i=function(){n||u(a);for(var e,t=n.split(""),r=[],o=s.nextValue();t.length>0;)o=s.nextValue(),e=Math.floor(o*t.length),r.push(t.splice(e,1)[0]);return r.join("")}())}e.exports={get:function(){return n||a},characters:function(e){return u(e),n},seed:function(e){s.seed(e),o!==e&&(c(),o=e)},lookup:function(e){return f()[e]},shuffled:f}},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(0),o=r(1),i=r(2);t.normalizeError=function(e){if(e)if(o.isPlainObject(e))if(e.errMsg)if(["auth deny","scope unauthorized"].some((function(t){return String(e.errMsg).indexOf(t)>-1})))if(0===e.errMsg.indexOf("getUserInfo"))Object.assign(e,{code:i.ErrorCode.GET_USERINFO_NEED_AUTH,msg:"尚未开启微信基本信息授权,请授权后使用"});else{var r=n.__read(e.errMsg.split(":"),1)[0];Object.assign(e,{code:i.ErrorCode.WX_API_NEED_AUTH,msg:"小程序接口("+r+")需要用户授权,请授权后使用"})}else Object.assign(e,{code:i.ErrorCode.WX_API_FAIL,msg:"小程序接口调用失败,请稍后再试"});else t.isVerifyLoginError(e)&&(e=t.genVerifyLoginFailError(e));else e instanceof Error&&(e={code:i.ErrorCode.INTERNAL_ERROR,msg:e.message,stack:e.stack,error:e});return e},t.genVerifyLoginFailError=function(e){e||(e={});e.code,e.msg;var t=n.__rest(e,["code","msg"]);return n.__assign({code:i.ErrorCode.VERIFY_LOGIN_FAIL,msg:"登录态验证失败,请重新登录"},t)},t.isVerifyLoginError=function(e){return e&&String(e.code||"").indexOf("InvalidAccessToken")>-1},t.handleVerifyLoginError=function(e){if(t.isVerifyLoginError(e))throw t.genVerifyLoginFailError(e)}},function(e,t,r){"use strict";var n;Object.defineProperty(t,"__esModule",{value:!0});var o,i=r(1);!function(e){e.Debug="Debug",e.Info="Info",e.Warn="Warn",e.Error="Error"}(o=t.LogLevel||(t.LogLevel={}));var s=((n={})[o.Debug]=console.log,n[o.Info]=console.info,n[o.Warn]=console.warn,n[o.Error]=console.error,n),a=function(){function e(){this.options={debug:!1}}return e.prototype._getLogger=function(e){return e in o||(e=o.Debug),this.options.debug?s[e].bind(console,"["+e+"]"):i.noop},e.prototype.config=function(e){Object.assign(this.options,e)},Object.defineProperty(e.prototype,"info",{get:function(){return this._getLogger(o.Info)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"debug",{get:function(){return this._getLogger(o.Debug)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"warn",{get:function(){return this._getLogger(o.Warn)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"error",{get:function(){return this._getLogger(o.Error)},enumerable:!0,configurable:!0}),e}();t.default=new a},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=Object.defineProperty,o=Object.create,i=Object.prototype.hasOwnProperty,s={configurable:!0,enumerable:!1,writable:!0,value:null};function a(e){if("function"!=typeof e)throw new TypeError(e+" is not a function");return e}var c=function(){function e(){}return e.prototype.on=function(e,t){var r;return a(t),i.call(this,"__ee__")?r=this.__ee__:(r=s.value=o(null),n(this,"__ee__",s),s.value=null),r[e]?r[e].push(t):r[e]=[t],this},e.prototype.once=function(e,t){var r,n=this;return a(t),this.on.call(this,e,r=function(){for(var o=[],i=0;i<arguments.length;i++)o[i]=arguments[i];n.off.call(void 0,e,r),t.apply(n,o)}),this},e.prototype.off=function(e,t){if(!i.call(this,"__ee__"))return this;var r=this.__ee__;if(!r[e])return this;if(t){var n=r[e]||[],o=n.indexOf(t);o>-1&&n.splice(o,1)}else r[e].length=0;return this},e.prototype.emit=function(e){for(var t=this,r=[],n=1;n<arguments.length;n++)r[n-1]=arguments[n];if(i.call(this,"__ee__")){var o=this.__ee__[e];o&&o.length&&o.forEach((function(e){return e.apply(t,r)}))}},e}();t.default=c},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(0);t.pify=function(e,t){return void 0===t&&(t=wx),function(r){for(var o=[],i=1;i<arguments.length;i++)o[i-1]=arguments[i];return new Promise((function(i,s){e?e.call.apply(e,n.__spread([t,n.__assign(n.__assign({},r),{success:i,fail:s})],o)):wx.showModal({title:"提示",content:"当前微信版本过低,无法使用该功能,请升级到最新微信版本后重试",complete:function(){return s()},confirmColor:"#006eff",showCancel:!1})}))}}},function(e,t,r){"use strict";var n=r(3),o=r(18),i=r(22),s=r(23)||0;function a(){return o(s)}e.exports=a,e.exports.generate=a,e.exports.seed=function(t){return n.seed(t),e.exports},e.exports.worker=function(t){return s=t,e.exports},e.exports.characters=function(e){return void 0!==e&&n.characters(e),n.shuffled()},e.exports.isValid=i},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(0);n.__exportStar(r(10),t),n.__exportStar(r(16),t)},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(0),o=n.__importDefault(r(15)),i=r(7),s=0;t.request=function(e){return n.__awaiter(void 0,void 0,void 0,(function(){var t,r=e.url,a=e.data,c=e.header,u=void 0===c?{}:c,f=e.method,l=void 0===f?"get":f,d=e.dataType,_=e.responseType,p=n.__rest(e,["url","data","header","method","dataType","responseType"]);return n.__generator(this,(function(e){switch(e.label){case 0:e.trys.push([0,5,6,7]),e.label=1;case 1:return s>=10?[4,o.default.startBlocking()]:[3,3];case 2:return e.sent(),[3,1];case 3:return s++,[4,i.pify(wx.request)(n.__assign({url:r,data:a,header:u,method:l,dataType:d,responseType:_},p))];case 4:return[2,e.sent()];case 5:return t=e.sent(),[2,Promise.reject(t)];case 6:return s--,o.default.resolveFirstBlock(),[7];case 7:return[2]}}))}))}},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(0);n.__exportStar(r(2),t),n.__exportStar(r(12),t)},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(0);r(13);var o=r(14),i=n.__importDefault(r(6)),s=r(25),a=n.__importDefault(r(5)),c=r(29),u=r(2),f=r(1),l=r(9),d=r(4),_=r(30),p=function(e){function t(t){var r=t.getAccessToken,i=t.appKey,c=void 0===i?"":i,f=t.apiPlatform,l=void 0===f?"":f,d=t.debug,_=void 0!==d&&d,p=t.wsConfig,h=void 0===p?{}:p,g=h.autoReconnect,v=void 0===g||g,E=h.disconnectWhenAppHide,y=void 0===E||E,C=h.connectWhenAppShow,m=void 0===C||C,T=n.__rest(h,["autoReconnect","disconnectWhenAppHide","connectWhenAppShow"]),I=e.call(this)||this;return I.isManuallyClose=!1,I._defaultFamilyIdPromise=null,a.default.config({debug:_}),I.ws=new s.IotWebsocket(I,n.__assign(n.__assign({},T),{apiPlatform:l})),I.loginManager=new o.LoginManager(I,{getAccessToken:r,appKey:c}),I._apiPlatform=l,I.ws.on("error",(function(e){a.default.debug("websocket error",e),I.emit(u.EventTypes.WsError,e),v&&I._reconnectWs()})),I.ws.on("close",(function(e){var t=void 0===e?{}:e,r=t.code,n=t.reason;a.default.debug("websocket close",{code:r,reason:n}),I.emit(u.EventTypes.WsClose,{code:r,reason:n}),v&&I._onWebsocketClose()})),I.ws.on("push",(function(e){return I._handlePushEvent(e)})),wx.onAppHide((function(){y&&(I.isManuallyClose=!0,I.ws.disconnect())})),wx.onAppShow((function(){m&&I.isLogin&&I.ws.connect()})),I}return n.__extends(t,e),Object.defineProperty(t.prototype,"userInfo",{get:function(){return this.loginManager.userInfo},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"isLogin",{get:function(){return this.loginManager.isLogin},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"userId",{get:function(){return this.loginManager.userId},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"nickName",{get:function(){return this.loginManager.nickName},enumerable:!0,configurable:!0}),t.prototype.init=function(e){return n.__awaiter(this,void 0,void 0,(function(){var t=this;return n.__generator(this,(function(r){return e||(e={}),e.reload&&(this._initPromise=null),[2,this._initPromise||(this._initPromise=new Promise((function(e,r){return n.__awaiter(t,void 0,void 0,(function(){var t;return n.__generator(this,(function(n){switch(n.label){case 0:return n.trys.push([0,3,,4]),[4,this.loginManager.login()];case 1:return n.sent(),[4,this.ws.connect()];case 2:return n.sent(),e(),[3,4];case 3:return t=n.sent(),r(d.normalizeError(t)),this._initPromise=null,[3,4];case 4:return[2]}}))}))})))]}))}))},t.prototype.getDefaultFamilyId=function(){var e=this;return this._defaultFamilyIdPromise||(this._defaultFamilyIdPromise=new Promise((function(t,r){return n.__awaiter(e,void 0,void 0,(function(){var e,o,i,s;return n.__generator(this,(function(n){switch(n.label){case 0:return n.trys.push([0,4,,5]),[4,this.requestApi("AppGetFamilyList",{Offset:0,Limit:100})];case 1:return e=n.sent(),o=e.FamilyList,e.Total?[3,3]:[4,this.requestApi("AppCreateFamily",{Name:this.loginManager.nickName})];case 2:return i=n.sent().Data.FamilyId,[2,t(i)];case 3:return t(o[0].FamilyId),[3,5];case 4:return s=n.sent(),r(s),this._defaultFamilyIdPromise=null,[3,5];case 5:return[2]}}))}))})))},t.prototype.sendWebsocketMessage=function(e,t){return void 0===t&&(t={}),n.__awaiter(this,void 0,void 0,(function(){return n.__generator(this,(function(r){switch(r.label){case 0:return[4,this.init()];case 1:return r.sent(),[2,this.ws.send(e,t)]}}))}))},t.prototype.connectWebsocket=function(){return n.__awaiter(this,void 0,void 0,(function(){return n.__generator(this,(function(e){switch(e.label){case 0:return[4,this.init()];case 1:return e.sent(),[4,this.ws.connect()];case 2:return e.sent(),[2]}}))}))},t.prototype.disconnectWebsocket=function(){this.ws.disconnect()},t.prototype.subscribeDevices=function(e){return n.__awaiter(this,void 0,void 0,(function(){return n.__generator(this,(function(t){return this.ws.subscribe((e||[]).map((function(e){return"string"==typeof e?e:e&&e.DeviceId?e.DeviceId:void 0})).filter(Boolean)),[2]}))}))},t.prototype.requestApi=function(e,t,r){void 0===t&&(t={}),void 0===r&&(r={});var o=r.doNotRetry,i=void 0!==o&&o,s=r.needLogin,c=void 0===s||s,u=n.__rest(r,["doNotRetry","needLogin"]);return n.__awaiter(this,void 0,void 0,(function(){var r,o,s,f,_,p,h;return n.__generator(this,(function(g){switch(g.label){case 0:return g.trys.push([0,6,,13]),c?[4,this.loginManager.checkLogin()]:[3,2];case 1:g.sent(),g.label=2;case 2:return r=this.loginManager,o=r.accessToken,s=r.userId,t&&"default"===t.FamilyId?(f=t,[4,this.getDefaultFamilyId()]):[3,4];case 3:f.FamilyId=g.sent(),g.label=4;case 4:return _=n.__assign({uin:s},t),o&&(_.AccessToken="fuckyou"),this._apiPlatform&&(_.Platform=this._apiPlatform),[4,l.requestTokenApi(e,_,u)];case 5:return[2,g.sent()];case 6:if(p=g.sent(),a.default.debug("requestApi fail",p),!d.isVerifyLoginError(p))return[3,12];if(i)return[3,11];g.label=7;case 7:return g.trys.push([7,9,,10]),[4,this.loginManager.reLogin()];case 8:return g.sent(),[3,10];case 9:return h=g.sent(),a.default.error("reLogin fail",h),[2,Promise.reject(d.genVerifyLoginFailError(p))];case 10:return[2,this.requestApi(e,t,n.__assign({doNotRetry:!0},u))];case 11:return[2,Promise.reject(d.genVerifyLoginFailError(p))];case 12:return[2,Promise.reject(d.normalizeError(p))];case 13:return[2]}}))}))},t.prototype.connectDevice=function(e){return _.connectDevice(this,e)},t.prototype._handlePushEvent=function(e){e||(e={}),this.emit(u.EventTypes.WsPush,e);var t=e.action,r=e.params;r||(r={}),a.default.debug("actions updateDeviceDataByPush",e);var n=r.DeviceId,o=r.Type,i=r.SubType,s=r.Payload,f=r.Time,l=new Date(f).getTime();switch(t){case"DeviceChange":switch(o){case"Property":case"Shadow":case"Template":switch(i){case"Report":var d={};try{var _=JSON.parse(c.decodeBase64(s));if(a.default.debug("actions updateDeviceData payload",_),_){var p=_.type,h=_.state,g=_.method,v=_.params;if(p&&"update"===p&&h&&h.reported&&(g="report",v=h.reported),v||(v={}),"report"===g)for(var E in v)d[E]={Value:v[E],lastUpdate:l}}}catch(e){a.default.error("handle report event error",e)}this.emit(u.EventTypes.WsReport,{deviceId:n,deviceData:d});break;case"Push":d={};try{if(s){p=s.type,_=s.payload,g=s.method,v=s.params;if(p&&"delta"===p&&_&&_.state&&(g="control",v=_.state),"control"===g&&v){for(var E in v)d[E]={Value:v[E],LastUpdate:l};this.emit(u.EventTypes.WsControl,{deviceId:n,deviceData:d})}}}catch(e){a.default.error(e)}}break;case"StatusChange":var y="Online"===i?1:0;this.emit(u.EventTypes.WsStatusChange,{deviceId:n,deviceStatus:y})}}},t.prototype._onWebsocketClose=function(){if(!this.isManuallyClose)return this._reconnectWs();this.isManuallyClose=!1},t.prototype._reconnectWs=function(){return n.__awaiter(this,void 0,void 0,(function(){var e;return n.__generator(this,(function(t){switch(t.label){case 0:return t.trys.push([0,3,,4]),a.default.debug("websocket reconnecting in 2 seconds"),[4,f.delay(2e3)];case 1:return t.sent(),[4,this.ws.connect()];case 2:return t.sent(),[3,4];case 3:return e=t.sent(),a.default.error("error when reconnect ws",e),[2,Promise.reject(e)];case 4:return[2]}}))}))},t}(i.default);t.QcloudIotExplorerAppDevSdk=p},function(e,t){},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(0),o=n.__importDefault(r(6)),i=r(9),s=n.__importDefault(r(24)),a=r(4),c=n.__importDefault(r(5)),u="__qcloud-iotexplorer-appdev-sdk-accessToken",f=function(e){function t(t,r){var n=r.getAccessToken,o=r.appKey,i=e.call(this)||this;return i.accessToken="",i.appKey="",i.isLogin=!1,i.userInfo=null,i.sdk=t,i.getAccessToken=n,i.appKey=o,i}return n.__extends(t,e),t.prototype.login=function(){return n.__awaiter(this,void 0,void 0,(function(){var e,t,r,o,f;return n.__generator(this,(function(n){switch(n.label){case 0:e=!1,n.label=1;case 1:return n.trys.push([1,7,,10]),[4,s.default.getItem(u)];case 2:return(t=n.sent())?[3,4]:[4,this.getAccessToken()];case 3:return r=n.sent().Token,t=r,[3,5];case 4:e=!0,n.label=5;case 5:return[4,i.requestTokenApi("AppGetUser",{AccessToken:t})];case 6:return o=n.sent().Data,s.default.setItem(u,t),this.accessToken=t,this.userInfo=o,this.isLogin=!0,[3,10];case 7:return f=n.sent(),a.isVerifyLoginError(f)?[4,this.logout()]:[3,9];case 8:if(n.sent(),e)return c.default.debug("Cached Token expired, retrying..."),[2,this.login()];n.label=9;case 9:return[2,Promise.reject(f)];case 10:return[2]}}))}))},Object.defineProperty(t.prototype,"userId",{get:function(){return this.userInfo?this.userInfo.UserID:""},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"nickName",{get:function(){return this.userInfo?this.userInfo.NickName:""},enumerable:!0,configurable:!0}),t.prototype.checkLogin=function(){if(!this.isLogin)throw a.genVerifyLoginFailError()},t.prototype.logout=function(){return n.__awaiter(this,void 0,void 0,(function(){return n.__generator(this,(function(e){switch(e.label){case 0:return[4,s.default.removeItem(u)];case 1:return e.sent(),this.accessToken="",this.isLogin=!1,[2]}}))}))},t.prototype.reLogin=function(){return n.__awaiter(this,void 0,void 0,(function(){return n.__generator(this,(function(e){switch(e.label){case 0:return[4,this.logout()];case 1:return e.sent(),[4,this.login()];case 2:return e.sent(),[2]}}))}))},t}(o.default);t.LoginManager=f},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=[];t.default={resolveFirstBlock:function(){n.length&&(n[0].resolve(),n.shift())},startBlocking:function(){var e,t=new Promise((function(t){e=t}));return n.push({promise:t,resolve:e}),t}}},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(0),o=n.__importDefault(r(8)),i=r(1),s=r(10);t.requestTokenApi=function(e,t,r){return void 0===t&&(t={}),void 0===r&&(r={}),n.__awaiter(void 0,void 0,void 0,(function(){var a,c,u,f,l,d,_,p,h,g=t.uin,v=t.AccessToken,E=n.__rest(t,["uin","AccessToken"]),y=r.method,C=void 0===y?"POST":y,m=n.__rest(r,["method"]);return n.__generator(this,(function(t){switch(t.label){case 0:return c=o.default(),u={uin:g,cmd:e},E=Object.assign({},E,{Action:e,RequestId:c,AccessToken:v}),f=i.appendParams(m.url||"https://iot.cloud.tencent.com/api/exploreropen/tokenapi",u),a=n.__assign({url:f,data:E,method:C},m),[4,s.request(a)];case 1:if(l=t.sent().data,d=l.code,_=l.msg,p=l.data,h=void 0===p?{}:p,d){if(h&&h.Error)throw{code:h.Error.Code,msg:h.Error.Message,reqId:c};throw{code:d,msg:_,reqId:c}}return[2,h]}}))}))}},function(e,t,r){"use strict";var n=1;e.exports={nextValue:function(){return(n=(9301*n+49297)%233280)/233280},seed:function(e){n=e}}},function(e,t,r){"use strict";var n,o,i=r(19),s=(r(3),1459707606518),a=6;e.exports=function(e){var t="",r=Math.floor(.001*(Date.now()-s));return r===o?n++:(n=0,o=r),t+=i(a),t+=i(e),n>0&&(t+=i(n)),t+=i(r)}},function(e,t,r){"use strict";var n=r(3),o=r(20),i=r(21);e.exports=function(e){for(var t,r=0,s="";!t;)s+=i(o,n.get(),1),t=e<Math.pow(16,r+1),r++;return s}},function(e,t,r){"use strict";var n,o="object"==typeof window&&(window.crypto||window.msCrypto);n=o&&o.getRandomValues?function(e){return o.getRandomValues(new Uint8Array(e))}:function(e){for(var t=[],r=0;r<e;r++)t.push(Math.floor(256*Math.random()));return t},e.exports=n},function(e,t){e.exports=function(e,t,r){for(var n=(2<<Math.log(t.length-1)/Math.LN2)-1,o=Math.ceil(1.6*n*r/t.length),i="";;)for(var s=e(o),a=0;a<o;a++){var c=s[a]&n;if(t[c]&&(i+=t[c]).length===r)return i}}},function(e,t,r){"use strict";var n=r(3);e.exports=function(e){return!(!e||"string"!=typeof e||e.length<6)&&!new RegExp("[^"+n.get().replace(/[|\\{}()[\]^$+*?.-]/g,"\\$&")+"]").test(e)}},function(e,t,r){"use strict";e.exports=0},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(0),o=r(7);t.default={getItem:function(e){return n.__awaiter(this,void 0,void 0,(function(){return n.__generator(this,(function(t){switch(t.label){case 0:return t.trys.push([0,2,,3]),[4,o.pify(wx.getStorage)({key:e})];case 1:return[2,t.sent().data];case 2:return t.sent(),[2,null];case 3:return[2]}}))}))},setItem:function(e,t){return n.__awaiter(this,void 0,void 0,(function(){var r;return n.__generator(this,(function(n){switch(n.label){case 0:return n.trys.push([0,2,,3]),[4,o.pify(wx.setStorage)({key:e,data:t})];case 1:return n.sent(),[3,3];case 2:return r=n.sent(),console.error("setStorage error",r),[3,3];case 3:return[2]}}))}))},removeItem:function(e){return n.__awaiter(this,void 0,void 0,(function(){var t;return n.__generator(this,(function(r){switch(r.label){case 0:return r.trys.push([0,2,,3]),[4,o.pify(wx.removeStorage)({key:e})];case 1:return r.sent(),[3,3];case 2:return t=r.sent(),console.error("removeStorage error",t),[3,3];case 3:return[2]}}))}))}}},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(0),o=n.__importDefault(r(6)),i=n.__importDefault(r(8)),s=r(1),a=r(26),c=n.__importDefault(r(5)),u=r(4),f={url:"wss://iot.cloud.tencent.com/ws/explorer",heartbeatInterval:6e4},l=function(e){function t(t,r){var n=e.call(this)||this;return n.sdk=t,n.requestHandlerMap={},n.options=Object.assign({},f,r),n._connected=!1,n._subscribeDeviceIdList=[],n._heartBeatTimer=null,n}return n.__extends(t,e),t.prototype.isConnected=function(){return!!this._connected},t.prototype.doConnectWs=function(){return n.__awaiter(this,void 0,void 0,(function(){var e=this;return n.__generator(this,(function(t){return[2,this._doConnectWsPromise||(this._doConnectWsPromise=new Promise((function(t,r){return n.__awaiter(e,void 0,void 0,(function(){var e,o,i=this;return n.__generator(this,(function(u){e=function(e){r(e),i.emit("error",e),i.disconnect()};try{o=this.options.url,this.ws=new a.WebSocket(s.appendParams(o,{uin:this.sdk.loginManager.userId})),this.ws.onOpen((function(){c.default.debug("websocket connected"),i._connected=!0,i.emit("connect"),t()})),this.ws.onError(e),this.ws.onMessage((function(e){var t=e.data;i.emit("message",t);try{t=JSON.parse(t)}catch(e){return void c.default.warn("onMessage parse event.data error: "+t)}t.push?i.emit("push",t):void 0!==t.reqId&&i.requestHandlerMap[t.reqId]&&i.requestHandlerMap[t.reqId](null,t)})),this.ws.onClose((function(e){return n.__awaiter(i,void 0,void 0,(function(){return n.__generator(this,(function(t){return c.default.debug("websocket closed"),this.disconnect(),this.emit("close",e),[2]}))}))}))}catch(t){e(t)}return[2]}))}))})))]}))}))},t.prototype.connect=function(){return n.__awaiter(this,void 0,void 0,(function(){return n.__generator(this,(function(e){switch(e.label){case 0:return[4,this.sdk.loginManager.checkLogin()];case 1:return e.sent(),this.isConnected()?[3,3]:[4,this.doConnectWs()];case 2:e.sent(),e.label=3;case 3:return[2,this.activePush()]}}))}))},t.prototype.subscribe=function(e){return this.activePush(e)},t.prototype.disconnect=function(){if(this.ws){this.ws.close({}),this._connected=!1,this._doConnectWsPromise=null,this.ws=null,clearInterval(this._heartBeatTimer),this._heartBeatTimer=null}},t.prototype.send=function(e,t,r){void 0===t&&(t={});var o=(void 0===r?{}:r).reqId;return n.__awaiter(this,void 0,void 0,(function(){var r=this;return n.__generator(this,(function(n){switch(n.label){case 0:if(o||(o=i.default()),!this.ws)return[3,5];this.ws.send({data:JSON.stringify({action:e,reqId:o,params:t})}),n.label=1;case 1:return n.trys.push([1,,3,4]),[4,Promise.race([new Promise((function(e,t){r.requestHandlerMap[o]=function(r,n){if(!r)return n.data||!n.error&&!n.error_message?e(n.data):t({code:n.error,msg:n.error_message});t(r)}})),new Promise((function(e,t){setTimeout((function(){t({code:"TIMEOUT"})}),2e4)}))])];case 2:return[2,n.sent()];case 3:return delete this.requestHandlerMap[o],[7];case 4:return[3,6];case 5:c.default.warn("Try send ws message but no ws instance",e,t),n.label=6;case 6:return[2]}}))}))},t.prototype.callYunApi=function(e,t,r){void 0===t&&(t={});var o=(void 0===r?{}:r).doNotRetry;return n.__awaiter(this,void 0,void 0,(function(){var r,a,f,l,d,_,p,h,g,v,E,y;return n.__generator(this,(function(n){switch(n.label){case 0:r=i.default(),a=this.sdk.loginManager,f=a.accessToken,l=a.appKey,(t=Object.assign({},t,{RequestId:r})).AccessToken=f,d={Action:e,ActionParams:t},this.options.apiPlatform?d.Platform=this.options.apiPlatform:d.AppKey=l,c.default.debug("yunapi start("+r+") => ",d),n.label=1;case 1:return n.trys.push([1,3,,11]),[4,this.send("YunApi",d,{reqId:r})];case 2:if(!(_=n.sent()))throw c.default.error("empty response",d),{msg:"连接服务器失败,请稍后重试"};if(!(p=_.Response))throw c.default.error("empty response",d,p),{msg:"连接服务器失败,请稍后重试"};if(h=p.Error,g=p.error,v=p.error_message,h)throw{code:h.Code,msg:h.Message};if(g)throw{code:g,msg:v};return c.default.debug("yunapi success("+r+") => ",d,p),[2,p];case 3:if(E=n.sent(),c.default.error("yunapi fail("+r+") => ",E),!u.isVerifyLoginError(E))return[3,10];if(o)return[3,8];n.label=4;case 4:return n.trys.push([4,6,,7]),[4,this.sdk.loginManager.reLogin()];case 5:return n.sent(),[3,7];case 6:return y=n.sent(),c.default.error("reLogin fail",y),[2,Promise.reject(u.genVerifyLoginFailError(E))];case 7:return[2,this.callYunApi(e,t,{doNotRetry:!0})];case 8:return[4,this.sdk.loginManager.logout()];case 9:return n.sent(),[2,u.genVerifyLoginFailError(E)];case 10:return s.isPlainObject(E)&&(E.reqId=r),[2,Promise.reject(E)];case 11:return[2]}}))}))},t.prototype.sendWsHeatBeat=function(){if(this._subscribeDeviceIdList&&this._subscribeDeviceIdList.length)return this.callYunApi("AppDeviceTraceHeartBeat",{DeviceIds:this._subscribeDeviceIdList})},t.prototype.activePush=function(e){var t=this;e&&(this._subscribeDeviceIdList=e);var r=this.sdk.loginManager,n=r.isLogin,o=r.accessToken,i=r.appKey;n&&o&&this._subscribeDeviceIdList&&(this.send("ActivePush",{DeviceIds:this._subscribeDeviceIdList,AccessToken:o,AppKey:i}),this.sendWsHeatBeat(),clearInterval(this._heartBeatTimer),this._heartBeatTimer=setInterval((function(){return t.sendWsHeatBeat()}),this.options.heartbeatInterval))},t}(o.default);t.IotWebsocket=l},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(0).__importStar(r(27)),o=function(){function e(e){this.url=e,this.ws=null,this.initWs()}return e.prototype.initWs=function(){n.isMiniProgram?this.ws=wx.connectSocket({url:this.url}):this.ws=new e(this.url)},e.prototype.send=function(e){var t=e.data;n.isMiniProgram?this.ws.send({data:t}):this.ws.send(t)},e.prototype.close=function(e){var t=void 0===e?{}:e,r=t.code,o=t.reason;n.isMiniProgram?this.ws.close({code:r,reason:o}):this.ws.close(r,o)},e.prototype.onOpen=function(e){n.isMiniProgram?this.ws.onOpen(e):this.ws.addEventListener("open",e)},e.prototype.onClose=function(e){n.isMiniProgram?this.ws.onClose(e):this.ws.addEventListener("close",e)},e.prototype.onMessage=function(e){n.isMiniProgram?this.ws.onMessage(e):this.ws.addEventListener("message",e)},e.prototype.onError=function(e){n.isMiniProgram?this.ws.onError(e):this.ws.addEventListener("error",e)},e}();t.WebSocket=o},function(e,t,r){"use strict";(function(e){Object.defineProperty(t,"__esModule",{value:!0}),t.isMiniProgram=function(){try{return!!(wx&&wx.request&&wx.connectSocket)}catch(e){return!1}}(),t.isBrowser=function(){try{return"undefined"!=typeof window&&void 0!==window.document}catch(e){return!1}}(),t.isNode=function(){try{return!!e.versions.node}catch(e){return!1}}(),t.isRN=function(){try{return"ReactNative"===navigator.product}catch(e){return!1}}()}).call(this,r(28))},function(e,t){var r,n,o=e.exports={};function i(){throw new Error("setTimeout has not been defined")}function s(){throw new Error("clearTimeout has not been defined")}function a(e){if(r===setTimeout)return setTimeout(e,0);if((r===i||!r)&&setTimeout)return r=setTimeout,setTimeout(e,0);try{return r(e,0)}catch(t){try{return r.call(null,e,0)}catch(t){return r.call(this,e,0)}}}!function(){try{r="function"==typeof setTimeout?setTimeout:i}catch(e){r=i}try{n="function"==typeof clearTimeout?clearTimeout:s}catch(e){n=s}}();var c,u=[],f=!1,l=-1;function d(){f&&c&&(f=!1,c.length?u=c.concat(u):l=-1,u.length&&_())}function _(){if(!f){var e=a(d);f=!0;for(var t=u.length;t;){for(c=u,u=[];++l<t;)c&&c[l].run();l=-1,t=u.length}c=null,f=!1,function(e){if(n===clearTimeout)return clearTimeout(e);if((n===s||!n)&&clearTimeout)return n=clearTimeout,clearTimeout(e);try{n(e)}catch(t){try{return n.call(null,e)}catch(t){return n.call(this,e)}}}(e)}}function p(e,t){this.fun=e,this.array=t}function h(){}o.nextTick=function(e){var t=new Array(arguments.length-1);if(arguments.length>1)for(var r=1;r<arguments.length;r++)t[r-1]=arguments[r];u.push(new p(e,t)),1!==u.length||f||a(_)},p.prototype.run=function(){this.fun.apply(null,this.array)},o.title="browser",o.browser=!0,o.env={},o.argv=[],o.version="",o.versions={},o.on=h,o.addListener=h,o.once=h,o.off=h,o.removeListener=h,o.removeAllListeners=h,o.emit=h,o.prependListener=h,o.prependOnceListener=h,o.listeners=function(e){return[]},o.binding=function(e){throw new Error("process.binding is not supported")},o.cwd=function(){return"/"},o.chdir=function(e){throw new Error("process.chdir is not supported")},o.umask=function(){return 0}},function(e,t){const r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";t.encodeBase64=e=>{if(!e)return!1;let t,n,o,i,s,a,c,u="",f=0;do{t=e.charCodeAt(f++),n=e.charCodeAt(f++),o=e.charCodeAt(f++),i=t>>2,s=(3&t)<<4|n>>4,a=(15&n)<<2|o>>6,c=63&o,isNaN(n)?a=c=64:isNaN(o)&&(c=64),u+=r.charAt(i)+r.charAt(s)+r.charAt(a)+r.charAt(c)}while(f<e.length);return u},t.decodeBase64=e=>{if(!e)return!1;e=e.replace(/[^A-Za-z0-9\+\/\=]/g,"");let t,n,o,i,s="",a=0;do{t=r.indexOf(e.charAt(a++)),n=r.indexOf(e.charAt(a++)),o=r.indexOf(e.charAt(a++)),i=r.indexOf(e.charAt(a++)),s+=String.fromCharCode(t<<2|n>>4),64!=o&&(s+=String.fromCharCode((15&n)<<4|o>>2)),64!=i&&(s+=String.fromCharCode((3&o)<<6|i))}while(a<e.length);return s}},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(0),o=r(1),i=r(7),s=n.__importDefault(r(8)),a=n.__importDefault(r(5)),c=r(2),u=r(4),f=function(e){var t=new Uint8Array(e),r=String.fromCharCode.apply(null,t);return decodeURIComponent(escape(r))},l=function(e,t,r){return void 0===t&&(t=""),void 0===r&&(r={}),n.__awaiter(void 0,void 0,void 0,(function(){return n.__generator(this,(function(o){switch(o.label){case 0:return wx.hideToast(),[4,i.pify(wx.showModal)(n.__assign({title:e,content:t},r)).then((function(e){return!!e.confirm})).catch((function(){return!1}))];case 1:return[2,o.sent()]}}))}))};t.connectDevice=function(e,t){var r=t.targetWifiInfo,d=t.softApInfo,_=t.familyId,p=void 0===_?"default":_,h=t.udpAddress,g=void 0===h?"192.168.4.1":h,v=t.udpPort,E=void 0===v?8266:v,y=t.waitUdpResponseDuration,C=void 0===y?2e3:y,m=t.udpCommunicationRetryTime,T=void 0===m?5:m,I=t.stepGap,S=void 0===I?3e3:I,w=t.onProgress,b=void 0===w?o.noop:w,D=t.onError,O=void 0===D?o.noop:D,A=t.onComplete,N=void 0===A?o.noop:A,P=t.handleAddDevice;return n.__awaiter(this,void 0,void 0,(function(){var t,_,h,v,y,m,I,w,D,A,R=this;return n.__generator(this,(function(F){switch(F.label){case 0:s.default(),F.label=1;case 1:return F.trys.push([1,8,,9]),_=function(e){a.default.debug("softap-receive-unhandled-msg",{data:{message:e}})},v=function(e){"string"!=typeof e&&(e=JSON.stringify(e)),t.send({address:g,port:E,message:e})},y=function(e){return n.__awaiter(R,void 0,void 0,(function(){var t=this;return n.__generator(this,(function(r){return[2,new Promise((function(r,i){return n.__awaiter(t,void 0,void 0,(function(){var t,s,f,l;return n.__generator(this,(function(n){switch(n.label){case 0:n.trys.push([0,4,,5]),t=!0,s=0,_=function(e){try{t=!1,r(e)}catch(e){i(e)}},(f=function(){s++,a.default.debug("softap-udp-send-msg",{data:{msg:e,retryCount:s}}),v(e)})(),n.label=1;case 1:return t&&s<=T?[4,o.delay(C)]:[3,3];case 2:return n.sent(),t?(f(),[3,1]):[2];case 3:return i({code:c.ConnectDeviceErrorCode.UDP_NOT_RESPONSED}),[3,5];case 4:return l=n.sent(),(l=u.normalizeError(l)).code=c.ConnectDeviceErrorCode.SEND_UDP_MSG_FAIL,i(l),[3,5];case 5:return[2]}}))}))}))]}))}))},m=function(e){var t=e.SSID,r=e.password;return n.__awaiter(R,void 0,void 0,(function(){return n.__generator(this,(function(e){switch(e.label){case 0:return[4,i.pify(wx.connectWifi)({SSID:t,password:r})];case 1:return e.sent(),[4,i.pify(wx.getConnectedWifi)()];case 2:if(e.sent().wifi.SSID!==t)throw{code:c.ConnectDeviceErrorCode.SSID_NOT_MATCH};return a.default.debug("softap-connect-wifi-success"),[2]}}))}))},I=function(){return n.__awaiter(R,void 0,void 0,(function(){var i,s,d,g,v,E,C=this;return n.__generator(this,(function(T){switch(T.label){case 0:i=!1,T.label=1;case 1:return T.trys.push([1,3,,4]),h(c.ConnectDeviceStepCode.CREATE_UDP_CONNECTION_START),(t=wx.createUDPSocket()).bind(),s=o.genPromise(),d=o.genPromise(),g=o.genPromise(),t.onError((function(e){return s.reject({code:c.ConnectDeviceErrorCode.UDP_ERROR,errMsg:e})})),t.onMessage((function(e){try{var t=JSON.parse(f(e.message));a.default.debug("softap-udp-on-message",{data:{message:t}}),2==+t.cmdType&&("Current_Error"===t.deviceReply?g.reject({code:c.ConnectDeviceErrorCode.DEVICE_ERROR,errMsg:t}):"Previous_Error"===t.deviceReply?a.default.debug("softap-receive-prev-error",{data:{message:t}}):_(t))}catch(e){a.default.debug("softap-udp-parse-message-error",{error:e})}})),v=function(){return n.__awaiter(C,void 0,void 0,(function(){var s,f,d,_,g,v,E,C,T,I,w,b,D=this;return n.__generator(this,(function(O){switch(O.label){case 0:return s=function(e){return void 0===e&&(e=S),n.__awaiter(D,void 0,void 0,(function(){return n.__generator(this,(function(t){switch(t.label){case 0:return[4,o.delay(e)];case 1:if(t.sent(),i)throw a.default.debug("connection aborted"),null;return[2]}}))}))},f=Date.now(),console.log("step check",f),[4,s()];case 1:return O.sent(),console.log("after step check",Date.now()-f),h(c.ConnectDeviceStepCode.CREATE_UDP_CONNECTION_SUCCESS),h(c.ConnectDeviceStepCode.SEND_TARGET_WIFIINFO_START),[4,y({cmdType:1,ssid:r.SSID,password:r.password})];case 2:if("dataRecived"!==(d=O.sent()).deviceReply)throw{code:c.ConnectDeviceErrorCode.INVALID_UDP_RESPONSE,response:d};return[4,s(5e3)];case 3:return O.sent(),h(c.ConnectDeviceStepCode.SEND_TARGET_WIFIINFO_SUCCESS,{response:d}),h(c.ConnectDeviceStepCode.GET_DEVICE_SIGNATURE_START),[4,y({cmdType:0,timestamp:parseInt(String(Date.now()/1e3))})];case 4:if(_=O.sent(),g=_.mqttState,v=_.wifiState,E=n.__rest(_,["mqttState","wifiState"]),"connected"!==g)throw{code:c.ConnectDeviceErrorCode.DEVICE_CONNECT_MQTT_FAIL};if("connected"!==v)throw{code:c.ConnectDeviceErrorCode.DEVICE_CONNECT_WIFI_FAIL};return[4,s()];case 5:return O.sent(),h(c.ConnectDeviceStepCode.GET_DEVICE_SIGNATURE_SUCCESS,{signature:E}),t.close(),"function"!=typeof P?[3,7]:[4,P({Signature:E.signature,DeviceTimestamp:E.timestamp,ProductId:E.productId,DeviceName:E.deviceName,ConnId:E.connId})];case 6:return[2,O.sent()];case 7:C=!1,O.label=8;case 8:return O.trys.push([8,10,,12]),h(c.ConnectDeviceStepCode.CONNECT_TARGET_WIFI_START),[4,m(r)];case 9:return O.sent(),[3,12];case 10:return T=O.sent(),[4,l("手机连接路由Wi-Fi失败,请将手机手动切换到能够正常访问的网络环境后继续配网操作","",{confirmText:"继续",confirmColor:"#0052d9",cancelText:"取消",cancelColor:"#ff584c"})];case 11:if(!O.sent())throw I={code:c.ConnectDeviceErrorCode.CONNECT_TARGET_WIFI_FAIL},T&&T.errMsg&&(I.errMsg=T.errMsg),I;return C=!0,[3,12];case 12:return h(c.ConnectDeviceStepCode.CONNECT_TARGET_WIFI_SUCCESS,{userSkipReconnectWifi:C}),[4,s()];case 13:return O.sent(),w=function(){return n.__awaiter(D,void 0,void 0,(function(){var t;return n.__generator(this,(function(r){switch(r.label){case 0:return r.trys.push([0,2,,7]),[4,e.requestApi("AppSigBindDeviceInFamily",{Signature:E.signature,DeviceTimestamp:E.timestamp,ProductId:E.productId,DeviceName:E.deviceName,ConnId:E.connId,FamilyId:p||"default"})];case 1:return[2,r.sent()];case 2:return(t=r.sent())?t.errMsg&&/request:fail/.test(t.errMsg)?[4,l("手机切换到该网络环境后依然无法正常上网访问,请继续切换网络重试或取消配网操作","",{confirmText:"重试",confirmColor:"#0052d9",cancelText:"取消",cancelColor:"#ff584c"})]:[3,4]:[3,6];case 3:return r.sent()?[2,w()]:[2,Promise.reject({code:c.ConnectDeviceErrorCode.ADD_DEVICE_FAIL,errMsg:t.errMsg})];case 4:return[4,l(o.getErrorMsg(t),"",{confirmText:"重试",confirmColor:"#0052d9",cancelText:"取消",cancelColor:"#ff584c"})];case 5:return r.sent()?[2,w()]:((t=u.normalizeError(t)).code=c.ConnectDeviceErrorCode.ADD_DEVICE_FAIL,[2,Promise.reject(t)]);case 6:return[2,Promise.reject(t)];case 7:return[2]}}))}))},h(c.ConnectDeviceStepCode.ADD_DEVICE_START,{params:{Signature:E.signature,DeviceTimestamp:E.timestamp,ProductId:E.productId,DeviceName:E.deviceName,ConnId:E.connId}}),[4,w()];case 14:return b=O.sent(),h(c.ConnectDeviceStepCode.ADD_DEVICE_SUCCESS,{response:b}),[2]}}))}))},[4,Promise.race([v(),s.promise,d.promise,g.promise])];case 2:return T.sent(),[3,4];case 3:return E=T.sent(),i=!0,a.default.debug("softap-connect-fail",{error:E}),[2,Promise.reject(E)];case 4:return[2]}}))}))},(h=function(e,t){try{a.default.debug("STEP => "+e+", detail => "+JSON.stringify(t))}catch(e){}b(n.__assign({code:e,msg:c.SoftApStepMsg[e]},t))})(c.ConnectDeviceStepCode.CONNECT_DEVICE_START),[4,i.pify(wx.startWifi)()];case 2:if(F.sent(),!d)return[3,6];F.label=3;case 3:return F.trys.push([3,5,,6]),h(c.ConnectDeviceStepCode.CONNECT_SOFTAP_START),[4,m(d)];case 4:return F.sent(),h(c.ConnectDeviceStepCode.CONNECT_SOFTAP_SUCCESS),[3,6];case 5:throw w=F.sent(),D={code:c.ConnectDeviceErrorCode.CONNECT_SOFTAP_FAIL},w&&w.errMsg&&(D.errMsg=w.errMsg),D;case 6:return[4,I()];case 7:return F.sent(),h(c.ConnectDeviceStepCode.CONNECT_DEVICE_SUCCESS),N(),[3,9];case 8:return(A=F.sent())&&A.code in c.ConnectDeviceErrorCode&&(A.msg=c.SoftApErrorMsg[A.code]),O(A),[3,9];case 9:return[2]}}))}))}}])})); |
{ | ||
"name": "qcloud-iotexplorer-appdev-sdk", | ||
"version": "0.0.1", | ||
"version": "0.0.2", | ||
"description": "", | ||
"main": "dist/release/qcloud-iotexplorer-appdev-sdk.js", | ||
"scripts": { | ||
"dev": "webpack --watch", | ||
"build": "webpack --env.mode=production --watch" | ||
"dev": "webpack --env.target=miniprogram --watch", | ||
"build": "webpack --env.mode=production", | ||
"typing": "cd @types && tsc" | ||
}, | ||
@@ -10,0 +11,0 @@ "repository": { |
384
README.md
# qcloud-iotexplorer-appdev-sdk | ||
文档:TODO | ||
腾讯云物联网开发平台应用开发小程序端SDK | ||
## 安装 | ||
``` | ||
npm install qcloud-iotexplorer-appdev-sdk | ||
``` | ||
## 使用 | ||
```javascript | ||
// app.js | ||
const QcloudIotExplorerAppDevSdk = require('qcloud-iotexplorer-appdev-sdk'); | ||
App({ | ||
onLaunch() { | ||
const sdk = this.sdk = new QcloudIotExplorerAppDevSdk({ | ||
debug: true, | ||
appKey: '在「物联网开发平台-应用开发-小程序开发」中申请的AppKey', | ||
getAccessToken: () => this.login().then(({ Data }) => Data), | ||
}); | ||
// 初始化 | ||
sdk.init(); | ||
}, | ||
}); | ||
// pages/index.js | ||
Page({ | ||
onLoad() { | ||
const sdk = getApp().sdk; | ||
this.sdk.init().then(() => { | ||
// 当初始化完成后执行 | ||
console.log('ready'); | ||
this.getData(); | ||
}).catch((err) => { | ||
console.error(err); | ||
if (err.code === 'UserNeedAuth') { | ||
// 需要引导用户授权获取用户信息 | ||
} | ||
}) | ||
}, | ||
}); | ||
``` | ||
详细示例请参考[DEMO](https://github.com/tencentyun/qcloud-iotexplorer-appdev-sdk/blob/master/demo/miniprogram/README.md) | ||
## 开发文档 | ||
> 名称解释: | ||
> | ||
> API:指代本 SDK 提供的 API 方法 | ||
> | ||
> 接口:指代[物联网开发平台应用开发接口](https://cloud.tencent.com/document/product/1081/40773) | ||
### QcloudIotExplorerAppDevSdk(sdkOptions) | ||
构造函数选项 | ||
#### sdkOptions.getAccessToken: () => Promise<{ Token: string, ExpireAt?: number }> | ||
获取 accessToken 的回调,返回一个Promise,内包含 [AppGetTokenByWeiXin API](https://cloud.tencent.com/document/product/1081/40781) 的返回结果 | ||
#### sdkOptions.appKey: string | ||
在`物联网开发平台-应用开发-小程序开发` 中申请的 AppKey | ||
#### sdkOptions.debug?: boolean | ||
(可选)是否为调试模式,默认为: false,开启调试模式后会开启打印调试日志 | ||
#### sdkOptions.wsConfig?: WsOptions | ||
(可选)websocket的配置 | ||
##### WsOptions.autoReconnect?: boolean; | ||
(可选)websocket断开后是否自动连接,默认为: true,自动重连每两秒尝试一次 | ||
##### WsOptions.disconnectWhenAppHide?: boolean; | ||
(可选)当 App.onHide 触发时,是否自动断开 websocket,默认为: true | ||
##### WsOptions.connectWhenAppShow?: boolean; | ||
(可选)当 App.onShow 触发时,是否自动连接 websocket,默认为: true | ||
##### WsOptions.url?: string; | ||
(可选)websocket 服务的url,默认为:wss://iot.cloud.tencent.com/ws/explorer | ||
##### WsOptions.heartbeatInterval?: number; | ||
(可选)心跳包的发送间隔,单位毫秒,默认为: 60000 | ||
### API | ||
#### sdk.userInfo: UserInfo | ||
getter,用户信息 | ||
##### UserInfo.Avatar: string | ||
头像 | ||
##### UserInfo.CountryCode: string | ||
国家代码 | ||
##### UserInfo.Email: string | ||
邮箱 | ||
##### UserInfo.NickName: string | ||
昵称 | ||
##### UserInfo.PhoneNumber: string | ||
电话号码 | ||
##### UserInfo.UserID: string | ||
用户id | ||
#### sdk.isLogin: boolean | ||
getter,用户是否登录 | ||
#### sdk.userId: string; | ||
getter,用户id | ||
#### sdk.nickName: string; | ||
getter,用户昵称 | ||
#### sdk.init: (options) => Promise< void > | ||
##### options.reload?: boolean | ||
(可选)是否清理缓存的 Promise 并重新执行 | ||
##### API说明: | ||
初始化sdk,调用后将依次执行: | ||
1. 登录 | ||
2. 连接websocket | ||
该 API 可同时多次调用(返回同一个缓存的 Promise)。 | ||
若一次执行未完成或已执行成功,多次调用后拿到的会是同一个 Promise。 | ||
若 API 调用失败,则该缓存的 Promise 在 reject 之后会被释放,再次调用则将重新执行。 | ||
如: | ||
``` | ||
// app.js | ||
App({ | ||
onLaunch() { | ||
this.sdk = new Sdk(options); | ||
// 提前初始化 | ||
this.sdk.init(); | ||
} | ||
}) | ||
// pages/index/index.js | ||
Page({ | ||
onLoad() { | ||
// 该次调用与 app.js 中的调用拿到的是同一个 Promise,不会导致执行多次 | ||
getApp().sdk.init() | ||
.then(() => { | ||
// 初始化完成 | ||
}); | ||
} | ||
}) | ||
// pages/otherpage/otherpage.js | ||
Page({ | ||
onLoad() { | ||
// 若前面已初始化完成,这里将直接 resolve | ||
getApp().sdk.init(); | ||
.then(() => { | ||
// 初始化完成 | ||
}); | ||
} | ||
}) | ||
``` | ||
#### sdk.requestApi(Action: string, payload?: Object, options?: object) => Promise< response > | ||
##### Action: string; | ||
请求的接口 Action 名 | ||
##### payload?: Object | ||
(可选)请求接口的数据,API 会自动带上公共参数: `AccessToken`与`RequestId`。 | ||
##### options?: Object | ||
(可选)请求的选项,将透传给 [wx.request()](https://developers.weixin.qq.com/miniprogram/dev/api/network/request/wx.request.html)。 | ||
API说明: | ||
在完成 sdk.init() 后,请求 [TOKEN Api](https://cloud.tencent.com/document/product/1081/40773),返回一个 Promise。 | ||
若请求成功(code=0),则返回的是一个 resolved 的 Promise,内包含 Token Api 响应中的 `Response` 部分数据。 | ||
若请求失败,则返回的是一个 rejected 的 Promise,内包含数据结构如:`{ code, msg, ...detail }`。 | ||
>注意: | ||
>腾讯云物联网开发平台的设备体系是基于`家庭`的,所有设备都是归属于一个家庭的。 | ||
>开发者也可以选择不关注`家庭`这个概念,但是在所有需要传 `FamilyId` 的接口中需要传 `FamilyId='default'`(如:[查询设备列表](https://cloud.tencent.com/document/product/1081/40803)),sdk 会自动完成内部家庭相关的逻辑(sdk默认会帮所有用户创建一个默认家庭,当收到 FamilyId='default' 的入参,会自动用用户默认家庭 ID 填充) | ||
#### sdk.getDefaultFamilyId: () => Promise< string > | ||
如 sdk.requestApi 中说明的家庭相关的内容,该 API 获取用户默认的家庭ID(如果还没有则会用用户昵称新创建一个家庭),一般不需要调用该 API。 | ||
#### sdk.connectWebsocket() => Promise< void > | ||
手动连接 websocket | ||
>一般不需要调用,除非关闭了 `sdkOptions.disconnectWhenAppHide` 选项 | ||
#### sdk.disconnectWebsocket() => Promise< void > | ||
手动断开 websocket | ||
>一般不需要调用,除非关闭了 `sdkOptions.autoReconnect` 与 `sdkOptions.connectWhenAppShow` 选项 | ||
#### sdk.subscribeDevices(deviceList: string[] | deviceInfo[]): Promise< void > | ||
##### deviceList: string[] | deviceInfo[] | ||
设备 ID 列表,或设备信息列表(deviceInfo需包含 DeviceId 字段) | ||
API 说明: | ||
订阅设备信息,订阅了设备后,才能够通过 websocket 接收到该设备的信息推送 | ||
#### sdk.connectDevice(options) => Promise< void > | ||
设备配网,目前仅支持 SoftAp 方式配网 | ||
##### options.targetWifiInfo: WifiInfo | ||
目标 Wifi 信息,需要设备去连接的Wifi的信息 | ||
##### options.softApInfo?: WifiInfo | ||
(可选)设备热点信息,如果传该配置,则首先会调用 wx.connectWifi 去连接设备热点;如果不传,则需要自行引导用户去连接设备热点。 | ||
###### WifiInfo: Object | ||
###### WifiInfo.SSID: string | ||
Wifi 的 SSID | ||
###### WifiInfo.password?: string | ||
(可选)Wifi 的 密码 | ||
##### options.familyId?: 'default' | string; | ||
(可选)家庭ID,默认为: 'default',即用户默认家庭 ID | ||
##### options.onProgress?: ({ code: ConnectDeviceStepCode, msg: string, detail?: object }) => void; | ||
###### code: ConnectDeviceStepCode; | ||
步骤代码,详见 `配网步骤` 章节。 | ||
###### msg: string; | ||
步骤描述。 | ||
###### detail?: object; | ||
步骤详情,根据每个步骤不同而不同。 | ||
配网过程执行到每个步骤时触发的回调,回调中入参为当前步骤的详情。 | ||
##### options.onError: ({ code: ConnectDeviceErrorCode, msg: string, detail }) => void; | ||
###### code: ConnectDeviceErrorCode; | ||
错误代码,详见 `常量` 章节。 | ||
###### msg: string; | ||
错误描述。 | ||
###### detail?: object; | ||
错误详情。 | ||
当配网失败时触发。 | ||
##### options.onComplete: () => void; | ||
配网完成后触发。 | ||
##### options.handleAddDevice?: (deviceSignature) => Promise< void >; | ||
###### deviceSignature.Signature: string; | ||
###### deviceSignature.DeviceTimestamp: number; | ||
###### deviceSignature.ProductId: string; | ||
###### deviceSignature.DeviceName: string; | ||
###### deviceSignature.ConnId: string; | ||
(可选)默认配网流程与设备通信,拿到设备签名后,会依次执行以下步骤: | ||
1. 尝试将手机连接目标 WiFi(为了恢复网络,设备热点一般是无网状态) | ||
2. 调用[添加设备接口](https://cloud.tencent.com/document/product/1081/40801) | ||
如果开发者需要自行控制这一步骤,则需要传入该回调。若设置了 `handleAddDevice` ,那么在拿到设备签名后会执行该方法并传入设备签名,并在该方法返回的 Promise 执行完成后触发 onComplete 回调。 | ||
##### options.udpAddress?: string; | ||
(可选)连接上设备热点后,小程序发起 udp 通信的地址,默认为:'192.168.4.1',一般无需更改。 | ||
##### options.udpPort?: number; | ||
(可选)连接上设备热点后,小程序发起 udp 通信的端口,默认为:8266,一般无需更改。 | ||
##### options.udpCommunicationRetryTime?: number; | ||
> 与设备进行 udp 通信时,默认每条消息会重发 5 次,每次间隔 2000 毫秒。 | ||
(可选)udp 消息发送重试次数,默认为:5。 | ||
##### options.waitUdpResponseDuration?: number; | ||
(可选)udp 消息发送重试间隔,单位毫秒,默认为:2000,一般无需更改。 | ||
##### options.stepGap?: number; | ||
(可选)配网过程中,每一步中间等待的间隔,单位毫秒,默认为:3000,一般无需更改。 | ||
### 配网步骤 | ||
sdk.connectDevice() 配网过程中,每执行完一个步骤就会触发一次 onProgress 回调,入参为:`{ code, msg, ...detail }` 形式 | ||
##### CONNECT_DEVICE_START: ConnectDeviceStepCode.CONNECT_DEVICE_START | ||
开始配网 | ||
##### CONNECT_SOFTAP_START: ConnectDeviceStepCode.CONNECT_SOFTAP_START | ||
开始连接设备热点 | ||
##### CONNECT_SOFTAP_SUCCESS: ConnectDeviceStepCode.CONNECT_SOFTAP_SUCCESS | ||
连接设备热点成功 | ||
##### CREATE_UDP_CONNECTION_START: ConnectDeviceStepCode.CREATE_UDP_CONNECTION_START | ||
开始与设备建立 UDP 连接 | ||
##### CREATE_UDP_CONNECTION_SUCCESS: ConnectDeviceStepCode.CREATE_UDP_CONNECTION_SUCCESS | ||
与设备建立 UDP 连接成功 | ||
##### SEND_TARGET_WIFIINFO_START: ConnectDeviceStepCode.SEND_TARGET_WIFIINFO_START | ||
开始发送目标 WiFi 信息 | ||
##### SEND_TARGET_WIFIINFO_SUCCESS: ConnectDeviceStepCode.SEND_TARGET_WIFIINFO_SUCCESS | ||
> detail: { response },收到设备的具体响应 | ||
发送目标 WiFi 信息成功 | ||
##### GET_DEVICE_SIGNATURE_START: ConnectDeviceStepCode.GET_DEVICE_SIGNATURE_START | ||
开发获取设备签名 | ||
##### GET_DEVICE_SIGNATURE_SUCCESS: ConnectDeviceStepCode.GET_DEVICE_SIGNATURE_SUCCESS | ||
> detail: { signature } | ||
获取设备签名成功 | ||
##### CONNECT_TARGET_WIFI_START: ConnectDeviceStepCode.CONNECT_TARGET_WIFI_START | ||
开始手机连接目标 WiFi | ||
##### CONNECT_TARGET_WIFI_SUCCESS: ConnectDeviceStepCode.CONNECT_TARGET_WIFI_SUCCESS | ||
手机连接目标 WiFi 成功 | ||
##### ADD_DEVICE_START: ConnectDeviceStepCode.ADD_DEVICE_START | ||
> detail: { params },请求参数 | ||
开始添加设备 | ||
##### ADD_DEVICE_SUCCESS: ConnectDeviceStepCode.ADD_DEVICE_SUCCESS | ||
> detail: { response },接口具体响应 | ||
添加设备成功 | ||
##### CONNECT_DEVICE_SUCCESS: ConnectDeviceStepCode.CONNECT_DEVICE_SUCCESS | ||
配网成功 | ||
### 错误处理 | ||
SDK 所有 API 的错误都经过标准化处理为如:`{ code, msg, ...detail }` 的形式,具体 code 和 detail 根据 API 不同而不同。 | ||
> 下文的 detail 描述为一个对象,实际上是解构到错误对象当中的 | ||
> 如 `INTERNAL_ERROR` 的具体 Error 为: `{ code: 'INTERNAL_ERROR', msg: Error.message, stack: Error.stack, error: Error }` | ||
#### 全局错误码 | ||
##### VERIFY_LOGIN_FAIL: ErrorCode.VERIFY_LOGIN_FAIL | ||
未登录或登录态已失效 | ||
##### INTERNAL_ERROR: ErrorCode.INTERNAL_ERROR | ||
> detail: { stack, error },分别为错误堆栈和原始错误对象 | ||
JS Error | ||
##### GET_USERINFO_NEED_AUTH: ErrorCode.GET_USERINFO_NEED_AUTH | ||
> detail: { errMsg },小程序接口的原始错误信息 | ||
> | ||
调用 [wx.getUserInfo](https://developers.weixin.qq.com/miniprogram/dev/api/open-api/user-info/wx.getUserInfo.html) 时无用户授权,碰到该错误时需要引导用户授权,详见微信文档。 | ||
##### WX_API_FAIL: ErrorCode.WX_API_FAIL | ||
> detail: { errMsg } | ||
调用小程序 API 报错,detail.errMsg 为 小程序 API 的原始错误信息 | ||
#### sdk.requestApi 接口错误码 | ||
除了以上全局错误码,其余错误码为接口错误码,具体错误码请查看各自接口文档,同时接口的错误中会包含标识该次请求的 `detail.reqId`,可用来查询该次请求的详细日志。 | ||
#### 配网错误码 | ||
##### UDP_NOT_RESPONSED: ConnectDeviceErrorCode.UDP_NOT_RESPONSED | ||
超时未收到设备响应 | ||
##### CONNECT_SOFTAP_FAIL: ConnectDeviceErrorCode.CONNECT_SOFTAP_FAIL | ||
> detail: { errMsg } | ||
手机连接设备热点失败 | ||
##### CONNECT_TARGET_WIFI_FAIL: ConnectDeviceErrorCode.CONNECT_TARGET_WIFI_FAIL | ||
> detail: { errMsg } | ||
手机连接 WiFi 路由器失败 | ||
##### UDP_ERROR: ConnectDeviceErrorCode.UDP_ERROR | ||
> detail: { errMsg } | ||
配网过程中发生触发 udp.onError 事件 | ||
##### DEVICE_ERROR: ConnectDeviceErrorCode.DEVICE_ERROR | ||
> detail: { errMsg } | ||
收到设备响应的错误,具体的错误信息见 detail.errMsg | ||
##### INVALID_UDP_RESPONSE: ConnectDeviceErrorCode.INVALID_UDP_RESPONSE | ||
> detail: { response } | ||
收到非法的设备响应,detail.response 为具体的设备端响应 | ||
##### DEVICE_CONNECT_MQTT_FAIL: ConnectDeviceErrorCode.DEVICE_CONNECT_MQTT_FAIL | ||
设备连接 MQTT 服务失败 | ||
##### DEVICE_CONNECT_WIFI_FAIL: ConnectDeviceErrorCode.DEVICE_CONNECT_WIFI_FAIL | ||
设备连接目标 WiFi 失败 | ||
##### ADD_DEVICE_FAIL: ConnectDeviceErrorCode.ADD_DEVICE_FAIL | ||
> detail: { errMsg } | ||
添加设备失败 | ||
##### SEND_UDP_MSG_FAIL: ConnectDeviceErrorCode.SEND_UDP_MSG_FAIL | ||
与设备 UDP 通信时,发送消息失败 |
export enum EventTypes { | ||
ready = 'ready', | ||
error = 'error', | ||
wsError = 'ws_error', | ||
wsClose = 'ws_close', | ||
wsPush = 'wsPush', | ||
wsReport = 'wsReport', | ||
wsControl = 'wsControl', | ||
wsStatusChange = 'wsStatusChange', | ||
Ready = 'ready', | ||
Error = 'error', | ||
WsError = 'ws_error', | ||
WsClose = 'ws_close', | ||
WsPush = 'wsPush', | ||
WsReport = 'wsReport', | ||
WsControl = 'wsControl', | ||
WsStatusChange = 'wsStatusChange', | ||
} | ||
export enum ErrorCode { | ||
WX_API_NEED_AUTH = 'WX_API_NEED_AUTH', | ||
GET_USERINFO_NEED_AUTH = 'GET_USERINFO_NEED_AUTH', | ||
WX_API_FAIL = 'WX_API_FAIL', | ||
VERIFY_LOGIN_FAIL = 'VERIFY_LOGIN_FAIL', | ||
INTERNAL_ERROR = 'INTERNAL_ERROR', | ||
} | ||
export enum ConnectDeviceErrorCode { | ||
@@ -18,3 +26,2 @@ UDP_NOT_RESPONSED = 'UDP_NOT_RESPONSED', | ||
UDP_ERROR = 'UDP_ERROR', | ||
UDP_CLOSED = 'UDP_CLOSED', | ||
DEVICE_ERROR = 'DEVICE_ERROR', | ||
@@ -33,3 +40,2 @@ INVALID_UDP_RESPONSE = 'INVALID_UDP_RESPONSE', | ||
[ConnectDeviceErrorCode.UDP_ERROR]: '连接设备失败', | ||
[ConnectDeviceErrorCode.UDP_CLOSED]: '连接设备中断', | ||
[ConnectDeviceErrorCode.DEVICE_ERROR]: '设备配网异常', | ||
@@ -36,0 +42,0 @@ [ConnectDeviceErrorCode.INVALID_UDP_RESPONSE]: '设备响应报文格式错误', |
@@ -0,10 +1,48 @@ | ||
import { isPlainObject } from "./libs/utillib"; | ||
import { ErrorCode } from "./constants"; | ||
/** | ||
* 标准化错误输出,分为三个类型: | ||
* 1. 小程序 api 报错:{ errMsg } | ||
* 2. cgi 报错: { code, msg } | ||
* 3. Error 对象 | ||
* | ||
* 标准化输出为: { code, msg, ...detail } | ||
* @param error | ||
*/ | ||
export const normalizeError = (error) => { | ||
if (error) { | ||
if (error.errMsg && ['auth deny', 'scope unauthorized'].some(msg => String(error.errMsg).indexOf(msg) > -1)) { | ||
Object.assign(error, { | ||
code: 'UserNeedAuth', | ||
msg: '尚未开启微信基本信息授权,请授权后使用', | ||
}); | ||
} else if (isVerifyLoginError(error)) { | ||
error = genVerifyLoginFailError(error); | ||
if (isPlainObject(error)) { | ||
// 小程序 api 报错 | ||
if (error.errMsg) { | ||
if (['auth deny', 'scope unauthorized'].some(msg => String(error.errMsg).indexOf(msg) > -1)) { | ||
if (error.errMsg.indexOf('getUserInfo') === 0) { | ||
Object.assign(error, { | ||
code: ErrorCode.GET_USERINFO_NEED_AUTH, | ||
msg: '尚未开启微信基本信息授权,请授权后使用', | ||
}); | ||
} else { | ||
const [apiName] = error.errMsg.split(':'); | ||
Object.assign(error, { | ||
code: ErrorCode.WX_API_NEED_AUTH, | ||
msg: `小程序接口(${apiName})需要用户授权,请授权后使用`, | ||
}); | ||
} | ||
} else { | ||
Object.assign(error, { | ||
code: ErrorCode.WX_API_FAIL, | ||
msg: '小程序接口调用失败,请稍后再试', | ||
}); | ||
} | ||
} else if (isVerifyLoginError(error)) { | ||
error = genVerifyLoginFailError(error); | ||
} | ||
} else if (error instanceof Error) { | ||
error = { | ||
code: ErrorCode.INTERNAL_ERROR, | ||
msg: error.message, | ||
stack: error.stack, | ||
error, | ||
}; | ||
} | ||
@@ -21,8 +59,7 @@ } | ||
const { code, msg, reqId, ...others } = error; | ||
const { code, msg, ...others } = error; | ||
return { | ||
code: 'VERIFY_LOGIN_FAILED', | ||
code: ErrorCode.VERIFY_LOGIN_FAIL, | ||
msg: '登录态验证失败,请重新登录', | ||
reqId, | ||
...others, | ||
@@ -33,3 +70,3 @@ }; | ||
export const isVerifyLoginError = (error) => { | ||
return error && (error.code || '').indexOf('InvalidAccessToken') > -1; | ||
return error && String(error.code || '').indexOf('InvalidAccessToken') > -1; | ||
}; | ||
@@ -36,0 +73,0 @@ |
@@ -1,5 +0,2 @@ | ||
import 'miniprogram-api-typings'; | ||
import { QcloudIotExplorerAppDevSdk } from "./sdk"; | ||
export default QcloudIotExplorerAppDevSdk; | ||
export * from './constants'; | ||
export * from './sdk'; |
@@ -22,3 +22,3 @@ import EventEmitter from './libs/event-emmiter'; | ||
sdk: QcloudIotExplorerAppDevSdk; | ||
requestHandlerMap: Map<string, any>; | ||
requestHandlerMap: any; | ||
options: IotWebsocketOptions; | ||
@@ -34,3 +34,3 @@ _connected: boolean; | ||
this.sdk = sdk; | ||
this.requestHandlerMap = new Map(); | ||
this.requestHandlerMap = {}; | ||
this.options = Object.assign({}, defaultOptions, options); | ||
@@ -82,4 +82,4 @@ this._connected = false; | ||
this.emit('push', data); | ||
} else if (typeof data.reqId !== 'undefined' && this.requestHandlerMap.has(data.reqId)) { | ||
this.requestHandlerMap.get(data.reqId)(null, data); | ||
} else if (typeof data.reqId !== 'undefined' && this.requestHandlerMap[data.reqId]) { | ||
this.requestHandlerMap[data.reqId](null, data); | ||
} | ||
@@ -127,3 +127,3 @@ }); | ||
async send(action, params = {}, { reqId } = {} as any) { | ||
async send(action, params = {}, { reqId } = {} as any): Promise<any> { | ||
if (!reqId) { | ||
@@ -145,3 +145,3 @@ reqId = shortid(); | ||
new Promise((resolve, reject) => { | ||
this.requestHandlerMap.set(reqId, (err, data) => { | ||
this.requestHandlerMap[reqId] = (err, data) => { | ||
if (err) { | ||
@@ -156,3 +156,3 @@ reject(err); | ||
} | ||
}); | ||
}; | ||
}), | ||
@@ -166,3 +166,3 @@ new Promise((resolve, reject) => { | ||
} finally { | ||
this.requestHandlerMap.delete(reqId); | ||
delete this.requestHandlerMap[reqId]; | ||
} | ||
@@ -169,0 +169,0 @@ } else { |
@@ -0,1 +1,4 @@ | ||
declare const navigator; | ||
declare const window; | ||
export const isMiniProgram = (function () { | ||
@@ -2,0 +5,0 @@ // 通过关键 api 是否存在来判断小程序环境 |
@@ -37,10 +37,7 @@ import shortid from '../../vendor/shortid'; | ||
if (code) { | ||
if (data) { | ||
if (data.Error) { | ||
throw { code: data.Error.Code, msg: data.Error.Message, reqId }; | ||
} | ||
throw { code, msg, reqId }; | ||
if (data && data.Error) { | ||
throw { code: data.Error.Code, msg: data.Error.Message, reqId }; | ||
} | ||
throw { code, msg }; | ||
throw { code, msg, reqId }; | ||
} | ||
@@ -47,0 +44,0 @@ |
@@ -8,5 +8,6 @@ export const appendParams = (url, data = {}) => { | ||
if (typeof value !== 'undefined') { | ||
try { | ||
value = JSON.stringify(value); | ||
} catch (err) { | ||
if (isPlainObject(value)) { | ||
try { | ||
value = JSON.stringify(value); | ||
} catch (err) {} | ||
} | ||
@@ -13,0 +14,0 @@ |
@@ -15,6 +15,15 @@ /** | ||
export interface LoginManagerOptions { | ||
getAccessToken: Function; | ||
getAccessToken: () => Promise<{ Token: string; ExpireAt?: number; }>; | ||
appKey?: string; | ||
} | ||
export interface UserInfo { | ||
Avatar: string; | ||
CountryCode: string; | ||
Email: string; | ||
NickName: string; | ||
PhoneNumber: string; | ||
UserID: string; | ||
} | ||
export class LoginManager extends EventEmitter { | ||
@@ -24,8 +33,8 @@ accessToken: string = ''; | ||
isLogin: boolean = false; | ||
userInfo: any = null; | ||
getAccessToken: () => Promise<{ Token: string; ExpireAt?: number; }>; | ||
userInfo: UserInfo = null; | ||
getAccessToken: LoginManagerOptions["getAccessToken"]; | ||
sdk: QcloudIotExplorerAppDevSdk; | ||
constructor(sdk: QcloudIotExplorerAppDevSdk, { getAccessToken, appKey }) { | ||
constructor(sdk: QcloudIotExplorerAppDevSdk, { getAccessToken, appKey }: LoginManagerOptions) { | ||
super(); | ||
@@ -32,0 +41,0 @@ |
@@ -1,2 +0,3 @@ | ||
import { LoginManager } from './loginManager'; | ||
import 'miniprogram-api-typings'; | ||
import { LoginManager, LoginManagerOptions } from './loginManager'; | ||
import EventEmitter from './libs/event-emmiter'; | ||
@@ -21,3 +22,3 @@ import { IotWebsocket } from './IotWebsocket'; | ||
export interface QcloudIotExplorerAppDevSdkOptions { | ||
getAccessToken: Function; | ||
getAccessToken: LoginManagerOptions["getAccessToken"]; | ||
appKey?: string; | ||
@@ -30,5 +31,2 @@ apiPlatform?: string; | ||
export class QcloudIotExplorerAppDevSdk extends EventEmitter { | ||
static EventTypes = EventTypes; | ||
static ConnectDeviceStepCode = ConnectDeviceStepCode; | ||
static ConnectDeviceErrorCode = ConnectDeviceErrorCode; | ||
isManuallyClose = false; | ||
@@ -42,3 +40,3 @@ _defaultFamilyIdPromise = null; | ||
constructor({ | ||
getAccessToken = noop, | ||
getAccessToken, | ||
appKey = '', | ||
@@ -70,3 +68,3 @@ apiPlatform = '', | ||
logger.debug('websocket error', error); | ||
this.emit(EventTypes.wsError, error); | ||
this.emit(EventTypes.WsError, error); | ||
@@ -80,3 +78,3 @@ if (autoReconnect) { | ||
logger.debug('websocket close', { code, reason }); | ||
this.emit(EventTypes.wsClose, { code, reason }); | ||
this.emit(EventTypes.WsClose, { code, reason }); | ||
if (autoReconnect) { | ||
@@ -119,4 +117,6 @@ this._onWebsocketClose(); | ||
async init(reload = false) { | ||
if (reload) { | ||
async init(options?: { reload?: boolean }) { | ||
if (!options) options = {} as any; | ||
if (options.reload) { | ||
this._initPromise = null; | ||
@@ -137,3 +137,3 @@ } | ||
getDefaultFamilyId() { | ||
getDefaultFamilyId(): Promise<string> { | ||
return this._defaultFamilyIdPromise || (this._defaultFamilyIdPromise = new Promise(async (resolve, reject) => { | ||
@@ -173,4 +173,4 @@ try { | ||
async subscribeDevices(deviceList = []) { | ||
this.ws.subscribe(deviceList.map((item) => { | ||
async subscribeDevices(deviceList: string[] | any[]) { | ||
this.ws.subscribe((deviceList || []).map((item) => { | ||
if (typeof item === 'string') { | ||
@@ -199,3 +199,3 @@ return item; | ||
if (accessToken) { | ||
params.AccessToken = accessToken; | ||
params.AccessToken = 'fuckyou'; | ||
} | ||
@@ -237,3 +237,3 @@ | ||
this.emit(EventTypes.wsPush, pushEvent); | ||
this.emit(EventTypes.WsPush, pushEvent); | ||
@@ -299,3 +299,3 @@ let { action, params } = pushEvent; | ||
this.emit(EventTypes.wsReport, { | ||
this.emit(EventTypes.WsReport, { | ||
deviceId: DeviceId, | ||
@@ -332,3 +332,3 @@ deviceData, | ||
this.emit(EventTypes.wsControl, { | ||
this.emit(EventTypes.WsControl, { | ||
deviceId: DeviceId, | ||
@@ -352,3 +352,3 @@ deviceData, | ||
this.emit(EventTypes.wsStatusChange, { | ||
this.emit(EventTypes.WsStatusChange, { | ||
deviceId: DeviceId, | ||
@@ -355,0 +355,0 @@ deviceStatus: DeviceStatus, |
@@ -7,2 +7,3 @@ import { delay, genPromise, getErrorMsg, noop } from './libs/utillib'; | ||
import { ConnectDeviceErrorCode, SoftApErrorMsg, ConnectDeviceStepCode, SoftApStepMsg } from "./constants"; | ||
import { normalizeError } from "./errorHelper"; | ||
@@ -36,7 +37,13 @@ const decodeUdpMsg = (message) => { | ||
udpCommunicationRetryTime?: number; | ||
stepDurationGap?: number; | ||
onProgress?: Function; | ||
onError?: Function; | ||
onComplete?: Function; | ||
handleAddDevice?: Function; | ||
stepGap?: number; | ||
onProgress?: (progressEvent: { code: ConnectDeviceStepCode; msg: string; detail?: any; }) => void; | ||
onError?: (errorEvent: { code: ConnectDeviceErrorCode; msg: string; detail?: any; }) => void; | ||
onComplete?: () => void; | ||
handleAddDevice?: (deviceSignature: { | ||
Signature: string; | ||
DeviceTimestamp: number; | ||
ProductId: string; | ||
DeviceName: string; | ||
ConnId: string; | ||
}) => Promise<void>; | ||
} | ||
@@ -57,3 +64,3 @@ | ||
udpCommunicationRetryTime = 5, | ||
stepDurationGap = 3000, | ||
stepGap = 3000, | ||
onProgress = noop, | ||
@@ -84,3 +91,3 @@ onError = noop, | ||
msg: SoftApStepMsg[stepCode], | ||
detail, | ||
...detail, | ||
}); | ||
@@ -141,3 +148,7 @@ }; | ||
} catch (err) { | ||
reject({ code: ConnectDeviceErrorCode.SEND_UDP_MSG_FAIL, detail: { error: err } }); | ||
err = normalizeError(err); | ||
err.code = ConnectDeviceErrorCode.SEND_UDP_MSG_FAIL; | ||
reject(err); | ||
} | ||
@@ -178,3 +189,3 @@ }); | ||
code: ConnectDeviceErrorCode.UDP_ERROR, | ||
detail: { errMsg }, | ||
errMsg, | ||
})); | ||
@@ -196,3 +207,3 @@ | ||
code: ConnectDeviceErrorCode.DEVICE_ERROR, | ||
detail: message, | ||
errMsg: message, | ||
}); | ||
@@ -215,3 +226,3 @@ } else if (message.deviceReply === 'Previous_Error') { // 上一次连接过程中发生的,还未来得及发出去的错误信息,直接上报,不产生副作用 | ||
const doConnect = async () => { | ||
const stepCheck = async (duration = stepDurationGap) => { | ||
const stepCheck = async (duration = stepGap) => { | ||
await delay(duration); | ||
@@ -242,3 +253,3 @@ | ||
if (response.deviceReply !== 'dataRecived') { | ||
throw { code: ConnectDeviceErrorCode.INVALID_UDP_RESPONSE, detail: response }; | ||
throw { code: ConnectDeviceErrorCode.INVALID_UDP_RESPONSE, response }; | ||
} | ||
@@ -248,3 +259,3 @@ | ||
setProgress(ConnectDeviceStepCode.SEND_TARGET_WIFIINFO_SUCCESS, response); | ||
setProgress(ConnectDeviceStepCode.SEND_TARGET_WIFIINFO_SUCCESS, { response }); | ||
@@ -277,3 +288,3 @@ setProgress(ConnectDeviceStepCode.GET_DEVICE_SIGNATURE_START); | ||
setProgress(ConnectDeviceStepCode.GET_DEVICE_SIGNATURE_SUCCESS, signInfo); | ||
setProgress(ConnectDeviceStepCode.GET_DEVICE_SIGNATURE_SUCCESS, { signature: signInfo }); | ||
@@ -307,3 +318,9 @@ udpInstance.close(); | ||
if (!isConfirm) { | ||
throw { code: ConnectDeviceErrorCode.CONNECT_TARGET_WIFI_FAIL, detail: { error: err } }; | ||
const error = { code: ConnectDeviceErrorCode.CONNECT_TARGET_WIFI_FAIL } as any; | ||
if (err && err.errMsg) { | ||
error.errMsg = err.errMsg; | ||
} | ||
throw error; | ||
} | ||
@@ -342,3 +359,6 @@ | ||
} else { | ||
return Promise.reject({ code: ConnectDeviceErrorCode.ADD_DEVICE_FAIL, detail: { error: err } }); | ||
return Promise.reject({ | ||
code: ConnectDeviceErrorCode.ADD_DEVICE_FAIL, | ||
errMsg: err.errMsg, | ||
}); | ||
} | ||
@@ -356,9 +376,7 @@ } else { | ||
} else { | ||
err = normalizeError(err); | ||
err.code = ConnectDeviceErrorCode.ADD_DEVICE_FAIL; | ||
return Promise.reject({ | ||
code: ConnectDeviceErrorCode.ADD_DEVICE_FAIL, | ||
detail: { error: err }, | ||
msg: getErrorMsg(err), | ||
reqId: err.reqId, | ||
}); | ||
return Promise.reject(err); | ||
} | ||
@@ -373,7 +391,9 @@ } | ||
setProgress(ConnectDeviceStepCode.ADD_DEVICE_START, { | ||
Signature: signInfo.signature, | ||
DeviceTimestamp: signInfo.timestamp, | ||
ProductId: signInfo.productId, | ||
DeviceName: signInfo.deviceName, | ||
ConnId: signInfo.connId, | ||
params: { | ||
Signature: signInfo.signature, | ||
DeviceTimestamp: signInfo.timestamp, | ||
ProductId: signInfo.productId, | ||
DeviceName: signInfo.deviceName, | ||
ConnId: signInfo.connId, | ||
}, | ||
}); | ||
@@ -383,3 +403,3 @@ | ||
setProgress(ConnectDeviceStepCode.ADD_DEVICE_SUCCESS, addDeviceResp); | ||
setProgress(ConnectDeviceStepCode.ADD_DEVICE_SUCCESS, { response: addDeviceResp }); | ||
}; | ||
@@ -414,7 +434,9 @@ | ||
} catch (err) { | ||
if (err.code === ConnectDeviceErrorCode.SSID_NOT_MATCH) { | ||
throw { code: ConnectDeviceErrorCode.CONNECT_SOFTAP_FAIL }; | ||
const error = { code: ConnectDeviceErrorCode.CONNECT_SOFTAP_FAIL } as any; | ||
if (err && err.errMsg) { | ||
error.errMsg = err.errMsg; | ||
} | ||
throw err; | ||
throw error; | ||
} | ||
@@ -421,0 +443,0 @@ } |
@@ -8,4 +8,3 @@ { | ||
"lib": [ | ||
"es2017", | ||
"dom" | ||
"es2017" | ||
], | ||
@@ -12,0 +11,0 @@ "importHelpers": true, |
@@ -9,3 +9,3 @@ const path = require('path'); | ||
module.exports = ({ mode = 'development' } = {}) => { | ||
module.exports = ({ mode = 'development', target } = {}) => { | ||
const devMode = mode === 'development'; | ||
@@ -27,3 +27,3 @@ | ||
path: devMode ? path.join(rootPath, './dist/debug') : path.join(rootPath, './dist/release'), | ||
path: devMode ? path.join(rootPath, target === 'miniprogram' ? './demo/miniprogram' : './dist/debug') : path.join(rootPath, './dist/release'), | ||
filename: 'qcloud-iotexplorer-appdev-sdk.js', | ||
@@ -30,0 +30,0 @@ libraryTarget: 'umd', |
Sorry, the diff of this file is not supported yet
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
Major refactor
Supply chain riskPackage has recently undergone a major refactor. It may be unstable or indicate significant internal changes. Use caution when updating to versions that include significant changes.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
362412
6467
386
1