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 = {
                    "T1": "20170102",
                    "T2": "210612",
                    "AzimuthAngle": "19657",
                    "ElevationAngle": "03946",
                    "PolarizationAngle": "-0608",
                    "WorkMode": "N",
                    "AzimuthStatus": "00",
                    "ElevationStatus": "00",
                    "PolarizationStatus": "00",
                    "Longitude": "11645",
                    "Latitude": "03916",
                    "Altitude": "0500",
                    "SignalStrengthDiff": "+123",
                    "XBJ_FR": "169800",
                    "XBJ_PCenter": "00",
                    "XBJ_PSize": "00",
                    "XBJ_PBHSize": "0000",
                    "NowTrackingMethod": "N",
                    "LastTrackingMethod": "N",
                    "Flag": "1"
                }

"""字段中文名"""
map_name_chg = {
                    "T1": "年月日",
                    "T2": "时分秒",
                    "AzimuthAngle": "方位位置 单位度",
                    "ElevationAngle": "俯仰位置 单位度",
                    "PolarizationAngle": "极化轴  单位度",
                    "WorkMode": "工作状态信息",
                    "AzimuthStatus": "方位状态数据",
                    "ElevationStatus": "俯仰状态数据",
                    "PolarizationStatus": "极化状态数据",
                    "Longitude": "经度值",
                    "Latitude": "纬度值",
                    "Altitude": "海拔高度",
                    "SignalStrengthDiff": "信号强度差",
                    "XBJ_FR": "备用字段:信标机的信号频率",
                    "XBJ_PCenter": "备用字段:信标功率中心点",
                    "XBJ_PSize": "备用字段:信标功率中心点",
                    "XBJ_PBHSize": "备用字段:信标机频率捕获范围",
                    "NowTrackingMethod": "备用字段:此次采用的跟踪方式",
                    "LastTrackingMethod": "备用字段:上一次采用的跟踪方式",
                    "Flag": "运动到位标志"
                }

	
	
	
	


packet_head ="#"
packet_end ="END\n\r"
tem_packet_str=""
def packet_string():
    map_work_status_lock.acquire()
    packet_info=packet_head+"\t"+\
        map_work_status["T1"]+"\t"+\
        map_work_status["T2"]+"\t"+\
        map_work_status["AzimuthAngle"]+"\t"+\
        map_work_status["ElevationAngle"]+"\t"+\
        map_work_status["PolarizationAngle"]+"\t"+\
        map_work_status["WorkMode"]+"\t"+\
        map_work_status["AzimuthStatus"]+"\t"+\
        map_work_status["ElevationStatus"]+"\t"+\
        map_work_status["PolarizationStatus"]+"\t"+\
        map_work_status["Longitude"]+"\t"+\
        map_work_status["Latitude"]+"\t"+\
        map_work_status["Altitude"]+"\t"+\
        map_work_status["SignalStrengthDiff"]+"\t"+\
        map_work_status["XBJ_FR"]+"\t"+\
        map_work_status["XBJ_PCenter"]+"\t"+\
        map_work_status["XBJ_PSize"]+"\t"+\
        map_work_status["XBJ_PBHSize"]+"\t"+\
        map_work_status["NowTrackingMethod"]+"\t"+\
        map_work_status["LastTrackingMethod"]+"\t"+\
        map_work_status["Flag"]+"\t\t\t\t\t"+packet_end
    map_work_status_lock.release()
    # print("11111111111122222222222222222: ",packet_info)
    return packet_info
# packet_string()
def packet_status_string():
    map_work_status_lock.acquire()
    packet_info=\
    map_name_chg["T1"]+" : "+map_work_status["T1"]+"\r\n"+\
    map_name_chg["T2"]+" : "+map_work_status["T2"]+"\r\n"+\
    map_name_chg["AzimuthAngle"]+" : "+map_work_status["AzimuthAngle"]+"\r\n"+\
    map_name_chg["ElevationAngle"]+" : "+map_work_status["ElevationAngle"]+"\r\n"+\
    map_name_chg["PolarizationAngle"]+" : "+map_work_status["PolarizationAngle"]+"\r\n"+\
    map_name_chg["WorkMode"]+" : "+map_work_status["WorkMode"]+"\r\n"+\
    map_name_chg["AzimuthStatus"]+" : "+map_work_status["AzimuthStatus"]+"\r\n"+\
    map_name_chg["ElevationStatus"]+" : "+map_work_status["ElevationStatus"]+"\r\n"+\
    map_name_chg["PolarizationStatus"]+" : "+map_work_status["PolarizationStatus"]+"\r\n"+\
    map_name_chg["Longitude"]+" : "+map_work_status["Longitude"]+"\r\n"+\
    map_name_chg["Latitude"]+" : "+map_work_status["Latitude"]+"\r\n"+\
    map_name_chg["Altitude"]+" : "+map_work_status["Altitude"]+"\r\n"+\
    map_name_chg["SignalStrengthDiff"]+" : "+map_work_status["SignalStrengthDiff"]+"\r\n"+\
    map_name_chg["XBJ_FR"]+" : "+map_work_status["XBJ_FR"]+"\r\n"+\
    map_name_chg["XBJ_PCenter"]+" : "+map_work_status["XBJ_PCenter"]+"\r\n"+\
    map_name_chg["XBJ_PSize"]+" : "+map_work_status["XBJ_PSize"]+"\r\n"+\
    map_name_chg["XBJ_PBHSize"]+" : "+map_work_status["XBJ_PBHSize"]+"\r\n"+\
    map_name_chg["NowTrackingMethod"]+" : "+map_work_status["NowTrackingMethod"]+"\r\n"+\
    map_name_chg["LastTrackingMethod"]+" : "+map_work_status["LastTrackingMethod"]+"\r\n"+\
    map_name_chg["Flag"]+" : "+map_work_status["Flag"]
    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_ACU7M3_DirectionSet(recv_cmd):
    map_work_status_lock.acquire()
    map_work_status["AzimuthAngle"]=recv_cmd[3:8]
    map_work_status["ElevationAngle"]=recv_cmd[8:13]
    map_work_status["PolarizationAngle"]=recv_cmd[13:18]
    map_work_status_lock.release()


map_calBackFun = {"$PP": HY_ACU7M3_DirectionSet
}


"""定时读取 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)
        str1= ""
        str1=data.decode()
        if (len(data) > 0):
            cmd = str1[0:3]
            print(cmd)
            print(data)

            if (cmd in map_calBackFun):
                map_calBackFun[cmd](str1)
                # SendMessage(rec_str)
            else:
                print("收到未知报文 : " + str1)
        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)


def SendMessage(recv_cmd):
    global client_socket
    send_str = ""
    map_work_status_lock.acquire()
    if recv_cmd[0] == "C":
        send_str = "<" + recv_cmd
    elif recv_cmd[0] == "B":
        send_str = "<" + recv_cmd
    elif recv_cmd[0] == "?":
        send_str = "<CF_" + map_work_status["InputFrequency"] + ",BD_" + map_banwith_status[map_work_status["Bandwidth"]] + "\r\n"
    client_socket.send(send_str.encode("utf-8"))
    map_work_status_lock.release()


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