Help with how to build a script

Thanks for all the help so far.

I used Chat GPT to build some scripts for me.

This script returns the unit rates I’m on based on the hours of the day:

// Replace with your actual API key
const apiKey = ‘YOUR API HERE’;

// Define the product code and tariff code for Octopus Go
const productCode = ‘GO-VAR-22-10-14’;
const tariffCode = ‘E-1R-GO-VAR-22-10-14-A’;

// Define the date range for fetching tariff data
const periodFrom = new Date().toISOString();
const periodTo = new Date(Date.now() + 24 * 60 * 60 * 1000).toISOString(); // Next 24 hours

// Construct the API endpoint URL
const url = https://api.octopus.energy/v1/products/${productCode}/electricity-tariffs/${tariffCode}/standard-unit-rates/?period_from=${periodFrom}&period_to=${periodTo};

// Fetch the tariff data
fetch(url, {
headers: {
‘Authorization’: Basic ${Buffer.from(apiKey + ':').toString('base64')}
}
})
.then(response => {
if (!response.ok) {
throw new Error(Error fetching data: ${response.statusText});
}
return response.json();
})
.then(data => {
// Process and use the tariff data as needed
data.results.forEach(rate => {
console.log(Price: ${rate.value_inc_vat} p/kWh);
console.log(Valid From: ${new Date(rate.valid_from).toLocaleString()});
console.log(Valid To: ${new Date(rate.valid_to).toLocaleString()});
});
})
.catch(error => {
console.error(‘Error:’, error);
});

As you can see here:

Then this script is giving what appears to be live data, although I am not sure it is the actual data as it doesn’t match the live data I can see on Voltaware or Octopus Mini IHD

// Replace with your actual API key, MPAN, and Meter Serial Number
const apiKey = ‘YOUR API HERE’;
const mpan = ‘YOUR MPAN HERE’;
const meterSerial = ‘YOUR METER SERIAL HERE’;

// Define the date range (last 24 hours to capture recent readings)
const periodFrom = new Date(Date.now() - 24 * 60 * 60 * 1000).toISOString().split(‘.’)[0] + ‘Z’;
const periodTo = new Date().toISOString().split(‘.’)[0] + ‘Z’;

// Construct the Octopus API endpoint
const url = https://api.octopus.energy/v1/electricity-meter-points/${mpan}/meters/${meterSerial}/consumption/?period_from=${periodFrom}&period_to=${periodTo}&page_size=1;

console.log(🔍 Fetching live energy data from: ${url});

fetch(url, {
headers: {
‘Authorization’: Basic ${Buffer.from(apiKey + ':').toString('base64')}
}
})
.then(response => {
console.log(🔄 API Response Status: ${response.status} ${response.statusText});
if (!response.ok) {
return response.text().then(text => {
throw new Error(⚠️ API Error: ${response.statusText} (Code: ${response.status}) - ${text});
});
}
return response.json();
})
.then(async (data) => {
if (data.results && data.results.length > 0) {
const latestConsumption = data.results[0];

  console.log(`✅ Latest Consumption: ${latestConsumption.consumption} kWh`);
  console.log(`🕒 Interval Start: ${new Date(latestConsumption.interval_start).toLocaleString()}`);
  console.log(`🕒 Interval End: ${new Date(latestConsumption.interval_end).toLocaleString()}`);

  // ✅ Store the consumption in a Homey variable (Tag) using the new function
  await tag('LiveEnergyUsage', latestConsumption.consumption);
  console.log(`✅ Homey tag "LiveEnergyUsage" updated successfully`);
} else {
  console.log('ℹ️ No consumption data available.');
}

})
.catch(error => {
console.error(‘:rotating_light: Error:’, error.message);
});

This is the output of that script which is not correct as that 0.168kWh latest consumption never changes. So I need to find out why it’s doing that as it only seems to pull the data from that one 30 min interval

1 Like