47 lines
1.8 KiB
JavaScript
47 lines
1.8 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 {
|
|
console.log("🌊 Fetching latest swell data...");
|
|
const response = await axios.get(`https://marine-api.open-meteo.com/v1/marine?latitude=-33.89&longitude=151.27¤t=swell_wave_height,swell_wave_period`);
|
|
|
|
const swellHeight = response.data.current.swell_wave_height;
|
|
const swellPeriod = response.data.current.swell_wave_period;
|
|
|
|
const point = new Point('surf_conditions')
|
|
.tag('location', 'local_break')
|
|
.floatField('swell_height', swellHeight)
|
|
.floatField('swell_period', swellPeriod);
|
|
|
|
console.log(`📡 Sending to InfluxDB: ${swellHeight}m...`);
|
|
|
|
// 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); |