import { Injectable } from '@angular/core'; import { MQTTEntity } from '../_models/mqtt_base'; import { GeneratorService } from './generator.service'; @Injectable({ providedIn: 'root', }) export class OutputService { constructor(private generatorService: GeneratorService) {} basecode: {} = { 'mqtt-init': '{testestsdsdf}' }; output: boolean = false; _integrated_output: boolean = false; _device_entity_cached: { entity: MQTTEntity; listlen: number } = { entity: new MQTTEntity(), listlen: 0, }; get device_entity(): MQTTEntity { if ( this._device_entity_cached.listlen === this.generatorService.created_entity_num ) return this._device_entity_cached.entity; let entites = Array.from(this.generatorService.created_enteties).sort( (a, b) => { return a.size - b.size; } ); this._device_entity_cached = { entity: entites[0], listlen: this.generatorService.created_entity_num, }; console.log('sizing'); console.log(this._device_entity_cached); return entites[0]; } get seperate_outputs(): boolean { return this.output && !this._integrated_output; } get integrated_output(): boolean { return this.output && this._integrated_output; } set integrated_output(value: boolean) { this._integrated_output = value; } getDiscoveryString(entity: MQTTEntity, escaped = false): string | {} { let str = entity.toJSON(); if (this.generatorService.use_device) { str['dev'] = this.generatorService.device.toJSON( entity.uniq_id == this.device_entity.uniq_id ); } if (escaped) { return JSON.stringify(str).replaceAll('"', '\\"'); } return str; } getDiscoveryTopic(entity: MQTTEntity): string { return join( '/', 'homeassistant', entity.ent_type, entity.display_name, 'config' ).toLowerCase(); } integrateCode(): string { let mqtt_init = '#include \n\nEspMQTTClient mqtt(\n\t"wifi_name",\n\t"wifi_pw",\n\t"broker_ip",\n\t"mqtt_acc",\n\t"mqtt_pw",\n\t"device_name",\n\t"mqtt_port"\n);\n'; let setup = 'void setup(){\nclient.setMaxPacketSize(512);\n}\n'; let onConnectStart = 'void onConnectionEstablished() {\n\tdelay=10\n'; let onConnectEnd = '\tmqtt.loop()\n}\n'; let loop = 'void loop() {\n\tmqtt.loop();\n\tdelay(100);\n}'; let discoveryMsg: string[] = []; let publishTopics: string[] = []; for (let [index, entity] of Array.from( this.generatorService.created_enteties ).entries()) { discoveryMsg.push('\t// Sending discovery for Entity ' + index); discoveryMsg.push( `\tmqtt.publish(${this.getDiscoveryTopic( entity )}, ${this.getDiscoveryString(entity, true)}, true);\n` ); publishTopics.push(...entity.publish_topics(index)); publishTopics.push(); } publishTopics.push('\n'); return ( mqtt_init + '\n' + publishTopics.join('\n') + setup + onConnectStart + discoveryMsg.join('\n') + onConnectEnd + loop ); } } function join(seperator = '/', first: string, ...args: string[]): string { let result = ''; for (let str of args) { if (str == '') continue; result += seperator + str; } if (first == '') return result.slice(1); return first + result; }