from pickletools import pyinteger_or_bool
import socket
import sys
import time
import re
import threading
import datetime
import sys
import configparser
import signal

# 定义回调函数
def myHandler(signum, frame):
    print("接收信号为：", signum)
    exit(0)
# 等待接收 signal.SIGTERM命令
signal.signal(signal.SIGTERM, myHandler)

argv = sys.argv[1:]
tcp_port = int(argv[0])

map_work_status_lock = threading.Lock()  # 锁的声明
"""字典 数据存放的map 使用锁进行读写访问"""

map_work_status = {
                    "DevEnvTemp":  "2230",
                    "ControlMode":  "1",
                    "TxModuleRFPow":  "1234",
                    "RxModuleRFPow":  "1234",
                    "TxModuleOpPow":  "1234",
                    "RxModuleOpPow":  "1234",
                    "TxModuleWorkMode":  "1",
                    "RxModuleWorkMode":  "2",
                    "TxModuleATT":  "11.1",
                    "RxModuleATT":  "222",
                    "TxModuleAGC":  "333",
                    "RxModuleAGC":  "444",
                    "TxModuleTemp":  "1750",
                    "RxModuleTemp":  "1760",
                    "TxModuleRFPowAlarmThreshold":  "180",
                    "RxModuleRFPowAlarmThreshold":  "180",
                    "TxModuleOpPowAlarmThreshold":  "-2900",
                    "RxModuleOpPowAlarmThreshold":  "-3000",
                    "TxModuleopticalPowerLow":  "0",
                    "TxModuleopticalPowerHight":  "0",
                    "TxModuleRFPowerLow":  "0",
                    "TxModuleRFPowerHight":  "0",
                    "TxModuleWorkStatus":  "0",
                    "RxModuleopticalPowerLow":  "0",
                    "RxModuleopticalPowerHight":  "0",
                    "RxModuleRFPowerLow":  "0",
                    "RxModuleRFPowerHight":  "0",
                    "RxModuleWorkStatus":  "0",
                    "DeviceWorkStatus":  "1"
                }
"""字段中文名"""
map_name_chg = {
                "DevEnvTemp":  "设备环境温度 精度0.01",
                "ControlMode":  "设备控制模式",
                "TxModuleRFPow":  "发射模块射频功率",
                "RxModuleRFPow":  "接收模块射频功率",
                "TxModuleOpPow":  "发送模块光功率",
                "RxModuleOpPow":  "接收模块光功率",
                "TxModuleWorkMode":  "发射模块工作模式",
                "RxModuleWorkMode":  "接收模块工作模式",
                "TxModuleATT":"发射模MGC块衰减值",
                "RxModuleATT":  "接收模MGC块衰减值",
                "TxModuleAGC":  "发射模块AGC衰减值",
                "RxModuleAGC":  "接收模块AGC衰减值",
                "TxModuleTemp":  "发射模块温度",
                "RxModuleTemp":  "接收模块温度",
                "TxModuleRFPowAlarmThreshold":  "发射模块射频功率告警门限",
                "RxModuleRFPowAlarmThreshold":  "接收模块射频功率告警门限",
                "TxModuleOpPowAlarmThreshold":  "发射模块光功率告警门限",
                "RxModuleOpPowAlarmThreshold":  "接收模块光功率告警门限",
                "TxModuleopticalPowerLow":  "发射模块光功率过小",
                "TxModuleopticalPowerHight":  "发射模块光功率过大",
                "TxModuleRFPowerLow":  "发射模块射频功率过小",
                "TxModuleRFPowerHight":  "发射模块射频功率过大",
                "TxModuleWorkStatus":  "发射模块工作状态",
                "RxModuleopticalPowerLow":  "接收模块光功率过小",
                "RxModuleopticalPowerHight":  "接收模块光功率过大",
                "RxModuleRFPowerLow":  "接收模块射频功率过小",
                "RxModuleRFPowerHight":  "接收射模块射频功率过大",
                "RxModuleWorkStatus":  "接收模块工作状态",
                "DeviceWorkStatus":  "设备工作状态"
                }

packet_head =bytearray([0xAA,0x55,0x00,0x9C,0x00,0x30,0x00,0x00,0x00,0xA8,0x02,0x01,0x00,0x00,0x00,0x00,0x02,0x00,0x01,0xC2,0x00,0x03,0xC0,0xA8,0x01,0xB3,0x04,0x00,0x00,0x1F,0x90,0x05,0xFF,0xFF,0xFF,0x00,0x06,0xC0,0xA8,0x01,0x01,0x07,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0x0E,0x00,0x00,0x00,0x00,0x0F,0x00,0x00,0x00,0x00])
# print("1111111111111111     ",packet_head)
tem_packet_str=""
def genCRC(tem_packet_str):
    sum=0
    size =len(tem_packet_str)
    # print("size == ", size)
    for num in range(2,size):
        sum=sum+(tem_packet_str[num])
        # print("sum == ",sum)
    # print("sum == ",sum)
    # print("%#x"%sum)
    crc=sum&0xff
    # print("%#x"%crc)
    return crc
def packet_string():
    tx_module_code =bytes([0x00,0xff])
    rx_module_code =bytes([0x01,0xff])
    packet_info=bytes()
    map_work_status_lock.acquire()
    cmd_value =bytes([0x10]) #设备环境温度
    value = int(map_work_status["DevEnvTemp"])
    # print(value,"   ",type(value))
    value_byte =value.to_bytes(4,"big")
    # print(value_byte,"   ",type(value_byte))
    packet_info=packet_info+cmd_value+value_byte

    cmd_value =bytes([0x20]) #设备控制模式
    value = int(map_work_status["ControlMode"])
    value_byte =value.to_bytes(4,"big")
    packet_info=packet_info+cmd_value+value_byte

    cmd_value =bytes([0x21]) #射频功率
    packet_info=packet_info+cmd_value
    value = int(map_work_status["TxModuleRFPow"])  #发射模块
    value_byte =value.to_bytes(2,"big")
    packet_info=packet_info+tx_module_code+value_byte
    value = int(map_work_status["RxModuleRFPow"])  #接收模块
    value_byte =value.to_bytes(2,"big")
    packet_info=packet_info+rx_module_code+value_byte

    cmd_value =bytes([0x22]) #光功率
    packet_info=packet_info+cmd_value
    value = int(map_work_status["TxModuleOpPow"])  #发射模块
    value_byte =value.to_bytes(2,"big")
    packet_info=packet_info+tx_module_code+value_byte
    value = int(map_work_status["TxModuleOpPow"])  #接收模块
    value_byte =value.to_bytes(2,"big")
    packet_info=packet_info+rx_module_code+value_byte

    cmd_value =bytes([0x23]) #工作模式
    packet_info=packet_info+cmd_value
    value = int(map_work_status["TxModuleWorkMode"])  #发射模块
    value_byte =value.to_bytes(2,"big")
    packet_info=packet_info+tx_module_code+value_byte
    value = int(map_work_status["RxModuleWorkMode"])  #接收模块
    value_byte =value.to_bytes(2,"big")
    packet_info=packet_info+rx_module_code+value_byte

    cmd_value =bytes([0x24]) #MGC衰减值 
    packet_info=packet_info+cmd_value
    value = int(float(map_work_status["TxModuleATT"])*10)  #发射模块
    value_byte =value.to_bytes(2,"big")
    packet_info=packet_info+tx_module_code+value_byte
    value = int(float(map_work_status["RxModuleATT"])*10)  #接收模块
    value_byte =value.to_bytes(2,"big")
    packet_info=packet_info+rx_module_code+value_byte

    cmd_value =bytes([0x25]) #MGC衰减值 
    packet_info=packet_info+cmd_value
    value = int(float(map_work_status["TxModuleAGC"])*10)  #发射模块
    value_byte =value.to_bytes(2,"big")
    packet_info=packet_info+tx_module_code+value_byte
    value =int(float(map_work_status["RxModuleAGC"])*10)  #接收模块
    value_byte =value.to_bytes(2,"big")
    packet_info=packet_info+rx_module_code+value_byte

    packet_info=packet_info+bytes([0x26,0x00,0x00,0x00,0x00,0x01,0x00,0x00,0x00]) #激光参考电压

    cmd_value =bytes([0x2C]) #模块温度
    packet_info=packet_info+cmd_value
    value = int(map_work_status["TxModuleTemp"])  #发射模块
    value_byte =value.to_bytes(2,"big")
    packet_info=packet_info+tx_module_code+value_byte
    value = int(map_work_status["RxModuleTemp"])  #接收模块
    value_byte =value.to_bytes(2,"big")
    packet_info=packet_info+rx_module_code+value_byte

    cmd_value =bytes([0x2D]) #射频功率告警门限
    packet_info=packet_info+cmd_value
    value = int(map_work_status["TxModuleRFPowAlarmThreshold"])  #接收模块
    if(value<0):
        value = 65536+int(map_work_status["TxModuleRFPowAlarmThreshold"])  #发射模块
    # print(value,"   ",type(value))
    value_byte =value.to_bytes(2,"big")
    # print(value_byte,"   ",type(value_byte))
    # value_byte =value.to_bytes(2,"big")
    packet_info=packet_info+tx_module_code+value_byte
    value = int(map_work_status["RxModuleRFPowAlarmThreshold"])  #接收模块
    if(value<0):
        value =  65536+int(map_work_status["RxModuleRFPowAlarmThreshold"])  #接收模块
    value_byte =value.to_bytes(2,"big")
    packet_info=packet_info+rx_module_code+value_byte

    cmd_value =bytes([0x2E]) #光功率告警门限
    packet_info=packet_info+cmd_value
    value = int(map_work_status["TxModuleOpPowAlarmThreshold"])  #接收模块
    if(value<0):    
        value =   65536+int(map_work_status["TxModuleOpPowAlarmThreshold"])  #发射模块
    value_byte =value.to_bytes(2,"big")
    packet_info=packet_info+tx_module_code+value_byte
    value = int(map_work_status["RxModuleOpPowAlarmThreshold"])  #接收模块
    if(value<0):     
        value =   65536+int(map_work_status["RxModuleOpPowAlarmThreshold"])  #接收模块
    value_byte =value.to_bytes(2,"big")
    packet_info=packet_info+rx_module_code+value_byte

    # 发射模块的工作状态;取最后一个字节状态值转换成二进制，bit0:工作状态（0异常，1正常）；
    # bit1:射频功率大（0正常，1大）；bit2:射频功率小（0正常，1小）；bit3:光功率大（0正常，1大）；bit4:光功率小（0正常，1小）

# TxModuleopticalPowerLow	发射模块光功率过小
# TxModuleopticalPowerHight	发射模块光功率过大
# TxModuleRFPowerLow	发射模块射频功率过小
# TxModuleRFPowerHight	发射模块射频功率过大
# TxModuleWorkStatus	发射模块工作状态
    cmd_value =bytes([0x2F]) #光功率告警门限
    packet_info=packet_info+cmd_value
    value = \
            int(map_work_status["TxModuleopticalPowerLow"],2)<<4|\
            int(map_work_status["TxModuleopticalPowerHight"],2)<<3|\
            int(map_work_status["TxModuleRFPowerLow"],2)<<2|\
            int(map_work_status["TxModuleRFPowerHight"],2)<<1|\
            int(map_work_status["TxModuleWorkStatus"],2)    
    # print(bin(value)," 111111111111111  ",type(value))
    value_byte =value.to_bytes(4,"big")     #接收模
    packet_info=packet_info+value_byte

# 发射模块的工作状态;取最后一个字节状态值转换成二进制，bit0:工作状态（0异常，1正常）；
# bit1:射频功率大（0正常，1大）；bit2:射频功率小（0正常，1小）；bit3:光功率大（0正常，1大）；bit4:光功率小（0正常，1小）
# RxModuleopticalPowerLow	接收模块光功率过小
# RxModuleopticalPowerHight	接收模块光功率过大
# RxModuleRFPowerLow	接收模块射频功率过小
# RxModuleRFPowerHight	接收射模块射频功率过大
# RxModuleWorkStatus	接收模块工作状态
     #发射模块     
    value = \
            int(map_work_status["RxModuleopticalPowerLow"],2)<<4|\
            int(map_work_status["RxModuleopticalPowerHight"],2)<<3|\
            int(map_work_status["RxModuleRFPowerLow"],2)<<2|\
            int(map_work_status["RxModuleRFPowerHight"],2)<<1|\
            int(map_work_status["RxModuleWorkStatus"],2)    
    # print(bin(value)," 111111111111111  ",type(value))
    value_byte =value.to_bytes(4,"big")     #接收模
    packet_info=packet_info+value_byte

    # DeviceWorkStatus	设备工作状态
    value = int(map_work_status["RxModuleWorkStatus"])    
    # print(bin(value)," 111111111111111  ",type(value))
    value_byte =value.to_bytes(4,"big")     #接收模
    packet_info=packet_info+value_byte

    packet_info=packet_head+packet_info
    # print(packet_info,"   ",type(packet_info))

    map_work_status_lock.release()
    crc =genCRC(packet_info)
    packet_info=packet_info+bytes([crc]) #crc

    return packet_info
    # return packet_head+packet_info.encode("utf-8")
def packet_status_string():
    map_work_status_lock.acquire()
    packet_info=\
        map_name_chg["DevEnvTemp"]+" : "+map_work_status["DevEnvTemp"]+"\r\n"+\
        map_name_chg["ControlMode"]+" : "+map_work_status["ControlMode"]+"\r\n"+\
        map_name_chg["TxModuleRFPow"]+" : "+map_work_status["TxModuleRFPow"]+"\r\n"+\
        map_name_chg["RxModuleRFPow"]+" : "+map_work_status["RxModuleRFPow"]+"\r\n"+\
        map_name_chg["TxModuleOpPow"]+" : "+map_work_status["TxModuleOpPow"]+"\r\n"+\
        map_name_chg["RxModuleOpPow"]+" : "+map_work_status["RxModuleOpPow"]+"\r\n"+\
        map_name_chg["TxModuleWorkMode"]+" : "+map_work_status["TxModuleWorkMode"]+"\r\n"+\
        map_name_chg["RxModuleWorkMode"]+" : "+map_work_status["RxModuleWorkMode"]+"\r\n"+\
        map_name_chg["TxModuleATT"]+" : "+map_work_status["TxModuleATT"]+"\r\n"+\
        map_name_chg["RxModuleATT"]+" : "+map_work_status["RxModuleATT"]+"\r\n"+\
        map_name_chg["TxModuleAGC"]+" : "+map_work_status["TxModuleAGC"]+"\r\n"+\
        map_name_chg["RxModuleAGC"]+" : "+map_work_status["RxModuleAGC"]+"\r\n"+\
        map_name_chg["TxModuleTemp"]+" : "+map_work_status["TxModuleTemp"]+"\r\n"+\
        map_name_chg["RxModuleTemp"]+" : "+map_work_status["RxModuleTemp"]+"\r\n"+\
        map_name_chg["TxModuleRFPowAlarmThreshold"]+" : "+map_work_status["TxModuleRFPowAlarmThreshold"]+"\r\n"+\
        map_name_chg["RxModuleRFPowAlarmThreshold"]+" : "+map_work_status["RxModuleRFPowAlarmThreshold"]+"\r\n"+\
        map_name_chg["TxModuleRFPowAlarmThreshold"]+" : "+map_work_status["TxModuleRFPowAlarmThreshold"]+"\r\n"+\
        map_name_chg["RxModuleRFPowAlarmThreshold"]+" : "+map_work_status["RxModuleRFPowAlarmThreshold"]+"\r\n"+\
        map_name_chg["TxModuleopticalPowerLow"]+" : "+map_work_status["TxModuleopticalPowerLow"]+"\r\n"+\
        map_name_chg["TxModuleopticalPowerHight"]+" : "+map_work_status["TxModuleopticalPowerHight"]+"\r\n"+\
        map_name_chg["TxModuleRFPowerLow"]+" : "+map_work_status["TxModuleRFPowerLow"]+"\r\n"+\
        map_name_chg["TxModuleRFPowerHight"]+" : "+map_work_status["TxModuleRFPowerHight"]+"\r\n"+\
        map_name_chg["TxModuleWorkStatus"]+" : "+map_work_status["TxModuleWorkStatus"]+"\r\n"+\
        map_name_chg["RxModuleopticalPowerLow"]+" : "+map_work_status["RxModuleopticalPowerLow"]+"\r\n"+\
        map_name_chg["RxModuleopticalPowerHight"]+" : "+map_work_status["RxModuleopticalPowerHight"]+"\r\n"+\
        map_name_chg["RxModuleRFPowerLow"]+" : "+map_work_status["RxModuleRFPowerLow"]+"\r\n"+\
        map_name_chg["RxModuleRFPowerHight"]+" : "+map_work_status["RxModuleRFPowerHight"]+"\r\n"+\
        map_name_chg["RxModuleWorkStatus"]+" : "+map_work_status["RxModuleWorkStatus"]+"\r\n"+\
        map_name_chg["DeviceWorkStatus"]+" : "+map_work_status["DeviceWorkStatus"]
    map_work_status_lock.release()
    # print("11111111111122222222222222222: ",packet_info)
    return packet_info
initstr=packet_status_string()
print("初始化数据：\r\n" + initstr)
tem_packet_str = packet_string()
print("tem_packet_str len ==: ",len(tem_packet_str))
sum=0


tcpServer_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)  # 1创建socket对象
tcpServer_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
tcpServer_socket.bind(('0.0.0.0', tcp_port))  # 2，需要自己绑定一个ip地址和端口号
tcpServer_socket.listen(1)  # 可以同时监听3个，但是这里只有一个因为没有写多线程
client_socket, addr = tcpServer_socket.accept()  # 阻塞 是服务端的socket对象clientServer_socket是接入的客户端socket对象
TCP_LINK_STATUS = 1  # TCP 连接标志位



""" 状态查询指令 回调函数 """
def HY_DChLBandOT_Query_CallBack(recv_cmd):
    # print(recv_cmd.hex()) binascii.unhexlify(hex_str.encode())
    tem_packet_str = packet_string()
    if (TCP_LINK_STATUS != 0):
        client_socket.send((tem_packet_str))


""" 参数设置指令 回调函数"""
def HY_HSM_ParamSetting_CallBack(recv_cmd):
    buf = recv_cmd[6:].decode()
    # print("11111111111 == " ,buf)
    map_work_status_lock.acquire()
    map_work_status["ControlMode"]=buf[0]
    map_work_status["Demodulation"]=buf[1]
    map_work_status["CepstrumSate"]=buf[2]
    map_work_status["SignalRate"]=buf[3:13]
    map_work_status["DifferentialDecoding"]=buf[13]
    map_work_status["FEC"]=buf[14]
    map_work_status["DecodingChannels"]=buf[15]
    map_work_status["ConvolutionalDecodingState"]=buf[16]
    map_work_status["RSDecoding"]=buf[17]
    map_work_status["RSChannels"]=buf[18]
    map_work_status["RSDepth"]=buf[19]
    map_work_status["Descrambling"]=buf[20]
    map_work_status["IPPacketSize"]=buf[21]
    map_work_status["FrameDetect"]=buf[22]
    map_work_status["SYNCLength"]=buf[23]
    map_work_status["FrameLength"]=buf[24:29]
    map_work_status["SYNC_I"]=buf[29:45]
    map_work_status["SYNC_Q"]=buf[45:61]
    map_work_status["CRC_Switch"]=buf[61]
    # map_work_status["Demodulation"]=
    map_work_status_lock.release()
    tem_packet_str = bytearray([0xeb,0x90,0x3E, 0X00])+recv_cmd[4:]
    # tem_packet_str = packet_string()

    if (TCP_LINK_STATUS != 0):
        client_socket.send((tem_packet_str))

""" 设置设备控制模式 回调函数 """
def HY_DChLBandOT_ControlMode_CallBack(recv_cmd):
    value=0
    value = recv_cmd[9]
    print(value)
    map_work_status_lock.acquire()
    map_work_status["ControlMode"]=str(value)
    map_work_status_lock.release()




""" 设置衰减指令 回调函数 """
def HY_DChLBandOT_SetATTd_CallBack(recv_cmd):
    module=0
    module = recv_cmd[6]
    value =int((recv_cmd[8]))
    # print("1111111111value == ",value)
    value1 =int((recv_cmd[9]))
    # print("1111111111value == ",value1)    
    value2 =value<<8|value1
    # print("1111111111value == ",value2)    
    ATT_value=0.0
    ATT_value = float(value2)/10
    # print("22222222222ATT_value == ",ATT_value)
    map_work_status_lock.acquire()
    # print("2333333333333333recv_cmd = ",recv_cmd)
    if(module == 0): #发射模块
        if(ATT_value!=6553.5):
            map_work_status["TxModuleATT"]=str(ATT_value)
            map_work_status["TxModuleWorkMode"]="0"
            print("ATT_value == ",(ATT_value))
        else:
            map_work_status["TxModuleAGC"]=str(222)
            map_work_status["TxModuleWorkMode"]="1"
    else:
        if(ATT_value!=6553.5):
            map_work_status["RxModuleATT"]=str(ATT_value)
            map_work_status["RxModuleWorkMode"]="0"

        else:
            map_work_status["RxModuleAGC"]=str(111)
            map_work_status["RxModuleWorkMode"]="1"

    map_work_status_lock.release()



map_calBackFun = {"0030": HY_DChLBandOT_Query_CallBack,
                "0120":HY_DChLBandOT_ControlMode_CallBack,
                "0121":HY_DChLBandOT_SetATTd_CallBack

}


"""定时读取 map_work_status 发布设备状态报文 间隔200ms"""
def SendStatusHandle():
    print("线程1")
    global client_socket
    cont = 0
    cont_print = 0
    max_cont = 10000
    while max_cont:
        # tem_packet_str =""
        # tem_packet_str = packet_string()
        # if (TCP_LINK_STATUS != 0):
        #     max_cont = max_cont - 1
        #     client_socket.send(tem_packet_str)
        cont = cont + 1
        if (cont > 2 and TCP_LINK_STATUS):
            cont_print = cont_print + 1
            tem_status_str = packet_status_string()
            print("=============== 打印当前模拟设备状态 ================= ", cont_print)
            print(tem_status_str)
            cont = 0
        time.sleep(1)


""" 一个模拟接收端，收到设置类型的指令后，修改 map_work_status。"""
def RecvSetCMDHandle():
    print("线程2")
    global TCP_LINK_STATUS
    global client_socket
    while 1:
        data = client_socket.recv(1024)
        # print("data: ",data)
        if (len(data) > 0):
            rec_str = data[4:6]
            print(rec_str.hex())
            cmd=rec_str.hex()
            # if(len(data)==7):
            #     cmd = rec_str[0:5]
            #     print("1111111",cmd)#查询指令
            # elif(len(data)==10 or len(data)==11):
            #     cmd = rec_str[0:4]
            #     print("1111111",cmd)#设置指令
            if (cmd in map_calBackFun):
                map_calBackFun[cmd](data)
            else:
                print("收到未知报文 : " + rec_str.hex())
        else:
            TCP_LINK_STATUS = 0
            print("连接断开，等待接入")
            client_socket.close()
            client_socket, addr = tcpServer_socket.accept()  # s是服务端的socket对象clientServer_socket是接入的客户端socket对象
            TCP_LINK_STATUS = 1
            print(addr)
            cont = 0
            time.sleep(1)


if __name__ == '__main__':
    tr1 = threading.Thread(target=SendStatusHandle)
    tr2 = threading.Thread(target=RecvSetCMDHandle)
    tr1.start()
    tr2.start()
