Guest User

Gas tracker scriptable widget

a guest
Feb 29th, 2024
477
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
JavaScript 5.69 KB | Housing | 0 0
  1. // Scriptable Widget for Displaying Energy and Gas Tariff Information
  2. // Adapted from https://github.com/smalley1992/smalley1992.github.io/blob/main/OctopusTrackerSmallWidget.scriptable
  3. // CS Feb 2024
  4. const widget = new ListWidget(); // Initialize a new list widget
  5. widget.backgroundColor = new Color("#100030"); // Set the background color of the widget
  6.  
  7. widget.addSpacer(20); // Add space at the top
  8. const header = widget.addText("Gas Tracker"); // Add header text
  9. header.font = Font.boldSystemFont(14); // Set the font and size of the header
  10. header.textColor = Color.white(); // Set the color of the header text
  11. widget.addSpacer(8); // Add space below the header
  12.  
  13. // Function to fetch tariff data for electricity or gas
  14. async function fetchTariffData(productCode, tariffCode) {
  15.     const today = new Date(); // Get today's date
  16.     const tomorrow = new Date(today.getTime() + 86400000); // Calculate tomorrow's date
  17.      
  18.     const baseUrl = `https://api.octopus.energy/v1/products/${productCode}/`; // Base URL for the API
  19.    
  20.     // Format today and tomorrow's dates as strings
  21.     const todayStr = `${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, '0')}-${String(today.getDate()).padStart(2, '0')}`;
  22.     const tomorrowStr = `${tomorrow.getFullYear()}-${String(tomorrow.getMonth() + 1).padStart(2, '0')}-${String(tomorrow.getDate()).padStart(2, '0')}`;
  23.     const tariffType = tariffCode.substring(0,1).toUpperCase() == 'G' ? 'gas' : 'electricity';
  24.     // Construct URLs for today and tomorrow's tariff data
  25.     const urlToday = `${baseUrl}${tariffType}-tariffs/${tariffCode}/standard-unit-rates/?period_from=${todayStr}T00:00:00Z&period_to=${todayStr}T23:59:59Z`;
  26.     const urlTomorrow = `${baseUrl}${tariffType}-tariffs/${tariffCode}/standard-unit-rates/?period_from=${tomorrowStr}T00:00:00Z&period_to=${tomorrowStr}T23:59:59Z`;
  27.     console.log(urlTomorrow);
  28.  
  29.     let dataToday, dataTomorrow;
  30.     try {
  31.         // Fetch and process today's tariff data
  32.         let responseToday = await new Request(urlToday).loadJSON();
  33.         dataToday = responseToday.results[0]?.value_inc_vat.toFixed(2);
  34.         // Fetch and process tomorrow's tariff data
  35.         let responseTomorrow = await new Request(urlTomorrow).loadJSON();
  36.         dataTomorrow = responseTomorrow.results[0]?.value_inc_vat.toFixed(2);
  37.     } catch (error) {
  38.         // Handle errors by setting data to "N/A"
  39.         console.error(`Error fetching tariff data: ${error}`);
  40.         dataToday = "N/A";
  41.         dataTomorrow = "N/A";
  42.     }
  43.  
  44.     return { today: dataToday, tomorrow: dataTomorrow }; // Return today and tomorrow's data
  45. }
  46.  
  47. // Function to display the tariff data on the widget
  48. async function displayTariffData(productCode, tariffCode, symbolName) {
  49.     const data = await fetchTariffData(productCode, tariffCode); // Fetch the tariff data
  50.     let row = widget.addStack(); // Create a new row in the widget
  51.     row.centerAlignContent(); // Center-align the content in the row
  52.  
  53.     const symbol = SFSymbol.named(symbolName); // Get the SF Symbol for the tariff type
  54.     symbol.applyMediumWeight(); // Apply medium weight to the symbol for better visibility
  55.     const img = row.addImage(symbol.image); // Add the symbol image to the row
  56.     img.tintColor = Color.white(); // Set the symbol's color to white
  57.     img.imageSize = new Size(30, 30); // Set the size of the symbol image
  58.     img.resizable = true; // Allow the symbol image to be resizable
  59.     row.addSpacer(8); // Add space after the symbol
  60.  
  61.     // Display today's price in a large font
  62.     let priceElement = row.addText(`${data.today}p`);
  63.     priceElement.font = Font.boldSystemFont(26);
  64.     priceElement.textColor = Color.white();
  65.  
  66.     widget.addSpacer(4); // Add space below today's price
  67.  
  68.     let subText, subElement;
  69.     // Check if tomorrow's price is available and not "N/A"
  70.     if (data.tomorrow && data.tomorrow !== "N/A") {
  71.         let change = data.today && data.today !== "N/A" ? ((parseFloat(data.tomorrow) - parseFloat(data.today)) / parseFloat(data.today)) * 100 : 0;
  72.         // Determine the arrow direction based on price change
  73.         let arrow = change > 0 ? "↑" : (change < 0 ? "↓" : ""); // Add an arrow for increase or decrease
  74.         subText = `Tomorrow: ${data.tomorrow}p ${arrow}`;
  75.         subElement = widget.addText(subText);
  76.         // Color the text based on price change direction
  77.         subElement.textColor = change > 0 ? new Color("#FF3B30") : (change < 0 ? new Color("#30D158") : Color.white());
  78.         subElement.font = Font.systemFont(12);
  79.     } else {
  80.         // Display "Coming Soon" if tomorrow's price is not available
  81.         subText = `Tomorrow: Unknown`;
  82.         subElement = widget.addText(subText);
  83.         subElement.textColor = Color.white();
  84.         subElement.font = Font.systemFont(10);
  85.     }
  86.  
  87.     widget.addSpacer(20); // Add final spacer for layout
  88. }
  89.  
  90. const product= "SILVER-BB-23-12-06"; // Product code for the current tariff
  91. const productOld = "VAR-BB-23-04-01"; // Product code for the previous tariff
  92. const tariff = "G-1R-SILVER-BB-23-12-06-C"; // Tariff code for the current tariff
  93. const tariffOld = "G-1R-VAR-BB-23-04-01-C"; // Tariff code for the previous tariff
  94.  
  95. // Display tariff information
  96. await displayTariffData(product, tariff, "flame.fill");
  97. await displayTariffData(productOld, tariffOld, "flame");
  98.  
  99. // Optional: Set the widget's URL to open a specific app or webpage when clicked
  100. widget.url = "https://octopustracker.small3y.co.uk";
  101.  
  102. // Preview the widget in the app if not running in a widget context
  103. if (!config.runsInWidget) {
  104.     await widget.presentMedium();
  105. }
  106.  
  107. Script.setWidget(widget); // Set the widget for display
  108. Script.complete(); // Signal that the script has completed execution
Advertisement
Add Comment
Please, Sign In to add comment