-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
276 lines (235 loc) · 11.4 KB
/
index.js
File metadata and controls
276 lines (235 loc) · 11.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
const express = require('express');
const axios = require('axios');
const cheerio = require('cheerio');
const https = require('https');
const app = express();
// --- CONSTANTES PARA AYSA ---
const UUID_BERNAL = 'B8046881-1BC3-43F8-9C9B-841AC482CF85';
const UUID_BERAZATEGUI = '5FFBD91B-1EBA-49CE-9AFA-2129F9397D22';
const BASE_API_URL_AYSA = 'https://www.aysa.com.ar/api/estaciones/getVariablesEstacionesHistorico';
// --- FUNCIONES PARA AYSA (API JSON) ---
// Helper function to fetch JSON data from a URL
async function fetchJsonData(url) {
const agent = new https.Agent({ rejectUnauthorized: false });
try {
console.log(`[Aysa] Fetching data from: ${url}`);
const response = await axios.get(url, {
httpsAgent: agent,
timeout: 15000,
headers: {
'User-Agent': 'Mozilla/5.0 (Scraping Script)'
}
});
console.log(`[Aysa] Data fetched successfully from: ${url}`);
return response.data;
} catch (error) {
console.error(`[Aysa] Error fetching data from ${url}:`, error.message);
throw error;
}
}
// Function to extract wind data for an Aysa station from the JSON API response
function extractWindDataAysa(apiData, stationName = 'Desconocida') {
console.log(`[Aysa] Procesando datos para la estación: ${stationName}...`);
try {
if (!apiData || typeof apiData !== 'object') {
return { error: "Formato de datos de la API inesperado.", estacion: stationName };
}
if (!apiData.estacion || !apiData.variables || !apiData.fechaMedicion) {
return { error: "Formato de datos de la API incompleto.", estacion: stationName };
}
const estacionUUID = apiData.estacion;
const variables = apiData.variables;
const fechaMedicion = apiData.fechaMedicion;
let velocidadViento = null;
let rafagaViento = null;
let direccionViento = null;
if (Array.isArray(variables.VelocidadViento) && variables.VelocidadViento.length > 0) {
const ultimoValorViento = variables.VelocidadViento[variables.VelocidadViento.length - 1];
velocidadViento = ultimoValorViento !== null ? parseFloat(ultimoValorViento) : null;
}
if (Array.isArray(variables.RafagaViento) && variables.RafagaViento.length > 0) {
const ultimoValorRafaga = variables.RafagaViento[variables.RafagaViento.length - 1];
rafagaViento = ultimoValorRafaga !== null ? parseFloat(ultimoValorRafaga) : null;
}
if (Array.isArray(variables.DireccionViento) && variables.DireccionViento.length > 0) {
direccionViento = variables.DireccionViento[variables.DireccionViento.length - 1];
}
console.log(`[Aysa] Datos extraídos para ${stationName} - Viento: ${velocidadViento}, Rafaga: ${rafagaViento}, Direccion: ${direccionViento}`);
return {
estacion: stationName,
uuid: estacionUUID,
fecha_medicion: fechaMedicion,
velocidad_viento: velocidadViento,
velocidad_rafaga: rafagaViento,
direccion_viento: direccionViento ? direccionViento.toString() : null // Asegurar string
};
} catch (err) {
console.error(`[Aysa] Error al procesar los datos para ${stationName}:`, err);
return { error: "Error interno al procesar los datos de la API.", estacion: stationName };
}
}
// --- FUNCIONES PARA UNLP (SCRAPING HTML) ---
// Helper function to get data from a URL (Cheerio)
async function fetchDataCheerio(url) {
const agent = new https.Agent({ rejectUnauthorized: false });
try {
console.log(`[UNLP] Fetching data from: ${url}`);
// Limpiar URL de espacios
const cleanUrl = url.trim();
const { data } = await axios.get(cleanUrl, { httpsAgent: agent, timeout: 10000 });
const $ = cheerio.load(data);
console.log(`[UNLP] Data fetched successfully from: ${cleanUrl}`);
return $;
} catch (error) {
console.error(`[UNLP] Error fetching data from ${url}:`, error.message);
throw error;
}
}
// Extract viento from torre.htm (UNLP)
function extractVientoUNLP($) {
try {
console.log(`[UNLP] Extrayendo datos de viento...`);
const $tabla = $('.variable').filter(function () {
return $(this).find('.nombre').text().trim() === 'Viento';
}).find('table.valores');
if (!$tabla.length) {
console.warn(`[UNLP] Tabla de viento no encontrada.`);
return {
velocidad_actual: null,
racha_maxima: null,
direccion: null
};
}
const velocidad_actual_text = $tabla.find('tr').eq(0).find('td').eq(1).text().trim();
const direccion_text = $tabla.find('tr').eq(1).find('td').eq(1).text().trim();
const racha_maxima_text = $tabla.find('tr').eq(3).find('td').eq(1).text().trim();
// Extraer solo el número de "XX km/h"
const velocidad_actual_match = velocidad_actual_text.match(/^(\d+(?:[.,]\d+)?)/);
const racha_maxima_match = racha_maxima_text.match(/^(\d+(?:[.,]\d+)?)/);
const velocidad_actual = velocidad_actual_match ? parseFloat(velocidad_actual_match[1].replace(',', '.')) : null;
const racha_maxima = racha_maxima_match ? parseFloat(racha_maxima_match[1].replace(',', '.')) : null;
const direccion = direccion_text || null; // Ya es texto
console.log(`[UNLP] Datos extraídos - Viento Actual: ${velocidad_actual}, Rafaga: ${racha_maxima}, Direccion: ${direccion}`);
return {
velocidad_actual,
racha_maxima,
direccion
};
} catch (err) {
console.error(`[UNLP] Error al extraer datos de viento:`, err);
return {
error: "Error al extraer datos de viento de la página UNLP."
};
}
}
// Función para adaptar el formato de UNLP al de Aysa
function adaptUNLPToAysaFormat(vientoUNLPData, stationName) {
// Asumimos una fecha/hora genérica o la obtenemos de otra parte si es crítica
// Para este ejemplo, usaremos un placeholder o intentaremos extraerla si es posible
// La página campo.htm tiene fecha/hora, pero para simplificar asumimos la actual del servidor
const now = new Date();
const fecha_medicion = now.toISOString(); // Formato ISO 8601
// Mapear nombres de campos
return {
estacion: stationName,
// uuid: null, // UNLP no tiene UUID en este contexto
fecha_medicion: fecha_medicion,
velocidad_viento: vientoUNLPData.velocidad_actual,
velocidad_rafaga: vientoUNLPData.racha_maxima,
direccion_viento: vientoUNLPData.direccion
};
}
// --- RUTA PRINCIPAL COMBINADA ---
app.get('/api/clima/combinado', async (req, res) => {
try {
console.log("Solicitando datos combinados de todas las estaciones...");
// URLs de Aysa
const urlBernal = `${BASE_API_URL_AYSA}/${UUID_BERNAL}`;
const urlBerazategui = `${BASE_API_URL_AYSA}/${UUID_BERAZATEGUI}`;
// URLs de UNLP
const campoURL = 'https://meteo.fcaglp.unlp.edu.ar/davis/campo/campo.htm';
const torreURL = 'https://meteo.fcaglp.unlp.edu.ar/davis/torre/torre.htm';
// Hacer todas las solicitudes en paralelo
const [responseBernal, responseBerazategui, responseUNLPCampo, responseUNLPTorre] = await Promise.allSettled([
fetchJsonData(urlBernal),
fetchJsonData(urlBerazategui),
fetchDataCheerio(campoURL),
fetchDataCheerio(torreURL)
]);
// --- Procesar datos de Aysa ---
let windDataBernal, windDataBerazategui;
if (responseBernal.status === 'fulfilled') {
windDataBernal = extractWindDataAysa(responseBernal.value, 'Bernal');
} else {
console.error('[Aysa] Error obteniendo datos de Bernal:', responseBernal.reason.message);
windDataBernal = { error: `Error al obtener datos de Bernal: ${responseBernal.reason.message}`, estacion: 'Bernal' };
}
if (responseBerazategui.status === 'fulfilled') {
windDataBerazategui = extractWindDataAysa(responseBerazategui.value, 'Berazategui');
} else {
console.error('[Aysa] Error obteniendo datos de Berazategui:', responseBerazategui.reason.message);
windDataBerazategui = { error: `Error al obtener datos de Berazategui: ${responseBerazategui.reason.message}`, estacion: 'Berazategui' };
}
// --- Procesar datos de UNLP ---
let windDataUNLP = { error: "Datos no disponibles", estacion: 'UNLP' };
if (responseUNLPCampo.status === 'fulfilled' && responseUNLPTorre.status === 'fulfilled') {
const $campo = responseUNLPCampo.value;
const $torre = responseUNLPTorre.value;
const vientoUNLPData = extractVientoUNLP($torre);
if (!vientoUNLPData.error) {
windDataUNLP = adaptUNLPToAysaFormat(vientoUNLPData, 'UNLP');
} else {
windDataUNLP = vientoUNLPData; // Devolver el error
}
} else {
const campoError = responseUNLPCampo.status === 'rejected' ? responseUNLPCampo.reason.message : null;
const torreError = responseUNLPTorre.status === 'rejected' ? responseUNLPTorre.reason.message : null;
console.error(`[UNLP] Error obteniendo datos: Campo: ${campoError}, Torre: ${torreError}`);
windDataUNLP = { error: `Error al obtener datos de UNLP: Campo (${campoError}), Torre (${torreError})`, estacion: 'UNLP' };
}
// --- Combinar resultados finales ---
const resultadoFinal = {
bernal: windDataBernal,
berazategui: windDataBerazategui,
unlp: windDataUNLP
};
console.log("Datos combinados obtenidos exitosamente.");
return res.json(resultadoFinal);
} catch (error) {
console.error('Error general en la ruta /api/clima/combinado:', error);
return res.status(500).json({ error: 'Error interno del servidor al obtener datos combinados de todas las estaciones.' });
}
});
// --- RUTAS INDIVIDUALES PARA AYSA ---
app.get('/api/viento/aysa/bernal', async (req, res) => {
try {
const url = `${BASE_API_URL_AYSA}/${UUID_BERNAL}`;
const apiData = await fetchJsonData(url);
const windData = extractWindDataAysa(apiData, 'Bernal');
if (windData.error) return res.status(500).json(windData);
return res.json(windData);
} catch (error) {
console.error('[Aysa/Bernal] Error en ruta individual:', error);
return res.status(500).json({ error: 'Error interno del servidor al obtener datos de Bernal.', estacion: 'Bernal' });
}
});
app.get('/api/viento/aysa/berazategui', async (req, res) => {
try {
const url = `${BASE_API_URL_AYSA}/${UUID_BERAZATEGUI}`;
const apiData = await fetchJsonData(url);
const windData = extractWindDataAysa(apiData, 'Berazategui');
if (windData.error) return res.status(500).json(windData);
return res.json(windData);
} catch (error) {
console.error('[Aysa/Berazategui] Error en ruta individual:', error);
return res.status(500).json({ error: 'Error interno del servidor al obtener datos de Berazategui.', estacion: 'Berazategui' });
}
});
// --- FIN RUTAS INDIVIDUALES PARA AYSA ---
const PORT = process.env.PORT || 3003;
app.listen(PORT, () => {
console.log(`API combinada de estaciones meteorológicas corriendo en http://localhost:${PORT}`);
console.log(` - Datos combinados: http://localhost:${PORT}/api/clima/combinado`);
console.log(` - Datos de viento Aysa Bernal: http://localhost:${PORT}/api/viento/aysa/bernal`);
console.log(` - Datos de viento Aysa Berazategui: http://localhost:${PORT}/api/viento/aysa/berazategui`);
});