import serial
import sys
import os
import time
def read_temperature_from_serial(port):
    try:
        with serial.Serial(port, baudrate=9600, timeout=2) as ser:
            # Read a line from the serial port
            line = ser.readline().decode('utf-8').strip()
            # Attempt to convert to a float
            return float(line)
    except serial.SerialException as e:
        print(f"Serial error: {e}")
        sys.exit(1)
    except ValueError:
        print("Received invalid temperature data.")
        return None
def save_temperature_to_file(file_path, temperature):
    # Ensure the directory exists
    os.makedirs(os.path.dirname(file_path), exist_ok=True)
    
    # Write the temperature value to the file
    with open(file_path, 'w') as file:
        file.write(f"{temperature:.1f}")
def main():
    if len(sys.argv) != 2:
        print("Usage: python3 script.py <COM_PORT>")
        sys.exit(1)
    com_port = sys.argv[1]
    file_path = r"c:\temperature\temp.sensor"
    while True:
        temperature = read_temperature_from_serial(com_port)
        if temperature is not None:
            save_temperature_to_file(file_path, temperature)
            print(f"Temperature {temperature:.1f} saved to {file_path}")
        else:
            print("Skipping invalid temperature reading.")
        
        time.sleep(5)
if __name__ == "__main__":
    main()