homebridge-sonnenbatterie-v2
Version:
A Homebridge plugin for a SonnenBatterie with v2 firmware.
111 lines • 3.6 kB
JavaScript
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.SonnenMQTT = void 0;
const mqtt_1 = __importDefault(require("mqtt"));
class SonnenMQTT {
client;
rootTopic;
constructor(client, rootTopic) {
this.client = client;
this.rootTopic = rootTopic;
}
connect(clientID, username, password, host, log = null) {
log?.debug("connecting... (user: ", username, "), password: (****))");
const opts = {
clientId: clientID,
rejectUnauthorized: true,
clean: true,
username: username,
password: password,
};
this.client = mqtt_1.default.connect(host, opts);
log?.debug("did connect, client...");
}
async connectAsync(clientID, username, password, host, log = null) {
log?.debug("connecting async... (user: ", username, "), password: (****)");
const opts = {
clientId: clientID,
rejectUnauthorized: true,
clean: true,
username: username,
password: password,
};
this.client = await mqtt_1.default.connectAsync(host, opts);
log?.debug("did connect, client...");
}
reconnect() {
if (this.client === null) {
return false;
}
if (this.client.connected == true) {
return true;
}
this.client = this.client.reconnect();
return this.client !== null;
}
getConnected() {
if (this.client === null) {
return false;
}
return this.client.connected;
}
getClient() {
return this.client;
}
async addSubscription(topic) {
const opts = { qos: 1 };
// qos: 1 means we want the message to arrive at least once but don't care if it arrives twice (or more
if (this.client === null) {
return null;
}
return this.client.subscribeAsync(topic, opts);
}
onMessage(callback) {
if (this.client === null) {
return false;
}
this.client.on('message', callback);
}
publish(topic, value, log) {
log?.debug("pulishing ", value, " to topic ", topic);
const stringValue = String(value);
if (stringValue === undefined) {
log?.error("cannot convert value ", value, " to string");
return;
}
if (this.client === null) {
log?.error("client is null");
const success = this.reconnect();
if (success == false) {
log?.error("reconnect failed");
}
}
const opts = {
qos: 1,
retain: false,
properties: {
messageExpiryInterval: 30
}
};
const topicValue = this.rootTopic.concat("/").concat(topic);
log?.debug("pulishing topic: ", topicValue, " << ", stringValue);
if (this.client != null) {
if (this.client.connected == false) {
log?.error("client is not connected");
}
log?.debug("publishing value: ", stringValue);
this.client.publish(topicValue, stringValue, opts);
}
}
async disconnect() {
if (this.client === null) {
return false;
}
return this.client.endAsync;
}
}
exports.SonnenMQTT = SonnenMQTT;
//# sourceMappingURL=garageclient.js.map