CHANGE: added publish topic functions

This commit is contained in:
2024-08-02 07:10:09 +02:00
parent e6a49d55e2
commit 942142f517
3 changed files with 37 additions and 26 deletions

View File

@@ -1,11 +1,11 @@
import { EventEmitter, Injectable } from '@angular/core';
import { EntityService } from '../_services/entity.service';
@Injectable()
export class MQTTEntity implements iMQTTEntityBase {
protected _name: string = '';
protected _stat_t: string = 'state/topic';
protected _uniq_id: string = '';
private _size: number = 0;
attrs = new Set(['name', 'stat_t', 'uniq_id']);
topic_updates = new EventEmitter<string>();
@@ -18,7 +18,7 @@ export class MQTTEntity implements iMQTTEntityBase {
set name(name: string) {
this._name = name;
if (name == '') return;
this._uniq_id = hash(name);
this._uniq_id = name + '_' + hash(name);
this.topic_updates.next('stat_t');
}
@@ -40,16 +40,19 @@ export class MQTTEntity implements iMQTTEntityBase {
}
get display_name() {
if (this._name != '' && this._uniq_id != '') {
return this._name + '_' + this._uniq_id;
} else {
return this._name;
if (this._uniq_id != '') {
return this._uniq_id;
}
return this._name;
}
toJSON(): any {
let jsonObject: { [key: string]: string } = {};
for (let prop_name of Object.getOwnPropertyNames(this)) {
publish_topics(index: number = 1): string[] {
return [`String stat_topic_${index} = "${this.stat_t}";`];
}
toJSON(): { [key: string]: string | {} } {
let jsonObject: { [key: string]: string | {} } = {};
for (let prop_name of this.attrs.values()) {
let property = this[prop_name as keyof this];
if (property == '') continue;
jsonObject[prop_name] = String(property);
@@ -63,7 +66,7 @@ export class MQTTEntity implements iMQTTEntityBase {
}
getProperty(name: string): any {
if (!this.attrs.has(name)) return;
if (!this.attrs.has(name)) return '';
return this[name as keyof this];
}
@@ -73,13 +76,6 @@ export class MQTTEntity implements iMQTTEntityBase {
}
}
export class MQTTDevice {
name: string = '';
identifiers: string[] = ['MQTT'];
serial_number: string = '';
configuration_url: string = '';
}
export class DeviceClass {
value: number = 0;
choices: string[] = ['None'];
@@ -94,22 +90,23 @@ export class DeviceClass {
}
export interface iMQTTEntityBase {
// name: string;
// stat_t: string;
// uniq_id: string;
// display_name: string;
name: string;
stat_t: string;
uniq_id: string;
display_name: string;
attrs: Set<string>;
readonly ent_type: string;
topic_updates: EventEmitter<string>;
toJSON: () => string;
publish_topics: (index: number) => string[];
toJSON: () => { [key: string]: string | {} };
}
function hash(str: string): string {
export function hash(str: string, digits: number = 5): string {
let seed = cyrb128(str);
let rand = sfc32(seed[0], seed[1], seed[2], seed[3]);
let rand_num = Math.floor(rand() * 100000).toString();
let rand_num = Math.floor(rand() * 10 ** digits).toString();
return rand_num;
}