NevadaWeatherAwareThermostatAgent

InfoGenerateCreated ByPackages

This code defines a `ThermostatAgent` class within the `Sublayer::Agents` module. Its purpose is to periodically check the current weather in Nevada and adjust the thermostat's temperature accordingly. Here's a breakdown of its main functionalities:

1. **Initialization**: It initializes with a `thermostat` and a `weather_service` object and sets up instance variables.

2. **Scheduled Trigger**: It is set to trigger every 4 hours (`trigger_on_time_interval`).

3. **Check Status**: Upon each trigger, it retrieves the current weather in Nevada using the `weather_service` and determines the desired temperature based on the weather.

4. **Goal Condition**: The goal is to maintain the thermostat's temperature at the desired temperature.

5. **Step Execution**: If the thermostat's current temperature doesn't match the desired temperature, it adjusts the thermostat to the desired temperature.

6. **Temperature Determination**: It determines the desired temperature based on weather conditions with specific rules:
- Heat to 70°F if the temperature is below 32°F
- Set to 68°F if the temperature is between 33°F and 75°F
- Cool to 75°F if the temperature is above 75°F

module Sublayer
  module Agents
    class ThermostatAgent < Base
      def initialize(thermostat, weather_service)
        @thermostat = thermostat
        @weather_service = weather_service
        @desired_temperature = nil
      end

      trigger_on_time_interval do
        4 * 3600  # every 4 hours
      end

      check_status do
        @current_weather = @weather_service.get_weather("Nevada")
        puts "Current weather in Nevada: #{@current_weather}"
        @desired_temperature = determine_temperature(@current_weather)
      end

      goal_condition do
        @thermostat.current_temperature == @desired_temperature
      end

      step do
        puts "Adjusting thermostat"
        @thermostat.set_temperature(@desired_temperature)
      end

      private

      def determine_temperature(weather)
        case weather[:temperature]
        when -Float::INFINITY..32
          70  # Heat to 70°F if temperature is below freezing
        when 33..75
          68  # Cooler setting if temperature is between 33°F and 75°F
        else
          75  # Air conditioning to 75°F if temperature is above 75°F
        end
      end
    end
  end
end