Updated auto code and change weather api

This commit is contained in:
2025-10-12 16:09:45 -04:00
parent c69d48dd74
commit ed2e6f96b6
8 changed files with 352 additions and 308 deletions

View File

@@ -0,0 +1,153 @@
from sqlalchemy.orm import Session
from sqlalchemy import func
from datetime import date, timedelta
from decimal import Decimal
# Import your existing database models
from app.models.auto import Auto_Delivery, Auto_Temp, Auto_Update, Tickets_Auto_Delivery
# --- Constants for the Model ---
# This is a baseline daily usage for homes that use oil for hot water.
# A typical value is 0.5 to 1.0 gallons per day. Adjust as needed.
HOT_WATER_DAILY_USAGE = Decimal('0.7')
# This determines how quickly the K-Factor adjusts.
# 0.7 means 70% weight is given to the historical factor and 30% to the new one.
# This prevents wild swings from a single unusual delivery period.
K_FACTOR_SMOOTHING_WEIGHT = Decimal('0.7')
class FuelEstimator:
def __init__(self, session: Session):
self.session = session
def _get_weather_for_date(self, target_date: date) -> Auto_Temp | None:
"""Helper to fetch weather data for a specific date."""
return self.session.query(Auto_Temp).filter(Auto_Temp.todays_date == target_date).first()
def run_daily_update(self):
"""
Main function to run once per day. It updates the estimated fuel level
for all active automatic delivery customers. The calling function must commit the session.
"""
today = date.today()
# 1. Check if the update has already run today
if self.session.query(Auto_Update).filter(Auto_Update.last_updated == today).first():
print(f"Daily update for {today} has already been completed.")
return {"ok": True, "message": "Update already run today."}
# 2. Get today's weather data (specifically the Heating Degree Days)
todays_weather = self._get_weather_for_date(today)
if not todays_weather:
print(f"Error: Weather data for {today} not found. Cannot run update.")
return {"ok": False, "message": f"Weather data for {today} not found."}
# Degree days can't be negative for this calculation. If it's warm, HDD is 0.
degree_day = Decimal(max(0, todays_weather.degree_day))
# 3. Get all active automatic customers
auto_customers = self.session.query(Auto_Delivery).filter(
Auto_Delivery.auto_status == 1 # Assuming 1 means active
).all()
if not auto_customers:
print("No active automatic delivery customers found.")
return {"ok": True, "message": "No active customers to update."}
print(f"Staging daily fuel update for {len(auto_customers)} customers...")
# 4. Loop through each customer and update their fuel level
for customer in auto_customers:
heating_usage = customer.house_factor * degree_day
hot_water_usage = Decimal('0.0')
if customer.hot_water_summer == 1:
hot_water_usage = HOT_WATER_DAILY_USAGE
gallons_used_today = heating_usage + hot_water_usage
customer.estimated_gallons_left_prev_day = customer.estimated_gallons_left
new_estimated_gallons = customer.estimated_gallons_left - gallons_used_today
customer.estimated_gallons_left = max(Decimal('0.0'), new_estimated_gallons)
customer.last_updated = today
if customer.days_since_last_fill is not None:
customer.days_since_last_fill += 1
# 5. Log that today's update is complete
new_update_log = Auto_Update(last_updated=today)
self.session.add(new_update_log)
print("Daily update staged. Awaiting commit.")
return {"ok": True, "message": f"Successfully staged updates for {len(auto_customers)} customers."}
def refine_factor_after_delivery(self, ticket: Tickets_Auto_Delivery):
"""
This is the self-correction logic. It recalculates and refines the customer's
K-Factor (house_factor) after a delivery. The calling function must commit the session.
"""
customer = self.session.query(Auto_Delivery).filter(
Auto_Delivery.customer_id == ticket.customer_id
).first()
if not customer or not customer.last_fill:
print(f"Cannot refine K-Factor: Customer {ticket.customer_id} not found or has no previous fill date. Resetting tank only.")
self._update_tank_after_fill(customer, ticket)
return
start_date = customer.last_fill
end_date = ticket.fill_date
if start_date >= end_date:
print(f"Cannot refine K-Factor for customer {ticket.customer_id}: New fill date is not after the last one. Resetting tank only.")
self._update_tank_after_fill(customer, ticket)
return
total_hdd_result = self.session.query(func.sum(Auto_Temp.degree_day)).filter(
Auto_Temp.todays_date > start_date,
Auto_Temp.todays_date <= end_date,
Auto_Temp.degree_day > 0
).scalar()
total_hdd = Decimal(total_hdd_result or 0)
total_hot_water_usage = Decimal('0.0')
if customer.hot_water_summer == 1:
num_days = (end_date - start_date).days
total_hot_water_usage = Decimal(num_days) * HOT_WATER_DAILY_USAGE
gallons_for_heating = ticket.gallons_delivered - total_hot_water_usage
if gallons_for_heating <= 0 or total_hdd == 0:
print(f"Cannot calculate new K-Factor for customer {ticket.customer_id}. (HDD: {total_hdd}, Heating Gallons: {gallons_for_heating}). Resetting tank only.")
self._update_tank_after_fill(customer, ticket)
return
new_k_factor = gallons_for_heating / total_hdd
current_k_factor = customer.house_factor
smoothed_k_factor = (current_k_factor * K_FACTOR_SMOOTHING_WEIGHT) + (new_k_factor * (Decimal('1.0') - K_FACTOR_SMOOTHING_WEIGHT))
print(f"Refining K-Factor for Customer ID {customer.customer_id}:")
print(f" - Old K-Factor: {current_k_factor:.4f}, New Smoothed K-Factor: {smoothed_k_factor:.4f}")
customer.house_factor = smoothed_k_factor
self._update_tank_after_fill(customer, ticket)
print(f"K-Factor and tank status for Customer {customer.customer_id} staged for update.")
def _update_tank_after_fill(self, customer: Auto_Delivery, ticket: Tickets_Auto_Delivery):
"""Helper to reset customer tank status after a fill-up."""
customer.last_fill = ticket.fill_date
customer.days_since_last_fill = 0
# A "fill-up" means the tank is full. This is critical for accuracy.
if customer.tank_size and Decimal(customer.tank_size) > 0:
customer.estimated_gallons_left = Decimal(customer.tank_size)
else:
# Default to a common tank size if not specified, e.g., 275
customer.estimated_gallons_left = Decimal('275.0')
# The previous day's value should match the new full value on a fill day.
customer.estimated_gallons_left_prev_day = customer.estimated_gallons_left
customer.last_updated = date.today()
customer.auto_status = 1 # Reactivate the customer

73
app/script/temp_getter.py Normal file
View File

@@ -0,0 +1,73 @@
from datetime import date
import requests
from decimal import Decimal
# Import your database model and the session from your database configuration
from app.models.auto import Auto_Temp
from database import session
def Average(lst):
"""Calculates the average of a list of numbers."""
return sum(lst) / len(lst)
def fetch_and_store_daily_temp() -> bool:
"""
Fetches the current day's weather for Worcester, MA, calculates the
Heating Degree Day (HDD), and stores it in the database if it doesn't already exist.
Returns:
bool: True if the temperature is successfully fetched and stored (or already exists),
False if an error occurs.
"""
# 1. Check if the temperature for today already exists in the database
today = date.today()
if session.query(Auto_Temp).filter(Auto_Temp.todays_date == today).first():
print(f"Temperature for {today} already exists in the database. Skipping fetch.")
return True
# 2. If it doesn't exist, fetch it from the API
print(f"Fetching temperature for {today} from OpenWeatherMap...")
try:
# API key and location
api_key = '21648d8c8d1a4ae495ace0b7810b4d36'
location = 'Worcester,US'
# Make request to OpenWeatherMap Current Weather API with imperial units for Fahrenheit
url = f"http://api.openweathermap.org/data/2.5/weather?q={location}&appid={api_key}&units=imperial"
response = requests.get(url)
response.raise_for_status() # Raise an error for bad status codes
data = response.json()
# Extract temperatures in Fahrenheit
main = data.get('main', {})
current_temp = Decimal(main.get('temp', 0))
low_temp = Decimal(main.get('temp_min', 0))
high_temp = Decimal(main.get('temp_max', 0))
# Calculate average temperature and Heating Degree Days (HDD)
avg_temp = (low_temp + high_temp) / 2
# HDD is based on a baseline of 65°F. It cannot be negative for heating calculations.
degree_day = max(Decimal(0), 65 - avg_temp)
# 3. Create a new database object
add_new_temp = Auto_Temp(
temp=current_temp,
temp_max=high_temp,
temp_min=low_temp,
temp_avg=round(avg_temp, 2),
degree_day=round(degree_day),
todays_date=today
)
# 4. Add the new record to the session (it will be committed by the calling function)
session.add(add_new_temp)
print(f"Successfully fetched and staged temperature for {today}.")
return True
except Exception as e:
print(f"An error occurred while fetching weather data: {e}")
# Make sure to rollback the session in case of a partial failure
session.rollback()
return False

View File

@@ -1,26 +0,0 @@
from decimal import Decimal
from database import session
def calc_home_factor(gallons_put_in_home, current_house_factor):
if 200.01 <= gallons_put_in_home <= 500:
customer_home_factor = Decimal(current_house_factor) + Decimal(1)
elif 170.01 <= gallons_put_in_home <= 200:
customer_home_factor = Decimal(current_house_factor) + Decimal(1.5)
elif 150.01 <= gallons_put_in_home <= 170:
customer_home_factor = Decimal(current_house_factor) + Decimal(1.25)
elif 120.01 <= gallons_put_in_home <= 150:
customer_home_factor = Decimal(current_house_factor) - Decimal(.25)
elif 90.01 <= gallons_put_in_home <= 120:
customer_home_factor = Decimal(current_house_factor) - Decimal(.50)
elif 0.01 <= gallons_put_in_home <= 90:
customer_home_factor = Decimal(current_house_factor) - Decimal(.75)
else:
customer_home_factor = Decimal(current_house_factor)
if customer_home_factor <= 0:
customer_home_factor = Decimal(.25)
return customer_home_factor