多字典多行值存储:制冷机温度监控程序开发技术问询
Hey Richard, let's build this temperature tracking program that checks all your boxes. I'll use Python for the example—it's perfect for data handling and scheduling tasks, but you can adapt the core logic to other languages too.
Core Requirements Recap
First, let's lock in exactly what we need to deliver:
- Persistently track temperatures per cooler as new data comes in
- Periodically output:
- Max/min temperatures for each individual cooler
- Global maximum temperature across all coolers
- Top 5 highest temperatures recorded globally
- Receive structured
tempinputdata every 5 minutes (we'll simulate sample input for testing)
Step 1: Data Storage Structure
We'll use a dictionary where each key is a cooler ID, and the value is a list of recorded temperatures for that cooler. This setup makes it trivial to add new readings and compute per-machine stats:
# Initialize storage: key = cooler ID, value = list of temperature readings cooler_temperatures = {}
Step 2: Process Incoming Tempinput
Let's create a function to handle each new tempinput entry. Assuming your input is a JSON object (like {"cooler_id": "C003", "temperature": 3.8}), we'll parse it and update our storage:
def process_tempinput(temp_data): cooler_id = temp_data["cooler_id"] temp = temp_data["temperature"] # Add the temperature to the cooler's list (create a new list if the cooler is new) if cooler_id not in cooler_temperatures: cooler_temperatures[cooler_id] = [] cooler_temperatures[cooler_id].append(temp) print(f"Logged temperature for {cooler_id}: {temp}°C")
Step 3: Calculate & Print Statistics
Next, let's write a function to compute all the required stats and print them in a clean, readable format:
def print_temperature_stats(): print("\n=== Temperature Statistics ===") # 1. Single cooler max/min temperatures for cooler_id, temps in cooler_temperatures.items(): if temps: max_temp = max(temps) min_temp = min(temps) print(f"Cooler {cooler_id}: Max = {max_temp}°C, Min = {min_temp}°C") # 2. Global maximum temperature all_temps = [temp for temps in cooler_temperatures.values() for temp in temps] if all_temps: global_max = max(all_temps) print(f"\nGlobal Maximum Temperature: {global_max}°C") # 3. Global Top 5 Highest Temperatures (sorted descending, take first 5) sorted_temps = sorted(all_temps, reverse=True) top_5 = sorted_temps[:5] print(f"Global Top 5 Temperatures: {', '.join(map(str, top_5))}°C") else: print("No temperature data recorded yet.")
Step 4: Schedule Periodic Tasks
We'll use the schedule library to handle the 5-minute interval for receiving data and printing stats. First, install it if you haven't:
pip install schedule
Then set up the scheduled tasks (we'll simulate sample tempinput data for testing—replace this with your actual data source like an API, file, or MQTT feed):
import schedule import time # Simulate incoming tempinput (replace this with your real data fetch logic) def fetch_and_process_tempinput(): # Sample tempinput entries sample_inputs = [ {"cooler_id": "C001", "temperature": 4.1}, {"cooler_id": "C002", "temperature": 2.8}, {"cooler_id": "C001", "temperature": 4.5}, {"cooler_id": "C003", "temperature": 3.9}, {"cooler_id": "C002", "temperature": 3.1} ] for input_data in sample_inputs: process_tempinput(input_data) # After processing new data, print updated stats print_temperature_stats() # Schedule the task to run every 5 minutes schedule.every(5).minutes.do(fetch_and_process_tempinput) # Run the scheduler indefinitely print("Starting temperature tracking program...") while True: schedule.run_pending() time.sleep(1)
Key Customization Tips
- Data Persistence: To keep data between program restarts, save
cooler_temperaturesto a JSON file or lightweight database (like SQLite) on a regular basis, then load it when the program starts. - Error Handling: Add try-except blocks to handle invalid
tempinput(e.g., missing cooler ID, non-numeric temperature) to make the program more robust. - Additional Stats: Extend the
print_temperature_statsfunction to include average temperatures, temperature trends, or alerts for out-of-range readings if needed.
内容的提问来源于stack exchange,提问作者Richard IC

