surf-hub/fetcher/index.js
GeorgeWebberley 7704532aa9
All checks were successful
ci/woodpecker/push/woodpecker Pipeline was successful
Added wind data
2026-01-28 11:24:38 +01:00

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}&current=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}&current=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);