Thermocouple logging

Thermocouple logging#

#!/usr/bin/env python3
"""Log four thermocouple channels to CSV once a second."""

import csv
import datetime
import os
import time

import synergy_logic

LOG_FILE = "temperatures.csv"

base = synergy_logic.Base()
thermo = base[1]              # SLM-THM-4

new_file = not os.path.exists(LOG_FILE) or os.path.getsize(LOG_FILE) == 0

with open(LOG_FILE, "a", newline="") as fh:
    writer = csv.writer(fh)
    if new_file:
        writer.writerow(["timestamp", "tc1", "tc2", "tc3", "tc4"])

    while True:
        readings = thermo.reals
        writer.writerow([datetime.datetime.now().isoformat()] + readings)
        fh.flush()               # Python buffer -> operating system
        os.fsync(fh.fileno())    # operating system -> SD card

        for index, temp in enumerate(readings, start=1):
            print(f"TC{index}: {temp:7.2f}")
        time.sleep(1)

The header row is written only when the file is new, so restarting the program appends to the existing log. flush() passes buffered rows to the operating system, and os.fsync() writes them to the SD card; together they limit what a power loss can discard to the row being written.

The temperature unit (Celsius or Fahrenheit) depends on the module configuration.