import ctypes
import json
import os
import sys
import threading
import time
import platform

from module.timer import timer
from module.I2CDevice import I2CDevice
from module.smqtt import smqtt

executable_path = sys.argv[0]
path = os.path.dirname(os.path.abspath(executable_path))
dev_sys = platform.system()
resourcesPath = path + os.sep

IDLE = 0
COLLECT_NORNAL = 1
COMPLETE = 2

def main_run():
    global high_enable, wtlink_enable
    global sample_num, sleep_ms
    global opdata_key
    global scr_data
    global topic_id
    wttimer = timer(24 * 3600, period)
    status = IDLE
    complete = False
    timesample = None
    opdata_buf = [{}]
    while True:
        if status == IDLE:
            if wttimer.getSendCheckInFlag() is True:
                mqtt.publish(checkinpub, [{"addr":0,"version":"1.02","hardware":"607"}])
                mqtt.publish(opcheckinpub, [{"addr":0,"version":"1.02","hardware":"607"}])
                wttimer.setSendCheckInFlag(False) 
            if high_enable:
                # I2CDevice._collect_event.set()
                print("开始采集")
                dev:I2CDevice
                for dev in high_device:
                    dev.start_sampling(sleep_ms * 1000, sample_num)    
            status = COLLECT_NORNAL
        if status == COLLECT_NORNAL:
            timesample = round(time.time())
            # 读工况数据
            if wtlink_enable: 
                dev:I2CDevice
                for index, dev in enumerate(wtlink_device):
                    data = ctypes.c_short(dev.read_reg(0x01)).value  # 读取寄存器
                    ma4to20 = round((data * 2.5) / 3900.0 , 3)
                    opdata_buf[0][opdata_key[index]] = ma4to20
                complete = True  
            # 高频数据
            if high_enable:
                thread_complete = False
                while thread_complete is not True:
                    dev:I2CDevice
                    complete_cnt = 0
                    for dev in high_device:
                        if dev.is_sampling_complete() is True:
                            complete_cnt = complete_cnt + 1
                        if complete_cnt == len(high_device):
                            thread_complete = True    
                    time.sleep(1) 
                complete = True
                print("读取完成")
            status = COMPLETE

        if status == COMPLETE:
            if complete is True:
                complete = False
            if wttimer.getSendWaveFlag() is True:
                if wtlink_enable: 
                    opdata_buf[0]['addr'] = "1"
                    opdata_buf[0]['ts'] = timesample
                    mqtt.publish(opdatapub, opdata_buf)    
                    print(f"=1+++={opdata_buf}")
                if high_enable:
                    dev:I2CDevice
                    for dev in high_device:
                        send = {'x': [], 'y': [], 'z': []}
                        wave_data = dev.get_c_data()
                        for item in wave_data:
                            value, timestamps = item
                            current_data = ctypes.c_short(value).value  # 读取寄存器     
                            send['x'].append(round((current_data * 2.5) / 3900.0 , 3))
                        sample_data = [{
                                            "addr": dev.addr,
                                            "id": topic_id,
                                            "ts": timesample,
                                            "x": send['x'],
                                            "y": send['y'],
                                            "z": send['z']
                                        }] 
                        print(f"=1+++={opdata_buf}")
                        mqtt.publish(datapub, sample_data)
                topic_id = topic_id + 1   
                wttimer.setSendWaveFlag(False)
                scr_data['topic_id'] = topic_id
                with open(resourcesPath + 'file/config.json' ,"w") as f:
                    json.dump(scr_data, f)
                print("上发完成")
                
            status = IDLE

if __name__ == "__main__":
    
    topic  = 'WT'
    scr_data = None
    high_enable   = False
    wtlink_enable = False
    with open(resourcesPath + 'file/config.json', 'rb') as load_f:
        context = load_f.read()
        scr_data = json.loads(context)

    mqtt_info = scr_data.get("mqtt_info", {'broker': 'www.witium.com.cn', 'port': 12883, 'user': 'witcd','password': 'Witium37774020'})
    gw_type = scr_data.get("gw_type", "WTG936F")  
    sn = scr_data.get("sn", "20240621") 
    period = scr_data.get("period", 300)   
    opdata_address = scr_data.get("iic_opdata_addr", [])  
    opdata_key = scr_data.get("opdata_key", [])  
    shift_address = scr_data.get("iic_shift_addr", [])  
    sleep_ms = scr_data.get("sleep_ms", 5)
    sample_num = scr_data.get("sample_num", 16384)
    topic_id = scr_data.get("topic_id", 0)

    if len(shift_address) != 0:
        high_enable = True
    if len(opdata_address) != 0: 
        wtlink_enable = True
    
    checkinpub = '%s/%s/%s/CheckIn' %(topic, gw_type, sn)
    opcheckinpub = '%s/WTG93RF/%sW/CheckIn' %(topic, sn)
    datapub = '%s/%s/%s/Data' %(topic, gw_type, sn)
    opdatapub = '%s/WTG93RF/%sW/opData' %(topic, sn)

    high_device = []
    wtlink_device = []
    
    if high_enable:
        dev:I2CDevice
        for index, addr in enumerate(shift_address):
            dev = I2CDevice(index + 1, addr)
            # threading.Thread(target=dev.collect_task, args=(int(sleep_ms * 1000), int(sample_num), )).start() 
            dev.write_reg(0x00, 0x4005)
            dev.write_reg(0x05, 0x2000)
            cfg_reg_value = dev.read_reg(0x00)
            cal_reg_value = dev.read_reg(0x05)
            print(f'addr {index + 1} 配置寄存器0x00: {cfg_reg_value}')
            print(f'addr {index + 1} 校准寄存器0x05: {cal_reg_value}')
            high_device.append(dev)
            del dev
    if wtlink_enable:
        dev:I2CDevice
        for index, addr in enumerate(opdata_address):
            dev = I2CDevice(index + 1, addr)
            threading.Thread(target=dev.collect_task, args=(int(sleep_ms * 1000), int(sample_num), )).start() 
            dev.write_reg(0x00, 0x4005)
            dev.write_reg(0x05, 0x2000)
            cfg_reg_value = dev.read_reg(0x00)
            cal_reg_value = dev.read_reg(0x05)
            print(f'addr {addr} 配置寄存器0x00: {cfg_reg_value}')
            print(f'addr {addr} 校准寄存器0x05: {cal_reg_value}')
            wtlink_device.append(dev)
            del dev    
        
    mqtt = smqtt(mqtt_info, None, None)
    mqtt.open_mqtt()
    threading.Thread(target=mqtt.internet_task).start() 
    time.sleep(2) 
    main_process = threading.Thread(target=main_run, ).start()
    time.sleep(300)
