# -*- coding: UTF-8 -*-
import time
import re  # 正则表达式;
import numpy as np
import zipfile
import gzip
import autoGamma
from mokaSerail import MokaSerial
from caSerail import CASerail


def readPartern():
    f = open(u"cfg.txt")  # 返回一个文件对象
    line = f.readline()  # 调用文件的 readline()方法，一次读取一行
    print(u"第一行", line)
    line = line.replace("\r", "")
    line = line.replace('\n', '')
    TV_COM = line.split(",")[0]
    CA_COM = line.split(",")[1]

    print("value", TV_COM, CA_COM)

    PAR_LIST = []
    while line:
        print(line)
        line = f.readline()
        if line.__len__() != 0:
            line = line.replace("\r", "")
            line = line.replace('\n', '')
            ls_d = line.split(',')
            # PAR_LIST.append(line.split(','))
            PAR_LIST.append([int(ls_d[0]), int(ls_d[1]), int(ls_d[2])])
    f.close()

    print(PAR_LIST)

    return TV_COM, CA_COM, PAR_LIST


def test_all():
    # 读取配置文件;
    TV_COM, CA_COM, PAR_LIST = readPartern()
    NP_LIST = np.array(PAR_LIST)
    # 取第一列,再取第4位到末尾;
    Index11 = NP_LIST[:, 1][3:]
    print("11 pattern", Index11)

    # 打开CA310
    ca = CASerail()
    ca.open(CA_COM, 19200, 7, 'E', 2)
    # 开启CA310
    data = ca.startCommunication()
    print("CA310 开启", data)

    print("CA310 显示模式", data)
    data = ca.set_XYZ_Display()        

    print("CA310 同步模式", data)
    data = ca.setSynchMode(3)
    
    print("CA310 测量速度", data)
    data = ca.setMeasureSpeed(2)
        
    if True:
        time.sleep(0.5)
        print("CA310 零校准", data)
        data = ca.setZeroCalibration()
        
    print("CA310 设置测试通道", data)
    data = ca.setChannel('01')
    
    # 打开TV串口;
    tv = MokaSerial()
    tv.open(TV_COM)
    print("进工厂模式")
    data = tv.enterFactory()

    print("白平衡初始化")
    data = tv.initWhiteBalance()

    print("关闭Localdimming")
    data = tv.closeLocaldimming()

    print("打开内置pattern")
    data = tv.openBuiltInPattern()

    print("切换标准色温")
    data = tv.switchStdColorTemperature()

    print("gamma初始化")
    data = tv.initGamma()

    XYZ_ALL = []
    print("内置pattern切换与CA310读取")
    for item in PAR_LIST:
        # print("item",item)
        if item.__len__() == 3:
            tv.send_parttern([int(item[0]), int(item[1]), int(item[2])])
            time.sleep(0.5)
            X, Y, Z = ca.readDisplay()
            print("CA410数据:", X, Y, Z)

            print("XYZ", X, Y, Z)
            XYZ_ALL.append([X, Y, Z])

    print("关闭内置pattern")
    data = tv.closeBuiltInPattern()

    # 关闭CA310
    data = ca.endCommunication()

    # 调用gamma算法生成gamma.ini
    factory = autoGamma.FiretvFactory()
    RGBcalculator = factory.create()
    print("XYZ_ALL", XYZ_ALL)
    RGB255 = RGBcalculator.calRGB255_for_Debug(np.array(XYZ_ALL[0:3]).T, np.array(XYZ_ALL[3:]).T, np.array(Index11),
                                               0.313, 0.329, 2.2)
    autoGamma.dumpRGB2ini(RGB255)

    # 生成切割文件；
    tv.gen_gzip('gamma.ini', 'gamma_cut.zip')
    # 调用串口命令写入TV中;
    tv.send_gamma('gamma_cut.zip')
    # 使生效;
    tv.send_gamma_active('gamma.ini')

    autoGamma.showRGBcurve(RGB255)


def get_test_result():
    # 读取配置文件;
    TV_COM, CA_COM, PAR_LIST = readPartern()
    NP_LIST = np.array(PAR_LIST)
    # 取第一列,再取第4位到末尾;
    Index11 = NP_LIST[:, 1][3:]
    print("11 pattern", Index11)

    # 打开CA310
    ca = CASerail()
    ca.open(CA_COM, 19200, 7, 'E', 2)
    # 开启CA310
    data = ca.startCommunication()
    print("CA310 开启", data)

    print("CA310 显示模式", data)
    data = ca.set_XYZ_Display()        

    print("CA310 同步模式", data)
    data = ca.setSynchMode(3)
    
    print("CA310 测量速度", data)
    data = ca.setMeasureSpeed(2)
        
    if True:
        time.sleep(0.5)
        print("CA310 零校准", data)
        data = ca.setZeroCalibration()
        
    print("CA310 设置测试通道", data)
    data = ca.setChannel('01')

    # 打开TV串口;
    tv = MokaSerial()
    tv.open(TV_COM)
    print("进工厂模式")
    data = tv.enterFactory()

    print("打开内置pattern")
    data = tv.openBuiltInPattern()


    XYZ_ALL = []
    print("内置pattern切换与CA310读取")
    for item in PAR_LIST:
        # print("item",item)
        if item.__len__() == 3:
            tv.send_parttern([int(item[0]), int(item[1]), int(item[2])])
            time.sleep(0.5)
            X, Y, Z = ca.readDisplay()
            print("CA410数据:", X, Y, Z)

            print("XYZ", X, Y, Z)
            XYZ_ALL.append([X, Y, Z])

    print("关闭内置pattern")
    data = tv.closeBuiltInPattern()

    # 关闭CA310
    data = ca.endCommunication()


if __name__ == "__main__":
    test_all()
