#! python3
# -*- encoding: utf-8 -*-
'''
@File    :   Ramses.py
@Time    :   2023/03/03 11:09:50
@Author  :   Jim @ Yiwin 
@Version :   1.0
@Contact :   jim@yi-win.com
@Desc    :   
@para    :    23 ..07  .... 06  05 04 03  02 01 00
			ip信息不包含
'''

import struct
import numpy as np
from pathlib import Path
from tools.mylogger import log
from myconfig import RamsesAWRAMS, RamsesSURFACE, RamsesPROFILE, DeviceType


class Ramses(object):

    def __init__(self,):
        """
        @description  :处理Ramses的数据标定 Hex -- realWavelength Intensity	
        @param  :  23 ..07  .... 06  05 04 03  02 01 00
                ip信息不包含
        @Returns  :	 realWavelength Intensity	
        @ 积分时间 04 07 ,后一位高位， 选 07
        """
        self.mode       = 0  # 默认0 空气中，1：水中
        self.buf        = b''
        self.buf_ip     = b''
        self.it         = None
        self.light_int  = None  # 未标定的整数值
        self.spectrum   = None  # 光谱强度
        self.ip         = []
        self.cal_cfg    = {}   # 单个传感器标定文件还是多个传感器的？
        pass

    def setBuf( self, buf: bytes ):
        self.buf = buf
        pass

    def setMode( self, mode = 1 ):
        self.mode = mode
        pass

    def setCalCfg(self, d: dict):
        self.cal_cfg = d
        pass

    def getRealWavelength(self, d: dict):
        self.cal_cfg = d
        pass

    def get_ip(self):
        return self.ip

    def getSpectrum(self):
        return self.spectrum
    
    def resetPara(self, ):
        self.buf = b''
        self.it  = None
        self.light_int = None  
        self.spectrum  = None  # 光谱强度
        self.cal_cfg = {}
        pass

    def resetItSpectrum(self, ):
        self.it  = None
        self.spectrum  = None  # 光谱强度
        pass
    


    def dealBuf(self, ip_included:bool=False):
        """
         头部是否包含Ip帧的信息
        ?? 不支持多个传感器的标定文件
        """
        log.info(f" dealBuf  ", __name__)

        res = {}
        len_ = len(self.buf)
        if len_ < 576:
            return
        if ip_included:
            self.buf_ip = self.buf[:26]
            self.ip = self.decode_ip_buf(self.buf_ip, self.cal_cfg)
            self.buf = self.buf[26:]
            len_ = len_ - 26
        if len_ % 576 != 0:
            return

        for i in range( int(len_/576) ):
            res.update( {i+1: {}} )
            temp_buf = self.buf[7:71] + self.buf[79:143] + \
                self.buf[151:215] + self.buf[223:287] + \
                self.buf[295:359] + self.buf[367:431] + \
                self.buf[439:503] + self.buf[511:575]
            self.ConvertAndCalibrate( temp_buf )
        pass

    def ConvertAndCalibrate(self,) -> None:
        '''单个成功数据转化 标定'''
        log.debug(f" ConvertAndCalibrate  ", __name__)
        temp = self.__ConvertBytesToInt( )
        # print( f"int : {self.it}  {temp}" )
        self.__CalibrateSpectrumData( )
        pass

    # 转换一个传感器的部分
    def __ConvertBytesToInt(self ) -> None:
       
        self.it = 2 << int(self.buf[1])  # integrated time
        # self.it = 2 << int(self.buf[0])  # integrated time
        
        self.light_int = struct.unpack(
            "<HHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH   \
                HHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH  \
                HHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH      \
                HHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH", self.buf[2:])
        # print( self.light_int )

    def __CalibrateSpectrumData(self ,) :
        t0 = 8092
        log.debug(f" __CalibrateSpectrumData ..... ", __name__)

        raw = np.asarray(self.light_int, dtype=float)
        B0 = np.asarray(self.cal_cfg["b0"], dtype=float)
        B1 = np.asarray(self.cal_cfg["b1"], dtype=float)

        Mn = raw/65535
        Bn = B0 + B1 * ( self.it/t0 )
        Cn = Mn-Bn

        Offset = self.getOffset(
            Cn, int(self.cal_cfg['DarkPixelStart']), int(self.cal_cfg['DarkPixelStop']))
        Dn = Cn - Offset
        En = Dn * ( t0/self.it )
        if self.mode == 0:
            Fn = En/np.asarray(self.cal_cfg["cal"], dtype=float)   # 空气的标定文件
        else:
            Fn = En/np.asarray(self.cal_cfg["calaq"], dtype=float)   # 水中的标定文件
        # Fn = En/np.asarray(self.cal_cfg["cal"], dtype=float)   # 空气或水中的标定文件
        self.spectrum = Fn
        # print(self.spectrum)


    def getOffset(self, data: np.ndarray, start: int, stop: int):
        ret = 0.0
        for i in range(start-1, stop, 1):
            ret = ret + data[i]
        return ret / (stop - start + 1)
    
    def removeMask(self, buf:bytes ) -> bytes:
        '''去除遮罩 0x64 0x65 0x66 0x67'''
        ret = b''
        flag = False
        blen = len(buf)
        for i in range(blen):
            if flag == False and buf[i] == 64 :
                flag = True
                continue
            if flag == False and buf[i] != 64 :
                ret = ret + buf[i].to_bytes( 1, byteorder = 'big' )
                continue
            if flag == True  and buf[i]     == 100:
                ret = ret + b'\x40'
                flag = False
                continue
            if flag == True  and buf[i]     == 101:
                ret = ret + b'\x23'
                flag = False
                continue
            if flag == True and buf[i]      == 102:
                ret = ret + b'\x11'
                flag = False
                continue
            if flag == True  and buf[i]     == 103:
                ret = ret + b'\x13'
                flag = False    
                continue
        return  ret            
        pass

    def decode_ip_buf(self, buf, ip_cal:dict):
        tmpbuf = buf
        if len(tmpbuf) ==26 and tmpbuf[0] == 0x13:
           tmpbuf = tmpbuf[2:]
           
        Incl_XGain      = float(ip_cal['Incl_XOffset'] )
        Incl_XOffset    = float(ip_cal['Incl_XOffset'] )
        Incl_YGain      = float(ip_cal['Incl_YGain'] )
        Incl_YOffset    = float(ip_cal['Incl_YOffset'] )
        
        Incl_KRef               = float(ip_cal['Incl_KRef'] )
        Press_Sens_mV_bar_1mA   = float(ip_cal['Press_Sens_mV_bar_1mA'] )
        Incl_KBG                = float(ip_cal['Incl_KBG'] )
        Press_Sens_mV_bar_4mA   = float(ip_cal['Press_Sens_mV_bar_4mA'] )
        Press_Gain              = float(ip_cal['Press_Gain'] )
        Press_Surface_bar       = float(ip_cal['Press_Surface_bar'] )

    
        ip_info = struct.unpack("<BBBBBBBBBBBBBBBBBBBBBBBB", buf)
        byte11 = ip_info[11]
        byte12 = ip_info[12]
        byte13 = ip_info[13]
        byte14 = ip_info[14]
        byte15 = ip_info[15]
        byte16 = ip_info[16]
        byte17 = ip_info[17]
        byte18 = ip_info[18]
        byte19 = ip_info[19]
        byte20 = ip_info[20]
        byte21 = ip_info[21]
        byte22 = ip_info[22]
        
        X = (byte11 -Incl_XOffset) /  Incl_XGain  # 单位 度
        Y = (byte12 - Incl_YOffset ) /  Incl_YGain  # 单位 度
        npress = byte14 *256 + byte13
        nbg     = byte18 * 256 + byte17
        nrefh   = byte20 * 256 + byte19
        nrefl   = byte22 * 256 + byte21
        noffset = nrefl - ( Incl_KRef  * (nrefh-nrefl))
        VPress  =  Incl_KBG * (npress-noffset) / (nbg- noffset) #电压值
        press_sens =  Press_Sens_mV_bar_4mA 
        if press_sens <= 0:
            press_sens = 4* Press_Sens_mV_bar_1mA 
        p_bar = 1000 * VPress / (press_sens *  Press_Gain )
        press_delta = p_bar - 1.021
        depth_m = press_delta * 10
        return  [depth_m,X,Y] 
    
    def getWavelength(self,) -> list:
        ret = []
        for i in range(1,256):
            tmp = float(self.cal_cfg['c0s']) + float(self.cal_cfg['c1s'])*i \
                        + float(self.cal_cfg['c2s'])*i*i + float(self.cal_cfg['c3s'])*i*i*i
            ret.append(tmp)
            pass
        return ret
    pass

    def printPara(self, ):
        print(f"**************Ramses printPara*******************")
        print(f"{self.buf}")
        print(f"{self.cal_cfg}")
        print(f"{self.it}")
        print(f"{self.light_int}")
        print(f"{self.spectrum}")
        print(f"**************Ramses printPara*******************")
        pass

if __name__ == "__main__":
    log.info(f"******** Awarms server initiate   *********", __name__, "", "")
    r = Ramses()
    buf_str = "\
        23a0000007fefe0a0781067d067d068e0693069c069c06b006b506cb06e40619076607e1076c081509cd09bb0a7d0bee0b1d0c6d0cca0ca40ddc0f30135b18b4224d320e43f852c8\
        23a0000006fefe17639c71c97c9484bb89358be98e5d98b1a37eadccb66abd26be31b97db124aa18a3f29c0499349735968e93a48eea8a028bc28cec8d048f1c92c096de9ab99d43\
        23a0000005fefee0a157a9ecb1b1b97dc034c507c741c7d2c65ec550c20dbde9b535ae56a60a9e2296cd8ee887278129798170c669b16503632e61605f3a5def5a8e5862561154be\
        23a0000004fefe3c51f54dda4a0c48634595426a3f5a3cc539903767362b36cc351f356634b633fc32c4310630fb2ec32fe63199349037e03ac03dc03eae3c303a9639d13a413da7\
        23a0000003fefe97412746bc49404caa4dc54d374ca646d63bde326b332739e43c503d2b3c363aca37ef342d32c22f782d1d2bd328ec250222101e691b2b1a7119d3184018fa174d\
        23a0000002fefed3177a17e3160616f81423149313f11233126711d8103b10a40f160f8a0efb0d580d660c6f0bd80aa10a580a000ab4099b0994097109e2082c087a0736072c077d\
        23a0000001fefe2a071e071607140718071e073c074d076a076e076b076007670763076c0760075c073d07350724071207fb06ef06d706cc06b706a506960684067b0672066306a2\
        23a0000000fefe58065406500642064e064306470642063f064806410644064306430641064206460640063c063e063e063d064406430644063c063c063c063c06400640064906ed\
        23a0000007fefe0a071b071c07260737073e0749075907650774078b07c0072c08e3082b0ada0be80d9c107b147318931ae51add1a271a77192f1bfb1d99207c265c30c738f03d53\
        23a0000006fefe07438f489d4d8452d957945cff639171a5832a97deab7fbe09c86cc5acb9d5ab299e90915287de7f8b7ae275ed6f056aff664f662665bc63936335655767926879\
        23a0000005fefec269206d3e724377fe7b7a8050831f85b68637881689e4884787008580823d7f887bee773d7496702a6cde654c5f895a1f570d5416514d4e9d4bde4897468c44c3\
        23a0000004fefe71421640db3dc83bbb39533777346c31b92e912c152b5b2aff292129e727cb26d925fd249223b4214020da1fe91ff41f28209420dc201520071e671c221c8d1cfe\
        23a0000003fefecd1dd31fe72164235924cb24b924f72331211e1ca018ef19221d121f621fe91e081ed51c761b311a2f193c18651788166015a013de11d1106e1041101810e80f2e\
        23a0000002fefee50fd90fbc0f6d0ff70e610ee00d930d460de40c900c450c010cbd0b7c0b480bfc0aab0a2c0a9e094d092b09fb08d008a208990881087d083908e6078d07660747\
        23a0000001fefe5b075a07500751074d074e0751075d076807730788077e077c077c07810777077a076c0765075c075607480740073607270723070d070d070b07ff06fd06f0062f\
        23a0000000fefef606f106ed06f506ef06eb06f106ec06f006e906e806ed06e606ef06e506ea06ec06ee06eb06e906ee06f006ef06ea06e906e606e606e606ec06ea06ea06f506f2\
        23a0000007fefe0605830479047d047e04810482048204850487048b048c04850487048c049304950498049c04a804a904b604b804c604d004e104f104190546059805ff059a06bb\
        23a0000006fefe90073209ea0b7610c117cc22b2324a487b645e8798acf2c927d28dc1f2a1ac809664804e543d7a308327a321d81dab1b0f1bca1bb41dba2098243329382e773335\
        23a0000005fefeca38213e544329486f4c1c500653335592564f577d573b57a556b4557e540a534451424f004d714a9b47994458410e3e9c3af8368c33b630982eca2c052b3429ae\
        23a0000004fefe632763255a234821321f0e1d061b291983171e16d814a91379124b1138104b0f610e990dd80c240c880bfc0a7b0af8097709020990082508de07c507ba07a50762\
        23a0000003fefe950781076407460727070007d306ab066e06270605060d0614061306fe05e805d105b405a00586057105630549053d0528051105fd04f304ee04e404dc04dd04c3\
        23a0000002fefed804d904d004c604bf04b904b904b104a804a604a6049d04980496048f04970491048c04880486047e0484047a047d047b047c0478047a04760476047004700430\
        23a0000001fefe6f0474046c046d0472046d047304750470046e04760472046f047604700473046f04730470047504700470046d046b047004710470046e046d046a046b046904e4\
        23a0000000fefe690470046e046b046c04680468046e0466046a046a0469046b046d04640466046c046c046b046a04660466046b046c046a046a0468046f046804740471048d0417\
        "
    buf = bytearray.fromhex(buf_str)
    one_senor = buf[:576]
    r.setHex(one_senor)
    r.ConvertBytesToInt()
    # print(len(buf))
    # # print(buf[:576])
    # print(buf[:576].hex())
    # print(buf[576:578].hex() )