I’ve been trying to get my storage heaters to switch on automatically based on the day’s highest temperature forecast, but honestly, I was stuck for a while. I tried writing a script myself, but it just wouldn’t work. Frustrated, I thought, why not give OpenAI a shot? Boy, was that a smart move!
Within minutes, I had a fully functional script tailored to my needs. Here’s the code it generated:
python
Import required modules
import requests
import datetime
Define API key and location for weather forecast
api_key = ‘your_api_key’
location = ‘your_location’
Make API request to get forecast data
response = requests.get(f’https://api.openweathermap.org/data/2.5/forecast?q={location}&appid={api_key}')
forecast_data = response.json()
Get the temperature forecast for today
today = datetime.datetime.now().strftime(“%Y-%m-%d”)
temperatures =
for forecast in forecast_data[‘list’]:
if forecast[‘dt_txt’].startswith(today):
temperatures.append(forecast[‘main’][‘temp’])
Get the highest forecast temperature for today
highest_temperature = max(temperatures)
Switch on device at different time based on temperature
if highest_temperature > 30:
switch_on_time = ‘12:00’
elif highest_temperature > 20:
switch_on_time = ‘14:00’
else:
switch_on_time = ‘16:00’
Define switch on action
switch_on_action = {‘service’: ‘switch.turn_on’, ‘entity_id’: ‘switch.your_switch’}
Schedule switch on
schedule.run_at(switch_on_time, switch_on_action)
I haven’t tested it yet, but the logic looks solid. It’s amazing how much time and effort this saved me compared to trying to figure it out on my own. I’m really excited to see how this works in practice!
If anyone has tips or suggestions for improving this script, I’d love to hear them. Let’s keep the smart home innovations coming! ![]()