/**
 * Minified by jsDelivr using Terser v5.39.0.
 * Original file: /npm/iobroker.mielecloudservice@6.5.12/main.js
 *
 * Do NOT use SRI with dynamically generated files! More information: https://www.jsdelivr.com/using-sri-with-dynamic-files
 */
"use strict";const utils=require("@iobroker/adapter-core"),{EventSource:EventSource}=require("eventsource"),mieleTools=require("./source/mieleTools.js"),mieleConst=require("./source/mieleConst"),timeouts={},fakeRequests=!1;let events,auth,connectionErrorHandlingInProgress=!1;class Mielecloudservice extends utils.Adapter{constructor(e){super({...e,name:"mielecloudservice"}),this.on("ready",this.onReady.bind(this)),this.on("stateChange",this.onStateChange.bind(this)),this.on("unload",this.onUnload.bind(this))}getEventSource(){const e=new EventSource(mieleConst.BASE_URL+mieleConst.ENDPOINT_EVENTS,{fetch:(e,t)=>fetch(e,{...t,headers:{Authorization:`Bearer ${auth.access_token}`,Accept:"text/event-stream","Accept-Language":this.config.locale,"User-Agent":mieleConst.UserAgent}})});return e.sseErrors=0,e}doSSEErrorHandling(e,t){if(connectionErrorHandlingInProgress)e.log.info("SSE connection error handling already in progress.");else{connectionErrorHandlingInProgress=!0;try{switch(t.readyState){case 0:for(e.log.info("SSE is trying to reconnect but it seems this won't work. So trying myself by closing and reinitializing."),t.close();0===t.readyState;){const i=1e3*Math.pow(t.sseErrors,2)+Math.floor(1e3*Math.random());timeouts.getEvents=setTimeout((()=>{e.initSSE(),e.log.info("Still trying to connect...")}),i)}break;case 1:e.log.info("SSE connection is still open or open again. Doing nothing.");break;case 2:e.log.info("SSE connection has been closed. Trying to reinitialize."),e.initSSE();break;default:e.log.warn(`SSE readyState should be [0,1,2] but has an illegal state(${t.readyState}).`)}}finally{connectionErrorHandlingInProgress=!1}}}initSSE(){events=this.getEventSource(),events.onopen=()=>{this.log.info(`Server Sent Events-Connection has been ${0===events.sseErrors?"established":"reestablished"} @Miele-API.`),this.setState("info.connection",!0,!0),events.sseErrors=0},events.addEventListener(mieleConst.DEVICES,(e=>{this.log.debug(`Received DEVICES message by SSE: [${JSON.stringify(e)}]`),mieleTools.splitMieleDevices(this,auth,JSON.parse(e.data)).catch((e=>{this.log.warn(`splitMieleDevices crashed with error: [${e}]`)}))})),events.addEventListener(mieleConst.ACTIONS,(e=>{this.log.debug(`Received ACTIONS message by SSE: [${JSON.stringify(e)}]`),mieleTools.splitMieleActionsMessage(this,JSON.parse(e.data)).catch((e=>{this.log.warn(`splitMieleActionsMessage crashed with error: [${e}]`)}))})),events.addEventListener(mieleConst.PING,(e=>{this.log.debug(`Received PING message by SSE: ${JSON.stringify(e)}`),auth.ping=new Date})),events.addEventListener(mieleConst.ERROR,(e=>{events.sseErrors++,this.setState("info.connection",!1,!0),this.log.debug(`Received error message by SSE: ${JSON.stringify(e)}`);const t=1e3*Math.pow(events.sseErrors,2)+Math.floor(1e3*Math.random());Object.prototype.hasOwnProperty.call(timeouts,"reconnectDelay")&&clearTimeout(timeouts.reconnectDelay),this.log.warn(`An ${void 0!==e.message?`error (#${events.sseErrors}) occurred (${e.message})`:"undefined error occurred"}. Handling it in ${t/1e3} seconds to give it a chance to solve itself.`),timeouts.reconnectDelay=setTimeout(((i,s)=>{e.reconnectInterval=t,this.doSSEErrorHandling(i,s)}),t,this,events)}))}doDataPolling(e,t){timeouts.datapolling=setInterval((async function(){const i=await mieleTools.refreshMieleDevices(e,t).catch((t=>{e.log.info(`Devices-Error: ${JSON.stringify(t)}`)}));t.ping=new Date,mieleTools.splitMieleDevices(e,t,i).catch((t=>{e.log.warn(`splitMieleDevices crashed with error: [${t}]`)})),timeouts.actionsDelay=setTimeout((async function(){const i=mieleTools.getKnownDevices(),s=Object.keys(i);e.log.debug(0===s.length?"There are no known devices; No actions to query":`There are ${s.length} known devices; querying actions for them.`);for(let o=0;o<s.length;o++){e.log.debug(`Querying device ${i[s[o]].name}`);const n=await mieleTools.refreshMieleActions(e,t,i[s[o]].API_ID).catch((t=>{e.log.info(`Actions-Error: ${JSON.stringify(t)}`)}));e.log.debug(`Actions: ${JSON.stringify(n)}`),mieleTools.splitMieleActionsMessage(e,n).catch((t=>{e.log.warn(`splitMieleActionsMessage crashed with error: [${t}]`)}))}}),1e3)}),e.config.pollInterval*e.config.pollUnit*1e3)}async onReady(){await this.setState("info.connection",!1,!0);try{await mieleTools.checkConfig(this,this.config).then((async()=>{auth=await mieleTools.getAuth(this,this.config,1).catch((e=>{this.terminate(e,11)}))})).catch((()=>{this.terminate("Terminating adapter due to invalid configuration.",11)})),auth&&(timeouts.authCheck=setInterval((async()=>{this.log.debug("Testing whether auth token is going to expire within the next 24 hours."),mieleTools.authHasExpired(auth)&&(auth=await mieleTools.refreshAuthToken(this,this.config,auth).catch((e=>{"string"==typeof e?this.terminate(e):(this.log.error(JSON.stringify(e)),this.terminate("Terminating adapter due to invalid auth token."))})))}),mieleConst.AUTH_CHECK_TIMEOUT,this,this.config),this.config.sse?(this.log.info("Registering for all appliance events at Miele API."),this.initSSE(),this.log.info("Initializing SSE watchdog."),timeouts.watchdog=setInterval((()=>{(new Date).getTime()-auth.ping.getTime()>=mieleConst.WATCHDOG_TIMEOUT&&(this.log.info("Watchdog detected ping failure. Last ping occurred over a minute ago. Trying to handle."),this.setState("info.connection",!1,!0),events.close(),this.initSSE())}),mieleConst.WATCHDOG_TIMEOUT)):(this.log.info(`Requesting data from Miele API using time based polling every ${this.config.pollInterval*this.config.pollUnit} Seconds.`),this.doDataPolling(this,auth)))}catch(e){this.log.error(e)}}async onUnload(e){try{this.unsubscribeObjects("*"),this.unsubscribeStates("*"),await this.setState("info.connection",!1,!0);for(const[e]of Object.entries(timeouts))this.log.debug(`Clearing ${e} interval.`),clearInterval(timeouts[e]);events.close(),auth&&await mieleTools.APILogOff(this,auth,"access_token"),e()}catch(t){this.log.error(`Error during unload: ${t.message} - ${t.stack}`),e()}}async onStateChange(e,t){if(t)if(t.ack)"Power"===e.split(".").pop()&&t.val&&await mieleTools.addProgramsToDevice(this,auth,e.split(".",3).pop());else{this.log.debug(`state ${e} changed: ${t.val} (ack = ${t.ack})`);const i={};let s;const o=e.split(".").pop(),n=e.split(".",3).pop();switch(s=mieleConst.ENDPOINT_ACTIONS.replace("LANG",this.config.locale),o){case"Nickname":i.deviceName=t.val;break;case"Start":i.processAction=mieleConst.START;break;case"Stop":i.processAction=mieleConst.STOP;break;case"Pause":i.processAction=mieleConst.PAUSE;break;case"SuperFreezing":i.processAction=t.val?mieleConst.START_SUPERFREEZING:mieleConst.STOP_SUPERFREEZING;break;case"SuperCooling":i.processAction=t.val?mieleConst.START_SUPERCOOLING:mieleConst.STOP_SUPERCOOLING;break;case"startTime":i.startTime="string"==typeof t.val?t.val.split(":"):[0,0];break;case"VentilationStep":i.ventilationStep=t.val;break;case"targetTemperatureZone-1":case"targetTemperatureZone-2":case"targetTemperatureZone-3":i.targetTemperature=[{zone:o.split("-").pop(),value:t.val}];break;case"Color":i.colors=t.val;break;case"Mode":i.modes=t.val;break;case"Light":i.light=t.val?1:2;break;case"Power":t.val?i.powerOn=!0:i.powerOff=!0;break;case"LastActionResult":break;default:i.programId="string"==typeof o?Number.parseInt(o):0,s=mieleConst.ENDPOINT_PROGRAMS.replace("LANG",this.config.locale)}await mieleTools.executeAction(this,auth,s,n,i).then((()=>{this.setState(`${n}.ACTIONS.LastActionResult`,"Okay!",!0)})).catch((e=>{this.setState(`${n}.ACTIONS.LastActionResult`,e,!0)}))}else this.log.info(`state ${e} deleted`)}}require.main!==module?module.exports=e=>new Mielecloudservice(e):new Mielecloudservice;
//# sourceMappingURL=/sm/19391d00f7ca41801f0df94ab5637e7a2276acd0dd983ab3fa5386e5dae1a685.map