Commit 2263309b by Alex

Backend añadido

parent 11a81b86
import { Component, OnInit, OnDestroy } from '@angular/core';
import { Component, OnInit, OnDestroy, ViewChild, output } from '@angular/core';
import { MatDialog } from '@angular/material/dialog';
import { MqttService, IMqttMessage } from 'ngx-mqtt';
import { Subscription, interval } from 'rxjs';
import { startWith, switchMap } from 'rxjs/operators';
import { CrearPedidoDialogComponent } from './crear-pedido-dialog/crear-pedido-dialog.component';
import { MapaComponent } from './mapa/mapa.component'; // Importa MapaComponent
import { BackendService } from './backend.service';
@Component({
selector: 'app-root',
......@@ -15,8 +17,11 @@ export class AppComponent implements OnInit, OnDestroy {
private subscription: Subscription = new Subscription(); //Variable para suscribirse a un topic
private publishInterval: Subscription = new Subscription(); //Variable para publicar datos cada 10 segundos
message: string = ''; //Variable para mostrar el mensaje MQTT
@ViewChild(MapaComponent) mapaComponent!: MapaComponent;
constructor(public dialog: MatDialog, private mqttService: MqttService) {}
constructor(public dialog: MatDialog, private mqttService: MqttService, private backendService:BackendService) {}
ngOnInit() {
this.subscribeToTopic(); //Nos suscribimos al inicializar la aplicación
this.startPublishing(); //Publicamos datos cada 10 segundos
......@@ -34,9 +39,18 @@ export class AppComponent implements OnInit, OnDestroy {
*/
subscribeToTopic() {
this.subscription = this.mqttService.observe('pruebaMQTT').subscribe((data: IMqttMessage) => {
this.message = data.payload.toString(); // Convierte el contenido del mensaje a cadena.
console.log('Mensaje MQTT recibido:', this.message); // Muestra el mensaje recibido en la consola.
console.log('Conectado:');
this.subscription = this.mqttService.observe('mapa').subscribe((data: IMqttMessage) => {
const message = data.payload.toString();
console.log('Mensaje MQTT recibido:', message);
this.backendService.enviarMapa(message).then((output:string) => {
console.log('Respuesta del servidor:', output)
});
// Update mapStr in MapaComponent
this.mapaComponent.mapStr = message;
// Call ngOnInit in MapaComponent to refresh the map
this.mapaComponent.ngOnInit();
});
}
......
......@@ -10,13 +10,14 @@ import { provideAnimationsAsync } from '@angular/platform-browser/animations/asy
import { CrearPedidoDialogComponent } from './crear-pedido-dialog/crear-pedido-dialog.component';
import { MatDialogModule } from '@angular/material/dialog';
import { MqttModule, IMqttServiceOptions } from 'ngx-mqtt';
import { HttpClientModule } from '@angular/common/http';
// Configuración de MQTT
export const MQTT_SERVICE_OPTIONS: IMqttServiceOptions = {
hostname: 'broker.hivemq.com', //Nombre de host o ip
port: 8884, // Puerto de conexión
hostname: '192.168.0.45', //Nombre de host o ip
port: 9001, // Puerto de conexión
path: '/mqtt',
protocol: 'wss' // Usar 'wss' para conexiones seguras
protocol: 'ws' // Usar 'wss' para conexiones seguras
};
@NgModule({
......@@ -28,6 +29,7 @@ export const MQTT_SERVICE_OPTIONS: IMqttServiceOptions = {
CrearPedidoDialogComponent
],
imports: [
HttpClientModule,
BrowserModule,
AppRoutingModule,
MatDialogModule,
......
import { TestBed } from '@angular/core/testing';
import { BackendService } from './backend.service';
describe('BackendService', () => {
let service: BackendService;
beforeEach(() => {
TestBed.configureTestingModule({});
service = TestBed.inject(BackendService);
});
it('should be created', () => {
expect(service).toBeTruthy();
});
});
// Definir las interfaces en un archivo separado o en la parte superior de tu servicio
export interface MapResponse {
status: string;
message: string;
}
export interface Error {
status: string;
message: string;
}
export interface RouteResponse {
route: any[]; // Especifica un tipo más concreto si conoces la estructura de la ruta
duration: number;
}
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class BackendService {
private baseUrl = 'http://localhost:5000/'; // URL del servidor Flask
constructor(private http: HttpClient) { }
enviarMapa(mapa: string): Promise<any> {
const url = this.baseUrl + "procesarmapa?mapa=" + encodeURIComponent(mapa);
const response = this.http.get(url).toPromise();
console.log("Respuesta sobre el mapa" + response);
return response;
}
//todo
enviarCaminos(ruta: string,): Promise<any> {
const url = this.baseUrl + "getcaminos?actual=" + encodeURIComponent(ruta);
const response = this.http.get(url).toPromise();
console.log("Respuesta sobre la ruta" + response);
return response;
}
}
import { MapaService } from '../mapa.service';
import { Component, OnInit, Output, EventEmitter, Input } from '@angular/core';
import { BackendService } from '../backend.service';
import { MapResponse } from '../backend.service';
import { RouteResponse } from '../backend.service';
import { Error } from '../backend.service';
@Component({
......@@ -20,7 +24,7 @@ export class MapaComponent implements OnInit {
@Output() celdaSeleccionada = new EventEmitter<{ id: string, idUnico: number, row: number, col: number }>();
@Output() celdaInvalidaClickeada = new EventEmitter<void>();
mapMatrix: {id: string, idUnico: number}[][] = [];
mapStr: string = "0202000105030705000200041109060110031000000200080101100110000106010701"; // Cadena de texto que representa las casillas del mapa
mapStr: string = ""; // Cadena de texto que representa las casillas del mapa
rows: number = 7;
cols: number = 5;
SeleccionadoIdRecogida: string | null = null;
......@@ -32,7 +36,7 @@ export class MapaComponent implements OnInit {
sinConexionAbajo: string[] = ['01', '03', '06', '07', '00'];
sinConexionArriba: string[] = ['01','04', '05', '09', '00'];
constructor(private MapaService: MapaService) { }
constructor(private MapaService: MapaService,private backendService: BackendService) { }
/**
......@@ -67,8 +71,23 @@ export class MapaComponent implements OnInit {
*/
ngOnInit(): void {
this.mapMatrix = this.MapaService.creaMapaMatriz(this.mapStr, this.rows, this.cols);
//this.cargarMapa();
}
/*
enviarPedido(pedido: any): void {
this.backendService.obtenerRuta(pedido).subscribe({
next: (ruta:RouteResponse) => {
console.log('Ruta recibida del backend', ruta);
// Aquí puedes manejar la lógica para actualizar la ruta del robot o lo que sea necesario
},
error: (error:Error) => console.error('Error al obtener la ruta', error)
});
}
*/
/**
* @brief Obtiene la ruta de la imagen para un ID de bloque específico.
*
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment