# -*- coding: utf-8 -*-

"""package scinstr.daq.labjack
author    Benoit Dubois
copyright FEMTO Engineering, 2020-2024
licence   GPL 3.0+
brief     Handle Labjack T7(-Pro) device (DAQ board) through ethernet
          interface.
"""

import logging
import pymodbus.exceptions as mdex
from pymodbus.client.sync import ModbusTcpClient

from scinstr.daq.labjack.t7 import T7


# =============================================================================
class T7Eth(T7):
    """T7Eth class, provide command/response handling of LabJack T7-Pro
    board through ethernet interface.
    """

    def __init__(self, ip=""):
        """Constructor.
        :param ip: IP address of T7-Pro device (str)
        :returns: None
        """
        super().__init__()
        self.ip = ip

    def connect(self):
        """Connect to device.
        :returns: None
        """
        logging.info('Connecting to T7 @%s...', self.ip)
        self._client = ModbusTcpClient(self.ip)
        retval = self._client.connect()
        if retval is True:
            logging.info('Connection --> Ok')
            return True
        logging.info('Connection --> Nok')
        return False

    def close(self):
        """Close connection with device.
        :returns: None
        """
        try:
            self._client.close()
        except mdex.ModbusException as ex:
            logging.error("Modbus error %r", ex)
        except Exception as ex:
            logging.error("Unexpected error %r", ex)
        logging.info("Connection to T7 closed")


# =============================================================================
if __name__ == "__main__":
    # For "Ctrl+C" works
    import signal
    signal.signal(signal.SIGINT, signal.SIG_DFL)

    # Setup logger
    LOG_FORMAT = '%(asctime)s %(levelname)s %(filename)s (%(lineno)d): ' \
                 + '%(message)s'
    logging.basicConfig(format=LOG_FORMAT, level=logging.INFO)

    import time
    from os.path import expanduser

    I0 = 200e-6
    IP = '192.168.0.206'
    HOME = expanduser("~")
    FILE = HOME + "/t7_test.dat"

    def pt100_v2t(volt, i0):
        """Temperature from voltage of a Pt100 sensor.
        """
        return (2.604 * volt / i0) - 260.4

    T7 = T7Eth(IP)
    T7.connect()
    print("Id:", T7.get_id())

    AINS = [0, 1, 2, 3]
    T7.set_ains_resolution(AINS, [8, 8, 8, 8])

    with open(FILE, "a") as fd:
        while True:
            V_RAW = T7.get_ains_voltage(AINS)
            V_STR = ''
            for V in V_RAW:
                V_STR += str(V) + ';'
            print(V_STR)
            time.sleep(1.0)

    T7.close()
    exit()
