@constructorfleet/ultimate-govee
Version:
Library for interacting with Govee devices written in Typescript.
134 lines • 5.99 kB
JavaScript
;
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var __param = (this && this.__param) || function (paramIndex, decorator) {
return function (target, key) { decorator(target, key, paramIndex); }
};
var IoTClient_1;
Object.defineProperty(exports, "__esModule", { value: true });
exports.IoTClient = void 0;
const aws_iot_device_sdk_v2_1 = require("aws-iot-device-sdk-v2");
const common_1 = require("@nestjs/common");
const os_1 = require("os");
const iot_config_1 = require("./iot.config");
let IoTClient = IoTClient_1 = class IoTClient {
constructor(config) {
this.config = config;
this.logger = new common_1.Logger(IoTClient_1.name);
this.connected = false;
this.subscriptions = [];
}
async create(iotData, handler) {
this.logger.verbose(`Adding ${iotData.topic} to subscriptions`);
if (!this.subscriptions.includes(iotData.topic)) {
this.subscriptions.push(iotData.topic);
}
const certificateWithCA = [
iotData.certificate,
this.config.certificateAuthority,
].join(os_1.EOL);
const client = new aws_iot_device_sdk_v2_1.mqtt.MqttClient();
const connectionConfig = aws_iot_device_sdk_v2_1.iot.AwsIotMqttConnectionConfigBuilder.new_mtls_builder(certificateWithCA, iotData.privateKey)
.with_client_id(`AP/${iotData.accountId}/a${iotData.clientId}`)
.with_endpoint(iotData.endpoint)
.with_clean_session(false)
.build();
this.connection = client.new_connection(connectionConfig);
this.bindEvents(this.connection, handler);
this.logger.log('Connecting to IoT Core');
await this.connection.connect();
return this;
}
bindEvents(iotConnection, handler) {
iotConnection.on('connect', () => {
this.logger.log('Connected to AWS IoT Core');
this.subscriptions.forEach(async (topic) => {
if (topic === undefined) {
return;
}
this.logger.log(`Subscribing to ${topic}`);
await iotConnection.subscribe(topic, aws_iot_device_sdk_v2_1.mqtt.QoS.AtLeastOnce);
});
this.connected = true;
});
iotConnection.on('connection_failure', handler.onConnectionFailure
? handler.onConnectionFailure.bind(handler)
: (data) => {
this.logger.error(`Error connecting to IoT ${data.error}`);
});
iotConnection.on('connection_success', handler.onConnectionSuccess
? handler.onConnectionSuccess.bind(handler)
: (data) => {
this.logger.debug(`Successfully ${data.session_present ? 're' : ''}connected to MQTT broker.`);
});
iotConnection.on('message', (topic, payload, dup, qos, retain) => {
handler.onMessage(topic, payload, dup, qos, retain);
});
iotConnection.on('resume', (code, resumed) => {
this.logger.debug(`Connection resumed with code ${code} with ${resumed ? 'existing' : 'new'} session.`);
});
iotConnection.on('interrupt', (reason) => {
this.logger.debug(`Connection interrupted due to ${reason.error_name || reason.name}.`);
});
iotConnection.on('error', handler.onError
? handler.onError.bind(handler)
: (reason) => {
this.logger.warn('Unexpected error with connection to MQTT broker', reason, reason.error_code);
});
iotConnection.on('disconnect', () => {
this.logger.log('Disconnected from MQTT broker.');
});
iotConnection.on('closed', () => {
this.logger.log('Connection to MQTT broker closed.');
});
}
async subscribe(topic) {
if (!this.subscriptions.includes(topic)) {
this.subscriptions.push(topic);
}
if (this.connection) {
await this.connection.subscribe(topic, aws_iot_device_sdk_v2_1.mqtt.QoS.AtLeastOnce);
}
}
async publish(topic, payload) {
if (this.connection && this.connected) {
await this.connection.publish(topic, payload, aws_iot_device_sdk_v2_1.mqtt.QoS.AtLeastOnce, false);
}
}
async unsubscribe() {
if (!this.connection || !this.connected) {
return;
}
await Promise.all(this.subscriptions.map(async (sub) => await this.connection?.unsubscribe(sub)));
}
async onModuleDestroy() {
await this.disconnect();
}
async disconnect() {
if (this.connection && this.connected) {
this.connected = false;
await this.unsubscribe();
await this.connection.disconnect();
await new Promise((resolve) => {
if (this.connected === false) {
resolve();
}
});
this.connection = undefined;
}
}
};
exports.IoTClient = IoTClient;
exports.IoTClient = IoTClient = IoTClient_1 = __decorate([
(0, common_1.Injectable)(),
__param(0, (0, common_1.Inject)(iot_config_1.IoTConfig.KEY)),
__metadata("design:paramtypes", [void 0])
], IoTClient);
//# sourceMappingURL=iot.client.js.map