surf-hub/fetcher/index.js
GeorgeWebberley 0554841ee3
All checks were successful
ci/woodpecker/push/woodpecker Pipeline was successful
Fixed script by removing tidal data
2026-01-28 12:57:53 +01:00

78 lines
3 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`;
const weatherUrl = `https://api.open-meteo.com/v1/forecast?latitude=${lat}&longitude=${lon}&current=wind_speed_10m,wind_direction_10m`;
async function fetchSurfData() {
try {
console.log("🌊 Fetching latest surf conditions...");
const [marineRes, weatherRes] = await Promise.all([
axios.get(marineUrl),
axios.get(weatherUrl),
]);
const swell = marineRes.data.current;
const wind = weatherRes.data.current;
const finalScore = getSurfScore(swell, wind);
const point = new Point('surf_conditions')
.tag('location', 'llangennith_beach')
.floatField('swell_height', swell.swell_wave_height)
.floatField('swell_period', swell.swell_wave_period)
.floatField('swell_direction', swell.swell_wave_direction)
.floatField('wind_speed', wind.wind_speed_10m)
.floatField('wind_direction', wind.wind_direction_10m)
.intField('surf_score', finalScore);
writeApi.writePoint(point);
await writeApi.flush();
console.log(`✅ Success! Score: ${finalScore}/10 | Swell: ${swell.swell_wave_height}m @ ${swell.swell_wave_period}s | Wind: ${wind.wind_speed_10m}km/h`);
} catch (error) {
if (error.code === 'ECONNREFUSED') {
console.error("❌ Database is not ready yet. Retrying in the next cycle...");
} else if (error.response) {
console.error("❌ API Error:", error.response.status, error.response.data);
} else {
console.error("❌ Error:", error.message);
}
}
}
function getSurfScore(swell, wind) {
let score = 5;
if (swell.swell_wave_height < 0.5) return 1;
if (swell.swell_wave_period >= 9 && swell.swell_wave_period <= 13) score += 2;
else if (swell.swell_wave_period > 13) score += 1;
else if (swell.swell_wave_period < 7) score -= 2;
const isOffshore = wind.wind_direction_10m >= 70 && wind.wind_direction_10m <= 110;
const isOnshore = wind.wind_direction_10m > 190 || wind.wind_direction_10m < 20;
if (isOffshore) {
score += 3;
} else if (isOnshore && wind.wind_speed_10m > 12) {
score -= 4;
}
return Math.max(1, Math.min(10, score));
}
console.log("⏳ Fetcher started. Waiting 10s for DB initialization...");
setTimeout(fetchSurfData, 10000);
setInterval(fetchSurfData, 1000 * 60 * 60);