import os
import time
import threading 

from ..conmunicator.INS401_Ethernet import Ethernet_Dev
from ..logger.Test_Logger import TestLogger



class DataLog:
    def __init__(self):
        self.eth = Ethernet_Dev()
        self.test_log = TestLogger()
        self.test_time = time.strftime("%Y_%m_%d_%H_%M_%S", time.localtime(time.time()))

    def run(self, timeout=30):

        logf_name = f'./data/user_data_{self.test_time}.bin'
        self.test_log.creat_binf(logf_name)

        self.eth.find_device()

        start_time = time.time()
        self.eth.start_listen_data()
        self.eth.reset_buffer() 
        print(f"Start log data ({timeout}s)")   
        while time.time() - start_time <= timeout:
            data = self.eth.read_data()
            self.test_log.write2bin(data)
        self.eth.stop_listen_data()
        if self.eth.check_len() != 0:
            while True:
                data = self.eth.read_data()
                self.test_log.write2bin(data)
                if self.eth.check_len() == 0:
                    break
