def log():
    """Get values back from convirons"""
    config = get_config(get_config_file())
    cmd_str = "%s %s " % (config.get("Conviron", "GetCommand"), config.get("Conviron", "DeviceID"))
    # Establish connection
    telnet = _connect(config)
    # Get temp
    temp_cmd = bytes("%s %s\n" % (cmd_str, config.get("Logging", "TempSequence")), encoding="UTF8")
    temp_resp = _run(telnet, temp_cmd, re.compile(b"# $"))
    # str should be:
    # '123 134 \r\n[PS1] # \r\n'
    # "<actual>SPACE<set>SPACE\r\n..."
    temp_str = temp_resp[2]
    temp, temp_set = temp_str.splitlines()[0].strip().split()
    temp = "{:0.1f}".format(float(temp) / 10.0)
    temp_set = "{:0.1f}".format(float(temp_set) / 10.0)
    # Get Rel Humidity
    rh_cmd = bytes("%s %s\n" % (cmd_str, config.get("Logging", "RHSequence")), encoding="UTF8")
    rh_resp = _run(telnet, rh_cmd, re.compile(b"# $"))
    # str should be:
    # '52 73 \r\n[$PS1] # \r\n'
    # "<actual>SPACE<set>SPACE\r\n..."
    rh_str = rh_resp[2]
    rh, rh_set = rh_str.splitlines()[0].strip().split()
    rh = rh.decode()
    rh_set = rh_set.decode()
    # Get PAR
    par_cmd = bytes("%s %s\n" % (cmd_str, config.get("Logging", "PARSequence")), encoding="UTF8")
    par_resp = _run(telnet, par_cmd, re.compile(b"# $"))
    # str should be:
    # '123 \r\n[PS1] # \r\n'
    # actual value only (set is always 0)
    par_str = par_resp[2]
    par = par_str.splitlines()[0].strip().decode()
    # We're done w/ the telnet handle, close it here to avoid timeout issues
    telnet.close()
    # Do the logging to a csv file
    now = datetime.datetime.now()
    date = now.strftime(config.get("Logging", "DateFmt"))
    time = now.strftime(config.get("Logging", "TimeFmt"))
    logfile = config.get("Logging", "LogFile")
    loghdr = config.get("Logging", "CSVLogHeader").strip().split(",")
    if path.exists(logfile):
        # don't clobber file, use append mode & don't write header
        lfh = open(logfile, "a", newline="")
        lcsv = DictWriter(lfh, loghdr)
    else:
        # new file, so create and write a header
        lfh = open(logfile, "w", newline="")
        lcsv = DictWriter(lfh, loghdr)
        lcsv.writeheader()
    lcsv.writerow(
        {"Date": date, "Time": time, "Temp": temp, "SetTemp": temp_set, "RH": rh, "SetRH": rh_set, "PAR": par}
    )
    # close things that need closing
    lfh.close()
Exemplo n.º 2
0
def communicate(line):
    config = get_config(get_config_file())

    # # We do the login manually # #
    # Establish connection
    telnet = Telnet(config.get("Heliospectra", "MasterHost"),
            port=config.getint("Heliospectra", "MasterPort"))
    response = telnet.read_until(b">")
    if config.getboolean("Global", "Debug") > 0:
        print("Intial response is:", response.decode())

    wavelengths = [s.strip() for s in
            config.get("Heliospectra", "Wavelengths").split(",")]

    intensities = []
    for wl in sorted(wavelengths):
        intensity = float(line[config.getint("HeliospectraCsvFields", wl)])
        # Solarcalc gives percentages, telnet wants value in 0-255
        intensity = int(round(
            intensity * config.getfloat("Heliospectra", "Multiplier")
            ))
        intensities.append((wl, intensity))

    intensities = sorted(intensities)
    if config.getboolean("Global", "Debug"):
        print("Intensity list is:", intensities)

    set_cmd = config.get("Heliospectra", "SetallWlCommand")

    command_line = bytes("%s %s\n" % (
                set_cmd,
                " ".join("%i" % itn for _, itn in intensities)
                ),
            encoding="UTF8"
            )

    if config.getboolean("Global", "Debug"):
        print("Running:", command_line.decode())
    telnet.write(command_line)

    response = telnet.read_some()
    if config.getboolean("Global", "Debug"):
        print("Response is:", response.decode())

    # Close telnet session
    telnet.close()
def communicate(line):
    config = get_config(get_config_file())
    helio_mode = config.get("Heliospectra", "Mode")
    helio_csv = helio_mode + "CsvFields"
    # # We do the login manually # #
    # Establish connection
    telnet = Telnet(config.get(helio_mode, "MasterHost"),
            port=config.getint(helio_mode, "MasterPort"))
    response = telnet.read_until(b">")
    LOG.debug("Intial response is: {0!s}".format(response.decode()))

    wavelengths = [s.strip() for s in
            config.get(helio_mode, "Wavelengths").split(",")]
    # Build list of wl:intensity pairs to send
    intensities = []
    for wl in wavelengths:
        intensity = float(line[config.getint(helio_csv, wl)])
        # Solarcalc gives percentages, telnet wants value in 0-255
        intensity = int(round(
            intensity * config.getfloat(helio_mode, "Multiplier")
            ))
        intensities.append((wl, intensity))
    # And order them
    intensities = sorted(intensities)
    LOG.debug("Intensity list is: {0!s}".format(intensities))

    set_cmd = config.get(helio_mode, "SetallWlCommand")

    command_line = bytes("%s %s\n" % (
                set_cmd,
                " ".join("%i" % intens for _, intens in intensities)
                ),
            encoding="UTF8"
            )

    LOG.debug("Running: {0!s}".format(command_line.decode()))
    telnet.write(command_line)

    response = telnet.read_some()
    LOG.debug("Response is: {0!s}".format(response.decode()))

    # Close telnet session
    telnet.close()
Exemplo n.º 4
0
from time import strptime, sleep, mktime, time
import datetime
import csv
import socket
import sys
import time
import traceback
from spcControl import get_config_file, get_config, chamber, heliospectra, email_error


timepoint_count = 0
config = get_config(get_config_file())


def _email_traceback(traceback):
    message_text = "Error on chamber %i\n" % config.getint("Global", "Chamber")
    message_text += traceback
    subject = "Conviron Error (Chamber %i)" % config.getint("Global", "Chamber")
    email_error(subject, message_text)


def _log_to_postgres(log_tuple):
    try:
        import psycopg2
    except ImportError:
        return
    try:
        con = psycopg2.connect(
            host=config.get("Postgres", "Host"),
            port=config.getint("Postgres", "Port"),
            user=config.get("Postgres", "User"),
import psycopg2
import sys
from spcControl import (
    email_error,
    get_config,
)
from datetime import datetime
from time import sleep, timezone
import traceback
from psycopg2.tz import FixedOffsetTimezone
try:
    monitor_config_file = sys.argv[1]
except IndexError:
    monitor_config_file = "./monitor.ini"

monitor_config = get_config(monitor_config_file)


def _poll_database(chamber):
    try:
        con = psycopg2.connect(
                               host=monitor_config.get("Postgres", "Host"),
                               port=monitor_config.getint("Postgres", "Port"),
                               user=monitor_config.get("Postgres", "User"),
                               password=monitor_config.get("Postgres", "Pass"),
        )
        cur = con.cursor()
        statement = monitor_config.get("Postgres", "SelectLogPassesStatement")
        cur.execute(statement, (chamber,))
        result = list(cur)
        cur.close()
def communicate(line):
    """Communicate config values in csv line to a conviron."""
    config = get_config(get_config_file())
    cmd_str = "%s %s " % (config.get("Conviron", "SetCommand"), config.get("Conviron", "DeviceID"))
    # Establish connection
    telnet = _connect(config)
    # Make list for the "Set" part of the communication
    # Append init commands to command list
    command_list = []
    for params in config.get("Conviron", "InitSequence").split(","):
        command_list.append(bytes(cmd_str + params + "\n", encoding="UTF8"))
    # Append temp command to list
    command_list.append(
        bytes(
            "%s %s %i %i\n"
            % (
                cmd_str,
                config.get("ConvironDataTypes", "Temperature"),
                config.getint("ConvironDataIndicies", "Temperature"),
                int(float(line[config.getint("GlobalCsvFields", "Temperature")]) * 10),
            ),
            encoding="UTF8",
        )
    )
    # Append humidity command to list
    command_list.append(
        bytes(
            "%s %s %i %i\n"
            % (
                cmd_str,
                config.get("ConvironDataTypes", "Humidity"),
                config.getint("ConvironDataIndicies", "Humidity"),
                int(line[config.getint("GlobalCsvFields", "Humidity")]),
            ),
            encoding="UTF8",
        )
    )
    if config.getboolean("Conviron", "UseInternalLights"):
        # Append light1 command to list
        cmd = "%s %s %i %i\n" % (
            cmd_str,
            config.get("ConvironDataTypes", "Light1"),
            config.getint("ConvironDataIndicies", "Light1"),
            int(line[config.getint("ConvironCsvFields", "Light1")]),
        )
        command_list.append(bytes(cmd, encoding="UTF8"))
    # Append teardown commands to command list
    for params in config.get("Conviron", "TearDownSequence").split(","):
        command_list.append(bytes(cmd_str + params + "\n", encoding="UTF8"))
    # Run set commands sequence
    for command in command_list:
        _run(telnet, command, re.compile(b"#"))
    sleep(2)
    # Clear write flag
    write_flag_command = bytes(cmd_str + config.get("Conviron", "ClearWriteFlagCommand") + "\n", encoding="UTF8")
    _run(telnet, write_flag_command, re.compile(b"#"))
    sleep(2)
    # Make list of Reload command sequences
    command_list = []
    for params in config.get("Conviron", "ReloadSequence").split(","):
        command_list.append(bytes(cmd_str + params + "\n", encoding="UTF8"))
    # Append teardown commands to command list
    for params in config.get("Conviron", "TearDownSequence").split(","):
        command_list.append(bytes(cmd_str + params + "\n", encoding="UTF8"))
    # Run Reload command sequence
    for command in command_list:
        _run(telnet, command, re.compile(b"#"))
    sleep(2)
    # Clear write flag
    clear_write_flag_cmd = bytes(cmd_str + config.get("Conviron", "ClearWriteFlagCommand") + "\n", encoding="UTF8")
    _run(telnet, clear_write_flag_cmd, re.compile(b"#"))
    sleep(2)
    # Clear Busy flag
    clear_busy_flag_cmd = bytes(cmd_str + config.get("Conviron", "ClearBusyFlagCommand") + "\n", encoding="UTF8")
    _run(telnet, clear_busy_flag_cmd, re.compile(b"#"))
    sleep(2)
    # Close telnet session
    telnet.close()