@ecoflow-api/rest-client
Version:
A rest client for the Ecoflow API for NodeJS
2 lines (1 loc) • 16.5 kB
JavaScript
var H=s=>{throw TypeError(s)};var _=(s,r,e)=>r.has(s)||H("Cannot "+e);var P=(s,r,e)=>(_(s,r,"read from private field"),e?e.call(s):r.get(s)),m=(s,r,e)=>r.has(s)?H("Cannot add the same private member more than once"):r instanceof WeakSet?r.add(s):r.set(s,e),b=(s,r,e,t)=>(_(s,r,"write to private field"),t?t.call(s,e):r.set(s,e),e),a=(s,r,e)=>(_(s,r,"access private method"),e);import{createHmac as V,randomUUID as X}from"node:crypto";function F(s,r,e){for(let t=0;t<r.length;t++)typeof r[t]=="object"?Object.assign(s,v(r[t],`${e}[${t}]`)):s[`${e}[${t}]`]=r[t]}function v(s,r=""){let e={};for(let[t,n]of Object.entries(s)){let o=Array.isArray(s)?`[${t}]`:t,C=r?`${r}.${o}`:o;typeof n=="object"&&n!==null?Array.isArray(n)?F(e,n,C):Object.assign(e,v(n,C)):e[C]=n}return e}var f,T,R,Q,A=class{constructor(r,e){m(this,R);m(this,f);m(this,T);b(this,f,r),b(this,T,e)}buildDataString(r){let e=v(r),t=[],n=Object.keys(e).sort();for(let o of n)t.push(`${o}=${e[o]}`);return t.join("&")}createSignature(r){let e=V("sha256",P(this,T)),t=Date.now().toString(),n=X(),o=a(this,R,Q).call(this,this.buildDataString(r??{}),n,t),C=e.update(o).digest("hex");return{nonce:n,timestamp:t,signature:C,accessKey:P(this,f)}}};f=new WeakMap,T=new WeakMap,R=new WeakSet,Q=function(r,e,t){let n=`accessKey=${P(this,f)}&nonce=${e}×tamp=${t}`;return r?`${r}&${n}`:n};import{certificationResponseSchema as Dt,deviceListResponseSchema as wt,errorResponseSchema as vt,quotaAllResponseSchema as At,setCommandResponseSchema as Rt}from"@ecoflow-api/schemas";var D,y,E,$,K,B=class{constructor(r){m(this,y);m(this,D);b(this,D,r)}async get(r){return a(this,y,E).call(this,r,"GET")}async post(r,e){return a(this,y,E).call(this,r,"POST",e)}async put(r,e){return a(this,y,E).call(this,r,"PUT",e)}};D=new WeakMap,y=new WeakSet,E=async function(r,e,t){let n=await fetch(r,a(this,y,$).call(this,e,t)),o=await n.json();if(n.status!==200)throw new Error(`Request failed with status ${n.status}, ${JSON.stringify(o,null,2)}`);return o},$=function(r,e){let t=P(this,D).createSignature(e),n={method:r,headers:a(this,y,K).call(this,t)};return typeof e<"u"&&(n.body=JSON.stringify(e)),n},K=function(r){return[["accessKey",r.accessKey],["timestamp",r.timestamp],["nonce",r.nonce],["sign",r.signature],["Content-Type","application/json;charset=UTF-8"]]};import{isDelta2SerialNumber as yt,isDeltaProSerialNumber as Ct,isGlacierSerialNumber as Pt,isPowerStreamSerialNumber as ft,isSmartHomePanelSerialNumber as bt,isSmartPlugSn as Tt}from"@ecoflow-api/schemas";var l=class{constructor(r,e){this.restClient=r;this.sn=e}async sendCommand(r,e){return this.restClient.setCommandPlain(e.parse(r))}async getProperties(){let r=await this.restClient.getDevicePropertiesPlain(this.sn);return this.parseProperties(r.data)}};import{isSmartPlugSn as Y,SmartPlugDeleteTimeTaskCommandSchema as Z,SmartPlugIndicatorBrightnessCommandSchema as ee,smartPlugQuotaAllSchema as te,smartPlugSwitchOnOffCommandSchema as re}from"@ecoflow-api/schemas";var w,k,N=class extends l{constructor(e,t){super(e,t);m(this,w);if(!Y(t))throw new Error("Invalid serial number for smart plug device.")}parseProperties(e){return te.parse(e)}async deleteTask(e){let t={sn:this.sn,cmdCode:"WN511_SOCKET_DELETE_TIME_TASK",params:{taskIndex:e}};return this.sendCommand(t,Z)}async setLedBrightness(e){let t={sn:this.sn,cmdCode:"WN511_SOCKET_SET_BRIGHTNESS_PACK",params:{brightness:e}};return this.sendCommand(t,ee)}async switchOn(){return a(this,w,k).call(this,1)}async switchOff(){return a(this,w,k).call(this,0)}};w=new WeakSet,k=async function(e){let t={sn:this.sn,cmdCode:"WN511_SOCKET_SET_PLUG_SWITCH_MESSAGE",params:{plugSwitch:e}};return this.sendCommand(t,re)};var L=class extends l{parseProperties(r){return r}};import{customLoadPowerSettingsSchema as ae,indicatorLightBrightnessSchema as ne,isPowerStreamSerialNumber as se,lowerChargingLevelSchema as oe,powerStreamDeleteTaskSchema as ie,powerStreamQuotaAllSchema as ce,powerSupplyPrioritySchema as me,upperChargingLevelSchema as de}from"@ecoflow-api/schemas";var I=class extends l{constructor(r,e){if(super(r,e),!se(e))throw new Error("Invalid serial number for powerStream device.")}parseProperties(r){return ce.parse(r)}async setPowerSupplyPriority(r){let t={cmdCode:"WN511_SET_SUPPLY_PRIORITY_PACK",params:{supplyPriority:{powerSupply:0,battery:1}[r]},sn:this.sn};return this.sendCommand(t,me)}async setCustomLoadPower(r){let e={cmdCode:"WN511_SET_PERMANENT_WATTS_PACK",params:{permanentWatts:r},sn:this.sn};return this.sendCommand(e,ae)}async setLowerChargingLevel(r){let e={cmdCode:"WN511_SET_BAT_LOWER_PACK",params:{lowerLimit:r},sn:this.sn};return this.sendCommand(e,oe)}async setUpperChargingLevel(r){let e={cmdCode:"WN511_SET_BAT_UPPER_PACK",params:{upperLimit:r},sn:this.sn};return this.sendCommand(e,de)}async setLedBrightness(r){let e={sn:this.sn,cmdCode:"WN511_SET_BRIGHTNESS_PACK",params:{brightness:r}};return this.sendCommand(e,ne)}async deleteTask(r){let e={sn:this.sn,cmdCode:"WN511_DELETE_TIME_TASK",params:{taskIndex:r}};return this.sendCommand(e,ie)}};import{acAlwaysOnSchema as le,acStandbyTimeSchema as he,buzzerSilentModeSchema as pe,carChargerDcSchema as ue,carChargerSwitchSchema as Se,carStandBySchema as ge,dcUsbSwitchSchema as ye,delta2QuotaAllSchema as Ce,energyManagementSchema as Pe,isDelta2SerialNumber as fe,lcdConfigSchema as be,pdStandByTime as Te,pvPrioritySchema as De}from"@ecoflow-api/schemas";var p,S,G=class extends l{constructor(e,t){super(e,t);m(this,p);if(!fe(t))throw new Error("Invalid serial number for Delta2 device.")}parseProperties(e){return Ce.parse(e)}async setCarStandByDuration(e){let t={...a(this,p,S).call(this,5),operateType:"carStandby",params:{standbyMins:e}};return this.sendCommand(t,ge)}async setSilentMode(e){let t={...a(this,p,S).call(this,5),operateType:"quietMode",params:{enabled:e}};return this.sendCommand(t,pe)}async setCarCharger(e){let t={...a(this,p,S).call(this,5),operateType:"mpptCar",params:{enabled:e}};return this.sendCommand(t,Se)}async setAcStandByTime(e){let t={...a(this,p,S).call(this,5),operateType:"standbyTime",params:{standbyMins:e}};return this.sendCommand(t,he)}async setCarInput(e){let t={...a(this,p,S).call(this,5),operateType:"dcChgCfg",params:{dcChgCfg:e}};return this.sendCommand(t,ue)}async setEnergyManagement(e){let t={...a(this,p,S).call(this,1),operateType:"watthConfig",params:e};return this.sendCommand(t,Pe)}async setDeviceTimeout(e){let t={...a(this,p,S).call(this,1),operateType:"standbyTime",params:{standbyMin:e}};return this.sendCommand(t,Te)}async enableUsbOutput(e){let t={...a(this,p,S).call(this,1),operateType:"dcOutCfg",params:{enabled:e}};return this.sendCommand(t,ye)}async setLcdTimeout(e){let t={...a(this,p,S).call(this,1),operateType:"lcdCfg",params:{delayOff:e,brightLevel:3}};return this.sendCommand(t,be)}async enablePvChargingPriority(e){let t={...a(this,p,S).call(this,1),operateType:"pvChangePrio",params:{pvChangeSet:e}};return this.sendCommand(t,De)}async setAcAutoOutConfig(e,t){let n={...a(this,p,S).call(this,1),operateType:"acAutoOutConfig",params:{acAutoOutConfig:e,minAcOutSoc:t}};return this.sendCommand(n,le)}};p=new WeakSet,S=function(e){return{moduleType:e,id:123456789,version:"1.0",sn:this.sn}};import{glacierQuotaAllSchema as we,glacierSetBatteryProtectionSchema as ve,glacierSetBuzzerCommandSchema as Ae,glacierSetBuzzerSchema as Re,glacierSetEcoModeSchema as Ee,glacierSetIceDetachingSchema as Be,glacierSetIceMakingSchema as Ne,glacierSetScreenTimeoutSchema as Le,glacierSetSensorDetectionSchema as Ie,glacierSetTemperatureSchema as Ge,glacierSetTemperatureUnitSchema as Oe,isGlacierSerialNumber as Ue}from"@ecoflow-api/schemas";var u,g,O=class extends l{constructor(e,t){super(e,t);m(this,u);if(!Ue(t))throw new Error("Invalid serial number for Glacier device.")}parseProperties(e){return we.parse(e)}async setTemperature({right:e,left:t,middle:n}){let o={...a(this,u,g).call(this),operateType:"temp",params:{tmpR:e,tmpL:t,tmpM:n}};return this.sendCommand(o,Ge)}async enableEcoMode(e){let t={...a(this,u,g).call(this),operateType:"ecoMode",params:{mode:e}};return this.sendCommand(t,Ee)}async enableBuzzer(e){let t={...a(this,u,g).call(this),operateType:"beepEn",params:{flag:e}};return this.sendCommand(t,Re)}async setBuzzerBeep(e){let t={...a(this,u,g).call(this),operateType:"beep",params:{flag:e}};return this.sendCommand(t,Ae)}async setScreenTimeout(e){let t={...a(this,u,g).call(this),operateType:"blTime",params:{time:e}};return this.sendCommand(t,Le)}async setTemperatureUnit(e){if(e!=="C"&&e!=="F")throw new Error("Invalid temperature unit. Use 'C' for Celsius or 'F' for Fahrenheit");let t={...a(this,u,g).call(this),operateType:"tmpUnit",params:{unit:e==="C"?0:1}};return this.sendCommand(t,Oe)}async setIceMaking(e,t){if(t!=="small"&&t!=="large")throw new Error("Invalid ice shape. Use 'small' or 'large'");let n={...a(this,u,g).call(this),operateType:"iceMake",params:{enable:e,iceShape:t==="small"?0:1}};return this.sendCommand(n,Ne)}async setIceDetaching(e){let t={...a(this,u,g).call(this),operateType:"deIce",params:{enable:e}};return this.sendCommand(t,Be)}async setSensorDetectionBlocking(e){let t={...a(this,u,g).call(this),operateType:"sensorAdv",params:{sensorAdv:e}};return this.sendCommand(t,Ie)}async setBatteryProtectionLevel(e,t){let n={...a(this,u,g).call(this),operateType:"protectBat",params:{level:t,state:e}};return this.sendCommand(n,ve)}};u=new WeakSet,g=function(){return{moduleType:1,id:123456789,version:"1.0",sn:this.sn}};import{isSmartHomePanelSerialNumber as Me,shpChannelCurrentConfigSchema as xe,shpChannelEnableStatusConfigSchema as _e,shpEmergencyModeSchema as ke,shpEpsModeConfigSchema as He,shpGridPowerParamConfigSchema as Qe,shpLoadChannelControlSchema as $e,shpLoadChannelInfoConfigSchema as Ke,shpPushStandbyChargeDischargeParamsSchema as ze,shpQuotaAllSchema as qe,shpRegionInfoConfigSchema as Je,shpRtcTimeUpdateSchema as je,shpScheduledChargingJobSchema as We,shpScheduledDischargingJobSchema as Fe,shpSetConfigStatusSchema as Ve,shpSplitPhaseInfoConfigSchema as Xe,shpStandbyChannelControlSchema as Ye,shpStartSelfCheckSchema as Ze}from"@ecoflow-api/schemas";var i,d,U=class extends l{constructor(e,t){super(e,t);m(this,i);if(!Me(t))throw new Error("Invalid serial number for SmartHomePanel device.")}parseProperties(e){return qe.parse(e)}async setRtcTime({sec:e,min:t,hour:n,day:o,week:C,month:J,year:j}){let W=a(this,i,d).call(this,{id:3,sec:e,min:t,hour:n,day:o,week:C,month:J,year:j});return this.sendCommand(W,je)}async setLoadChannelControl({ch:e,ctrlMode:t,sta:n}){let o=a(this,i,d).call(this,{id:16,ch:e,ctrlMode:t,sta:n});return this.sendCommand(o,$e)}async setStandbyChannelControl({ch:e,ctrlMode:t,sta:n}){let o=a(this,i,d).call(this,{id:17,ch:e,ctrlMode:t,sta:n});return this.sendCommand(o,Ye)}async setSplitPhaseInfoConfig(e){let t=a(this,i,d).call(this,{id:18,cfgList:e});return this.sendCommand(t,Xe)}async setChannelCurrentConfiguration({channel:e,cur:t}){let n=a(this,i,d).call(this,{id:20,chNum:e,cur:t});return this.sendCommand(n,xe)}async setGridPowerConfiguration({gridVol:e,gridFreq:t}){let n=a(this,i,d).call(this,{id:22,gridVol:e,gridFreq:t});return this.sendCommand(n,Qe)}async enableEpsMode(e){let t=a(this,i,d).call(this,{id:24,eps:e});return this.sendCommand(t,He)}async enableChannelStatus({channel:e,enable:t}){let n=a(this,i,d).call(this,{id:26,isEnable:t,chNum:e});return this.sendCommand(n,_e)}async setLoadChannelInfo({channel:e,channelName:t,iconInfo:n}){let o=a(this,i,d).call(this,{id:32,chNum:e,info:{chName:t,iconInfo:n}});return this.sendCommand(o,Ke)}async setRegionInfo(e){let t=a(this,i,d).call(this,{id:34,area:e});return this.sendCommand(t,Je)}async setEmergencyMode({isCfg:e,backupMode:t,overloadMode:n,chSta:o}){let C=a(this,i,d).call(this,{id:64,isCfg:e,backupMode:t,overloadMode:n,chSta:o});return this.sendCommand(C,ke)}async setScheduledChargingJob({cfgIndex:e,cfg:t}){let n=a(this,i,d).call(this,{id:81,cfgIndex:e,cfg:t});return this.sendCommand(n,We)}async setScheduledDischargingJob({cfgIndex:e,cfg:t}){let n=a(this,i,d).call(this,{id:82,cfgIndex:e,cfg:t});return this.sendCommand(n,Fe)}async setConfigurationStatus(e){let t=a(this,i,d).call(this,{id:7,cfgSta:e});return this.sendCommand(t,Ve)}async setStartSelfCheck(e){let t=a(this,i,d).call(this,{id:112,selfCheckType:e});return this.sendCommand(t,Ze)}async setStandByChargingDischargingParameters({discLower:e,forceChargeHigh:t}){let n=a(this,i,d).call(this,{id:29,discLower:e,forceChargeHigh:t});return this.sendCommand(n,ze)}};i=new WeakSet,d=function(e){return{sn:this.sn,operateType:"TCP",params:{cmdSet:11,...e}}};import{deltaProQuotaAllSchema as et,deltaProSetACChargingSchema as tt,deltaProSetACStandbyTimeSchema as rt,deltaProSetBeepSchema as at,deltaProSetBypassACAutoStartSchema as nt,deltaProSetCarChargerSchema as st,deltaProSetCarInputCurrentSchema as ot,deltaProSetChargeLevelSchema as it,deltaProSetDischargeLevelSchema as ct,deltaProSetPVChargingSchema as mt,deltaProSetScreenBrightnessSchema as dt,deltaProSetScreenTimeoutSchema as lt,deltaProSetSmartGeneratorAutoOffSchema as ht,deltaProSetSmartGeneratorAutoOnSchema as pt,deltaProSetUnitTimeoutSchema as ut,deltaProSetXBoostSchema as St,isDeltaProSerialNumber as gt}from"@ecoflow-api/schemas";var c,h,M=class extends l{constructor(e,t){super(e,t);m(this,c);if(!gt(t))throw new Error("Invalid serial number for Delta Pro device.")}parseProperties(e){return et.parse(e)}async enableXboost(e,t){let n=a(this,c,h).call(this,{id:66,enabled:e,xboost:t});return this.sendCommand(n,St)}async enableCharger(e){let t=a(this,c,h).call(this,{id:81,enabled:e});return this.sendCommand(t,st)}async setChargeLevel(e){let t=a(this,c,h).call(this,{id:49,maxChgSoc:e});return this.sendCommand(t,it)}async setDischargeLevel(e){let t=a(this,c,h).call(this,{id:51,minDsgSoc:e});return this.sendCommand(t,ct)}async setCarInput(e){let t=a(this,c,h).call(this,{id:71,currMa:e});return this.sendCommand(t,ot)}async enableBeep(e){let t=a(this,c,h).call(this,{id:38,enabled:e});return this.sendCommand(t,at)}async setScreenBrightness(e){let t=a(this,c,h).call(this,{id:39,lcdBrightness:e});return this.sendCommand(t,dt)}async setSmartGeneratorAutoOnThreshold(e){let t=a(this,c,h).call(this,{id:52,openOilSoc:e});return this.sendCommand(t,pt)}async setSmartGeneratorAutoOffThreshold(e){let t=a(this,c,h).call(this,{id:53,closeOilSoc:e});return this.sendCommand(t,ht)}async setUnitTimeout(e){let t=a(this,c,h).call(this,{id:33,standByMode:e});return this.sendCommand(t,ut)}async setScreenTimeout(e){let t=a(this,c,h).call(this,{id:39,lcdTime:e});return this.sendCommand(t,lt)}async setAcStandbyTime(e){let t=a(this,c,h).call(this,{id:153,standByMins:e});return this.sendCommand(t,rt)}async setAcChargingPower(e){let t=a(this,c,h).call(this,{id:69,slowChgPower:e});return this.sendCommand(t,tt)}async setPvChargingType(e){let t=a(this,c,h).call(this,{id:82,chgType:e});return this.sendCommand(t,mt)}async enableAcAutoStartBypass(e){let t=a(this,c,h).call(this,{id:84,enabled:e});return this.sendCommand(t,nt)}};c=new WeakSet,h=function(e){return{sn:this.sn,params:{cmdSet:32,...e}}};function z(s,r){return Tt(s)?new N(r,s):ft(s)?new I(r,s):yt(s)?new G(r,s):Pt(s)?new O(r,s):bt(s)?new U(r,s):Ct(s)?new M(r,s):new L(r,s)}var x={deviceList:"/iot-open/sign/device/list",deviceQuota:"/iot-open/sign/device/quota/all",setCmd:"/iot-open/sign/device/quota",certification:"/iot-open/sign/certification"},q=class{constructor(r){let e=t=>`${r.host}${t}`;this.requestHandler=new B(new A(r.accessKey,r.secretKey)),this.restApiHost=r.host,this.deviceListUrl=e(x.deviceList),this.deviceQuotaUrl=e(x.deviceQuota),this.setCmdUrl=e(x.setCmd),this.certificationUrl=e(x.certification)}parseResponse(r,e){let t=vt.safeParse(r);if(t.success)throw new Error(`code: ${t.data.code} | message: ${t.data.message}`);return e.parse(r)}async getMqttCredentials(){let r=this.parseResponse(await this.requestHandler.get(this.certificationUrl),Dt),{port:e}=r.data;return{...r.data,port:parseInt(e)}}async getDevicesPlain(){return this.parseResponse(await this.requestHandler.get(this.deviceListUrl),wt)}async getSerialNumbers(){return(await this.getDevicesPlain()).data.map(({sn:e})=>e)}async setCommandPlain(r){return this.parseResponse(await this.requestHandler.put(this.setCmdUrl,r),Rt)}async getDevicePropertiesPlain(r){return At.parse(await this.requestHandler.get(`${this.deviceQuotaUrl}?sn=${r}`))}getDevice(r){return z(r,this)}async getDevices(){return(await this.getDevicesPlain()).data.map(({sn:e})=>this.getDevice(e))}};export{q as RestClient};