53 lines
2.2 KiB
JavaScript
53 lines
2.2 KiB
JavaScript
const { InfluxDB, Point } = require('@influxdata/influxdb-client');
|
|
const axios = require('axios');
|
|
|
|
const token = process.env.INFLUX_TOKEN;
|
|
const url = process.env.INFLUX_URL;
|
|
const org = process.env.DOCKER_INFLUXDB_INIT_ORG;
|
|
const bucket = process.env.DOCKER_INFLUXDB_INIT_BUCKET;
|
|
|
|
const client = new InfluxDB({ url, token });
|
|
const writeApi = client.getWriteApi(org, bucket);
|
|
|
|
const lat = 51.58;
|
|
const lon = -4.29;
|
|
const marineUrl = `https://marine-api.open-meteo.com/v1/marine?latitude=${lat}&longitude=${lon}¤t=swell_wave_height,swell_wave_period,swell_wave_direction,wind_wave_height`;
|
|
const weatherUrl = `https://api.open-meteo.com/v1/forecast?latitude=${lat}&longitude=${lon}¤t=wind_speed_10m,wind_direction_10m`;
|
|
|
|
async function fetchSurfData() {
|
|
try {
|
|
const [marineRes, weatherRes] = await Promise.all([
|
|
axios.get(marineUrl),
|
|
axios.get(weatherUrl)
|
|
]);
|
|
|
|
const currentSwell = marineRes.data.current;
|
|
const currentWind = weatherRes.data.current;
|
|
|
|
const point = new Point('surf_conditions')
|
|
.tag('location', 'rhossili_beach')
|
|
.floatField('swell_height', currentSwell.swell_wave_height)
|
|
.floatField('swell_period', currentSwell.swell_wave_period)
|
|
.floatField('swell_direction', currentSwell.swell_wave_direction)
|
|
.floatField('wind_speed', currentWind.wind_speed_10m)
|
|
.floatField('wind_direction', currentWind.wind_direction_10m);
|
|
|
|
writeApi.writePoint(point);
|
|
await writeApi.flush();
|
|
console.log(`✅ Success: Captured ${currentSwell.swell_wave_height}m swell and ${currentWind.wind_speed_10m}km/h wind.`);
|
|
} catch (error) {
|
|
// If it's a connection error, let's be descriptive
|
|
if (error.code === 'ECONNREFUSED') {
|
|
console.error("❌ Database is not ready yet. Retrying in the next cycle...");
|
|
} else {
|
|
console.error("❌ Fetch error:", error.message);
|
|
}
|
|
}
|
|
}
|
|
|
|
// 10 second delay for the very first run to let InfluxDB boot up
|
|
console.log("⏳ Fetcher started. Waiting 10s for DB initialization...");
|
|
setTimeout(fetchSurfData, 10000);
|
|
|
|
// Then run every hour
|
|
setInterval(fetchSurfData, 1000 * 60 * 60); |