UNPKG

sma-solar

Version:

http client for sma solar webconnect portal

106 lines 3.4 kB
import querystring from "querystring"; export function isSMAResponse(response) { return (typeof response === "object" && response !== null && (("err" in response && typeof response.err === "number") || "result" in response)); } export async function createClient(host, role = "", password = "") { const client = new Client(host, role, password); await client.init(); return client; } export class Client { host; role; password; port = 80; protocol = "http"; metadata = {}; codes = {}; sessionID = ""; constructor(host, role = "usr", password = "") { this.host = host; this.role = role; this.password = password; } init() { return Promise.all([ this._get("/data/ObjectMetadata_Istl.json").then((result) => { this.metadata = result; }), this._get("/data/l10n/en-US.json").then((result) => { this.codes = result; }), ]); } async _get(path, query) { return fetch(`${this.protocol}://${this.host}:${this.port}/${path.replace(/^\//, "")}?${querystring.stringify(query)}`, { method: "GET", }) .then((r) => r.json()) .then((response) => { if (response.err) { throw response; } return response; }); } async _post(path, query, data) { return fetch(`${this.protocol}://${this.host}:${this.port}/${path.replace(/^\//, "")}?${querystring.stringify(query)}`, { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify(data), }) .then((r) => r.json()) .then((response) => { if (response.err) { throw response; } return response; }); } async _postWithSession(path, query, data) { if (!this.sessionID) { await this.login(this.password, this.role); query = { ...query, sid: this.sessionID }; } return this._post(path, query, data).catch((response) => { if (!response.err) { return response; } if (response.err == 401 && this.password) { return this.login(this.password, this.role).then(() => { query = { ...query, sid: this.sessionID }; return this._post(path, query, data); }); } throw response; }); } async login(password, role = "usr") { return this._post("/dyn/login.json", undefined, { right: role || "usr", pass: password, }).then((response) => { if (!response?.result?.sid) { throw response; } this.sessionID = response.result.sid; return response?.result; }); } async getAllOnlValues(devices = []) { return this._postWithSession(`/dyn/getAllOnlValues.json`, { sid: this.sessionID }, { destDev: devices || [], }).then((response) => { if (!response?.result) { throw response; } return response?.result; }); } } //# sourceMappingURL=client.js.map