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 使用锁进行读写访问"""
# DevEnvTemp	设备环境温度 精度0.01
# ControlMode	设备控制模式
# TxModuleRFPow	发射模块射频功率
# RxModuleRFPow	接收模块射频功率
# TxModuleOpPow	发送模块光功率
# RxModuleOpPow	接收模块光功率
# TxModuleWorkMode	发射模块工作模式
# RxModuleWorkMode	接收模块工作模式
# TxModuleATT	发射模MGC块衰减值
# RxModuleATT	接收模MGC块衰减值
# TxModuleAGC	发射模块AGC衰减值
# RxModuleAGC	接收模块AGC衰减值
# TxModuleTemp	发射模块温度
# RxModuleTemp	接收模块温度
# TxModuleRFPowAlarmThreshold	发射模块射频功率告警门限
# RxModuleRFPowAlarmThreshold	接收模块射频功率告警门限
# TxModuleRFPowAlarmThreshold	发射模块光功率告警门限
# RxModuleRFPowAlarmThreshold	接收模块光功率告警门限
# TxModuleopticalPowerLow	发射模块光功率过小
# TxModuleopticalPowerHight	发射模块光功率过大
# TxModuleRFPowerLow	发射模块射频功率过小
# TxModuleRFPowerHight	发射模块射频功率过大
# TxModuleWorkStatus	发射模块工作状态
# RxModuleopticalPowerLow	接收模块光功率过小
# RxModuleopticalPowerHight	接收模块光功率过大
# RxModuleRFPowerLow	接收模块射频功率过小
# RxModuleRFPowerHight	接收射模块射频功率过大
# RxModuleWorkStatus	接收模块工作状态
# DeviceWorkStatus	设备工作状态


map_work_status = {
                "ControlMode": "0",
                "Demodulation": "0",
                "CepstrumSate": "0",
                "SignalRate": "123456.789",
                "DifferentialDecoding": "0",
                "FEC": "0",
                "DecodingChannels": "1",
                "ConvolutionalDecodingState": "0",
                "RSDecoding": "0",
                "RSChannels": "1",
                "RSDepth": "1",
                "Descrambling": "0",
                "IPPacketSize": "0",
                "FrameDetect": "0",
                "SYNCLength": "1",
                "FrameLength": "01024",
                "SYNC_I": "000000001ACFFC1D",
                "SYNC_Q": "000000001ACFFC1D",
                "CRC_Switch": "0",
                "IFInputStatus": "0",
                "DSStatus": "0",
                "DecodingIndication": "0",
                "Eb_No": "12.5",
                "DemodulationBitErrorRate": "1.2-34",
                "IF_Level": "-12.5",
                # "RemDataLinkStatus": "远程数据传输终端连接状态", 这个模拟的也不会有
                # "ERRORINFO": "参数设置状态", 这个暂时不用
                "StartTime": "11111111111111",
                "EndTime": "2222222222222",
                "targetID": "33333",
                "frequency": "1234.5"
                }
    # ControlMode	控制模式
    # Demodulation	接收信号解调方式
    # CepstrumSate	接收信号倒谱状态
    # SignalRate	接收信号信息速率
    # DifferentialDecoding	差分译码
    # FEC	前向纠错
    # DecodingChannels	前向纠错译码路数
    # ConvolutionalDecodingState	卷积译码状态
    # RSDecoding	RS译码状态
    # RSChannels	RS译码路数
    # RSDepth	RS译码交织深度
    # Descrambling	去扰状态
    # IPPacketSize	IP包长设置
    # FrameDetect	帧检测
    # SYNCLength	同步码长度
    # FrameLength	帧长度
    # SYNC_I	I路同步码型
    # SYNC_Q	Q路同步码型
    # CRC_Switch	CRC校验开关状态

    # IFInputStatus	中频输入信号状态
    # DSStatus	解调同步状态
    # DecodingIndication	译码或帧同步状态
    # Eb_No	信号Eb/No
    # DemodulationBitErrorRate	解调误码率
    # IF_Level	中频电平幅度

"""字段中文名"""
map_name_chg = {
                "ControlMode": "控制模式",
                "Demodulation": "接收信号解调方式",
                "CepstrumSate": "接收信号倒谱状态",
                "SignalRate": "接收信号信息速率",
                "DifferentialDecoding": "差分译码",
                "FEC": "前向纠错",
                "DecodingChannels": "前向纠错译码路数",
                "ConvolutionalDecodingState": "卷积译码状态",
                "RSDecoding": "RS译码状态",
                "RSChannels": "RS译码路数",
                "RSDepth": "RS译码交织深度",
                "Descrambling": "去扰状态",
                "IPPacketSize": "IP包长设置",
                "FrameDetect": "帧检测",
                "SYNCLength": "同步码长度",
                "FrameLength": "帧长度",
                "SYNC_I": "I路同步码型",
                "SYNC_Q": "Q路同步码型",
                "CRC_Switch": "CRC校验开关状态",
                "IFInputStatus": "Q路同步码型",
                "DSStatus": "解调同步状态",
                "DecodingIndication": "译码或帧同步状态",
                "Eb_No": "信号Eb/No",
                "DemodulationBitErrorRate": "解调误码率",
                "IF_Level": "中频电平幅度",
                # "RemDataLinkStatus": "远程数据传输终端连接状态", 这个模拟的也不会有
                # "ERRORINFO": "参数设置状态", 这个暂时不用
                "StartTime": "任务开始时间",
                "EndTime": "任务结束时间",
                "targetID": "卫星编号参数",
                "frequency": "频率"
                }

	
	
	
	


packet_head =bytearray([0xeb,0x90,0x3e, 0x4f, 0x7b, 0x7a])
packet_end ="000000000000000000000000000000000000000000000000000000000000"
# print("1111111111111111     ",packet_head)
tem_packet_str=""
Eb_No_value = 12.5
def packet_string():
    global Eb_No_value
    if(Eb_No_value>90):
        Eb_No_value=10
    Eb_No_value=Eb_No_value+1.5
    str_Eb_No=format(Eb_No_value,'.1f')
    map_work_status_lock.acquire()
    map_work_status["Eb_No"]=str_Eb_No
    packet_info=\
        map_work_status["ControlMode"]+\
        map_work_status["Demodulation"]+\
        map_work_status["CepstrumSate"]+\
        map_work_status["SignalRate"]+\
        map_work_status["DifferentialDecoding"]+\
        map_work_status["FEC"]+\
        map_work_status["DecodingChannels"]+\
        map_work_status["ConvolutionalDecodingState"]+\
        map_work_status["RSDecoding"]+\
        map_work_status["RSChannels"]+\
        map_work_status["RSDepth"]+\
        map_work_status["Descrambling"]+\
        map_work_status["IPPacketSize"]+\
        map_work_status["FrameDetect"]+\
        map_work_status["SYNCLength"]+\
        map_work_status["FrameLength"]+\
        map_work_status["SYNC_I"]+\
        map_work_status["SYNC_Q"]+\
        map_work_status["CRC_Switch"]+\
        map_work_status["IFInputStatus"]+\
        map_work_status["DSStatus"]+\
        map_work_status["DecodingIndication"]+\
        map_work_status["Eb_No"]+\
        map_work_status["DemodulationBitErrorRate"]+\
        map_work_status["IF_Level"]+packet_end



    map_work_status_lock.release()
    # print("11111111111122222222222222222: ",tem_packet_str)
    return packet_head+packet_info.encode("utf-8")

def packet_status_string():
    map_work_status_lock.acquire()
    packet_info=\
        map_name_chg["ControlMode"]+" : "+map_work_status["ControlMode"]+"\r\n"+\
        map_name_chg["Demodulation"]+" : "+map_work_status["Demodulation"]+"\r\n"+\
        map_name_chg["CepstrumSate"]+" : "+ map_work_status["CepstrumSate"]+"\r\n"+\
        map_name_chg["SignalRate"]+" : "+  map_work_status["SignalRate"]+"\r\n"+\
        map_name_chg["DifferentialDecoding"]+" : "+map_work_status["DifferentialDecoding"]+"\r\n"+\
        map_name_chg["FEC"]+" : "+ map_work_status["FEC"]+"\r\n"+\
        map_name_chg["DecodingChannels"]+" : "+map_work_status["DecodingChannels"]+"\r\n"+\
        map_name_chg["ConvolutionalDecodingState"]+" : "+ map_work_status["ConvolutionalDecodingState"]+"\r\n"+\
        map_name_chg["RSDecoding"]+" : "+ map_work_status["RSDecoding"]+"\r\n"+\
        map_name_chg["RSChannels"]+" : "+ map_work_status["RSChannels"]+"\r\n"+\
        map_name_chg["RSDepth"]+" : "+ map_work_status["RSDepth"]+"\r\n"+\
        map_name_chg["Descrambling"]+" : "+  map_work_status["Descrambling"]+"\r\n"+\
        map_name_chg["IPPacketSize"]+" : "+ map_work_status["IPPacketSize"]+"\r\n"+\
        map_name_chg["FrameDetect"]+" : "+ map_work_status["FrameDetect"]+"\r\n"+\
        map_name_chg["SYNCLength"]+" : "+   map_work_status["SYNCLength"]+"\r\n"+\
        map_name_chg["FrameLength"]+" : "+map_work_status["FrameLength"]+"\r\n"+\
        map_name_chg["SYNC_I"]+" : "+map_work_status["SYNC_I"]+"\r\n"+\
        map_name_chg["SYNC_Q"]+" : "+ map_work_status["SYNC_Q"]+"\r\n"+\
        map_name_chg["CRC_Switch"]+" : "+ map_work_status["CRC_Switch"]+"\r\n"+\
        map_name_chg["IFInputStatus"]+" : "+map_work_status["IFInputStatus"]+"\r\n"+\
        map_name_chg["DSStatus"]+" : "+map_work_status["DSStatus"]+"\r\n"+\
        map_name_chg["DecodingIndication"]+" : "+map_work_status["DecodingIndication"]+"\r\n"+\
        map_name_chg["Eb_No"]+" : "+map_work_status["Eb_No"]+"\r\n"+\
        map_name_chg["DemodulationBitErrorRate"]+" : "+map_work_status["DemodulationBitErrorRate"]+"\r\n"+\
        map_name_chg["IF_Level"]+" : "+map_work_status["IF_Level"]+"\r\n"+\
        map_name_chg["StartTime"]+" : "+map_work_status["StartTime"]+"\r\n"+\
        map_name_chg["EndTime"]+" : "+map_work_status["EndTime"]+"\r\n"+\
        map_name_chg["targetID"]+" : "+map_work_status["targetID"]+"\r\n"+\
        map_name_chg["frequency"]+" : "+map_work_status["frequency"]
    map_work_status_lock.release()
    # print("11111111111122222222222222222: ",packet_info)
    return packet_info
initstr=packet_status_string()
tem_packet_str = packet_string()

print("初始化数据：\r\n" + initstr)


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_HSM_QueryStatus_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_HSM_StartReceiveDataControl_CallBack(recv_cmd):
    # print(recv_cmd.hex()) binascii.unhexlify(hex_str.encode())
    tem_packet_str = bytearray([0xeb,0x90,0x3E, 0X09])+recv_cmd[4:]
    # tem_packet_str = packet_string()
    buf = recv_cmd[6:].decode()
    print(buf)
    map_work_status_lock.acquire()
    map_work_status["StartTime"]=buf[0:14]
    map_work_status["EndTime"]=buf[14:28]
    map_work_status["targetID"]=buf[28:33]
    map_work_status["frequency"]=buf[33:39 ]
    map_work_status_lock.release()
    if (TCP_LINK_STATUS != 0):
        client_socket.send((tem_packet_str))



""" 停止记录控制指令 回调函数 """
def HY_HSM_StopRecord_CallBack(recv_cmd):
    # print(recv_cmd.hex()) binascii.unhexlify(hex_str.encode())
    tem_packet_str = bytearray([0xeb,0x90,0x3E, 0X0a])+recv_cmd[4:]
    # tem_packet_str = packet_string()
    if (TCP_LINK_STATUS != 0):
        client_socket.send((tem_packet_str))


map_calBackFun = {"eb903c4f": HY_HSM_QueryStatus_CallBack,
                "eb903c00":HY_HSM_ParamSetting_CallBack,
                "eb903c09":HY_HSM_StartReceiveDataControl_CallBack,
                "eb903c0a":HY_HSM_StopRecord_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.encode("utf-8"))
        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)
        if (len(data) > 0):
            rec_str = data[0:4]
            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)
                # SendMessage(rec_str)
            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()
