surf-hub/fetcher/index.js
GeorgeWebberley d0c8d34435
All checks were successful
ci/woodpecker/push/woodpecker Pipeline was successful
Added public view
2026-01-27 21:09:22 +01:00

51 lines
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);
async function fetchSurfData() {
try {
const lat = 51.58;
const lon = -4.29;
console.log("🌊 Fetching latest swell data...");
const url = `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 response = await axios.get(url);
const current = response.data.current;
const point = new Point('surf_conditions')
.tag('location', 'rhossili_beach')
.floatField('swell_height', current.swell_wave_height)
.floatField('swell_period', current.swell_wave_period)
.floatField('swell_direction', current.swell_wave_direction)
.floatField('wind_wave_height', current.wind_wave_height);
console.log(`📡 Data Captured: ${current.swell_wave_height}m at ${current.swell_wave_direction}°`);
// Write and explicitly flush
writeApi.writePoint(point);
await writeApi.flush();
console.log(`✅ Success! Data persisted.`);
} 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);