from ...base import BaseNode
from .configuration import Configuration
import asyncio
import pyvisa

class VISA(BaseNode, Configuration):
    def __init__(self, node_config: dict[str, str], stop_event: asyncio.Event):
        BaseNode.__init__(self, stop_event)
        Configuration.__init__(self, node_config)

    async def connect(self):
        try:
            self.client = pyvisa.ResourceManager(r'C:\Windows\system32\visa64.dll')
            self.device = self.client.open_resource(self.resource_name, timeout=self.timeout, write_termination = self.write_termination, read_termination = self.read_termination)
        except Exception as e:
            print("An error occurred while starting VISA:", e)
    
    async def disconnect(self):
        self.device.close()
        self.client.close()

    async def write(self, data: list[str]):
        try:
            for msg in data:
                self.device.write(msg)
        except Exception as e:
            print("An error occurred while sending data with VISA protocol:", e)

    async def read(self, variable_list: list[str]):
        try:
            value_list = []
            for variable_name in variable_list:
                variable_value = self.device.query_ascii_values(variable_name)
                value_list.append(variable_value)
            return value_list
        except Exception as e:
            print("An error occurred while receiving data with VISA protocol:", e)
