Attempting to grab electricity-price data and write schedule based on threshold

Hi

I’m trying to use AppDaemon with a py-script to do the following:
Trigger on change in attribute in price-sensor
Grab data from same sensor and attribute ‘raw_tomorrow’
Compare hourly prices with ‘input_number.heating_threshold’ and modify data with chosen heatsource - write data to schedule input_text.heating_schedule.

I got parts working but then trying to tie all together I’m getting completely lost on the way

import hassapi as hass

class HeatSourceSelection(hass.Hass):
    def initialize(self):
        try:
            self.log("App initialization complete")

            # Listen for changes in the sensor attribute tomorrow_valid
            self.listen_state(self.trigger_heat_source_selection, "sensor.nordpool_kwh_se4_sek_3_10_025", attribute="tomorrow_valid")

        except Exception as e:
            self.log(f"Error during initialization: {e}", level="ERROR")
            import traceback
            self.log(f"Traceback: {traceback.format_exc()}", level="ERROR")
            raise

    def trigger_heat_source_selection(self, entity, attribute, old, new, kwargs):
        try:
            if new == "true":
                self.log("Tomorrow's data is valid: Turning on the heat source selection logic.")

                # Get tomorrow's hourly prices from the sensor
                hourly_prices = self.get_state("sensor.nordpool_kwh_se4_sek_3_10_025", attribute="raw_tomorrow")

                # Threshold for switching between pellets and heat pump
                threshold = float(self.get_state("input_number.heating_threshold"))

                # Initialize an empty schedule
                heating_schedule = ""

                # Check each hourly price and decide whether to use pellets or heat pump
                for hour_price in hourly_prices:
                    if float(hour_price) < threshold:
                        heating_schedule += "Use Pellets\n"
                    else:
                        heating_schedule += "Use Heat Pump\n"

                # Set the value of input_text.heating_schedule
                self.set_state("input_text.heating_schedule", state=heating_schedule)

            else:
                self.log("Tomorrow's data is not valid.")

        except Exception as e:
            self.log(f"Error during trigger_heat_source_selection: {e}", level="ERROR")
            import traceback
            self.log(f"Traceback: {traceback.format_exc()}", level="ERROR")
            raise

# Instantiate the class with required parameters
HeatSourceSelection(name="heat_source_selection")
´´´

Fixed it :slight_smile:

import hassapi as hass

class HeatSourceSelection(hass.Hass):
    def initialize(self):
        try:
            self.log("App initialization complete")

            # Listen for changes in the sensor attribute tomorrow_valid
            self.listen_state(self.trigger_heat_source_selection, "sensor.nordpool_kwh_se4_sek_3_10_025", attribute="tomorrow_valid")

        except Exception as e:
            self.log(f"Error during initialization: {e}", level="ERROR")
            import traceback
            self.log(f"Traceback: {traceback.format_exc()}", level="ERROR")
            raise

    def trigger_heat_source_selection(self, entity, attribute, old, new, kwargs):
        try:
            if new is True:
                self.log("Tomorrow's data is valid: Turning on the heat source selection logic.")

                # Get the 'raw_today' attribute of the sensor
                raw_today = self.get_state("sensor.nordpool_kwh_se4_sek_3_10_025", attribute="raw_tomorrow")

                # Get the heating threshold
                heating_threshold = float(self.get_state("input_number.heating_threshold"))

                # Loop over the entries in 'raw_today'
                for entry in raw_today:
                    # Extract the 'start', 'end', and 'value' keys
                    start = entry['start']
                    end = entry['end']
                    value = float(entry['value'])

                    self.log(f"Start: {start}, End: {end}, Value: {value}")

                    # Determine the heat source based on the value and the threshold
                    heat_source = "Heat pump" if value < heating_threshold else "Pellets"

                    # Create an event in the calendar for this entry
                    self.call_service("calendar/create_event", 
                                      entity_id="calendar.heatsource_schedule", 
                                      summary=heat_source, 
                                      start_date_time=start, 
                                      end_date_time=end)

            else:
                self.log("Tomorrow's data is not valid.")

        except Exception as e:
            self.log(f"Error during trigger_heat_source_selection: {e}", level="ERROR")
            import traceback
            self.log(f"Traceback: {traceback.format_exc()}", level="ERROR")
            raise