Skip to main content

Export site measurement data to file

The following code exmple shows how you can query all the electricity measurements at a site for given time period, and store those measurements to a local .csv file. In this particular example we store all the energy measurements at the specified site measured in a 1 day period with a 10 minute aggregation level.

import fs from 'fs'
import axios from 'axios'
import csvWriter from 'csv-write-stream'

storeSiteElectricityMeasurements(
'<INSERT_API_KEY>',
'<INSERT_SITE_ID>',
'energy',
'2023-10-01',
'2023-10-08',
'1d',
'energy_data_export.csv'
).then(() => console.log('completed'))

const storeSiteElectricityMeasurements = async(
apiKey,
siteId,
type,
from,
to,
aggregation,
filename,
) => {
let nextUrl = `https://api.sensorfact.nl/v1/sites/${siteId}/electricity/measurements/assets?from=${from}&to=${to}&measurement_type=${type}&aggregation=${aggregation}`

while (nextUrl) {
const response = await axios.get(nextUrl, {headers: {'x-api-key': apiKey}})
const { data } = response.data

await writeMeasurements(type, data, filename)
nextUrl = response.data.paging?.next ?? null
}
}

const writeMeasurements = async(type, assets, filename) => {
const writer = !fs.existsSync(filename)
? csvWriter({ headers: ['asset_id', 'type', 'unit', 'timestamp', 'value']})
: csvWriter({sendHeaders: false});

writer.pipe(fs.createWriteStream(file, {flags: 'a'}))

const rows = assets.flatMap(asset => asset.measurements.map(measurement => ({
asset_id: asset.id,
type,
unit: asset.unit,
timestamp: measurement.time,
value: measurement.value
})))

for (const row of rows) {
writer.write(row)
}

writer.end()
}