import ctypes
import threading
import time
import wtina226

class I2CDevice:
    _collect_event = threading.Event()
    def __init__(self, addr, address):
        self.device = wtina226.I2CHandle(address)
        self.data = {f'{addr}_time':[], f'{addr}_data':[]}
        self.complete = None
        self.addr = str(addr)

    def __enter__(self):
        return self.device

    def __exit__(self, exc_type, exc_value, traceback):
        self.device = None

    def write_reg(self, reg, value):
        return self.device.write_reg(reg, value)

    def read_reg(self, reg):
        return self.device.read_reg(reg)
    
    def start_sampling(self, sample_interval_us, sample_count):
        return self.device.start_sampling(sample_interval_us, sample_count)

    def is_sampling_complete(self):
        return self.device.is_sampling_complete()
    
    def get_c_data(self):
        return self.device.get_data()
    
    def collect_task(self, sampling_interval, num_reads):
        while True:
            I2CDevice._collect_event.wait()
            print(f'addr {self.addr}: 开始采集')
            self.complete = False
            self.start_sampling(sampling_interval, num_reads)
            while not self.is_sampling_complete():
                time.sleep(1) 
            data = self.get_c_data()
            for item in data:
                value, timestamp = item
                current_data = ctypes.c_short(value).value  # 读取寄存器
                self.data[f'{self.addr}_data'].append(round((current_data * 2.5) / 3900.0 , 3))
                self.data[f'{self.addr}_time'].append(timestamp)
            self.complete = True
            I2CDevice._collect_event.clear()
            
    def get_data(self):
        return self.data
    
    def set_data(self):
        del self.data
        self.data = {f'{self.addr}_time':[], f'{self.addr}_data':[]}
        self.complete = False