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

#模拟下变频器设备 S/720 L/720

# 定义回调函数
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 = {"InputFrequency": "02200.000",\
                     "Attenuation": "40.00",\
                     "RFSignalSwitch": "ON",\
                     "LOState": "LOCK",\
                     "Current": "0.22",\
                     "TEM": "+25",\
                     "EXT": "NO",\
                     "ControlState": "ON",\
                     "ChannelStatus": "OK"\
                     }
"""字段中文名"""
map_name_chg = {"InputFrequency": "输入频率",\
                     "Attenuation": "衰减",\
                     "RFSignalSwitch": "射频信号开关",\
                     "LOState": "本振状态",\
                     "Current": "电源电流",\
                     "TEM": "温度",\
                     "EXT": "外参考输入",\
                     "ControlState": "控制状态",\
                     "ChannelStatus": "通道状态"\
                     }


tem_packet_str = map_name_chg["InputFrequency"]+": "+map_work_status["InputFrequency"]+"  "+\
                 map_name_chg["Attenuation"]+": "+map_work_status["Attenuation"]+\
                 map_name_chg["RFSignalSwitch"]+": "+map_work_status["RFSignalSwitch"]+\
                 map_name_chg["LOState"]+": "+map_work_status["LOState"]+\
                 map_name_chg["TEM"]+": "+map_work_status["TEM"]+\
                 map_name_chg["EXT"]+": "+map_work_status["EXT"]+\
                 map_name_chg["ControlState"]+": "+map_work_status["ControlState"]+\
                 map_name_chg["ChannelStatus"]+": "+map_work_status["ChannelStatus"]

print("初始化数据：" + tem_packet_str)

# config = configparser.ConfigParser()  # 类实例化
# 定义ini文件路径  这个文件用于存放 跟踪接收机当前的报警状态
# path = r'trackingReceiver.ini'

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_HWF03550357FC_SetControlState_CallBack(recv_cmd):
    # print("HY_HWF03550357FC_SetControlState_CallBack == recv_cmd",recv_cmd)
    if(len(recv_cmd) == 12):
        value = recv_cmd[9:11]
    else:
        value = recv_cmd[9:12]
    print("HY_HWF03550357FC_SetControlState_CallBack == ",value)
    map_work_status_lock.acquire()  # 上锁
    map_work_status["ControlState"] = value
    map_work_status_lock.release()  # 解锁




""" 设置射频信号开关 回调函数"""
def HY_HWF03550357FC_SetRFSignalSwitch_CallBack(recv_cmd):
    # print("HY_HWF03550357FC_SetRFSignalSwitch_CallBack == recv_cmd",recv_cmd)
    if(len(recv_cmd) == 12):
        value = recv_cmd[9:11]
    else:
        value = recv_cmd[9:12]
    print("HY_HWF03550357FC_SetRFSignalSwitch_CallBack == ",value)
    map_work_status_lock.acquire()  # 上锁
    map_work_status["RFSignalSwitch"] = value
    map_work_status_lock.release()  # 解锁

""" 设置频率 回调函数"""
def HY_HWF03550357FC_SetInputFrequency_CallBack(recv_cmd):
    # print("HY_HWF03550357FC_SetInputFrequency_CallBack == recv_cmd",recv_cmd)
    value = recv_cmd[9:18]
    print("HY_HWF03550357FC_SetInputFrequency_CallBack == ",value)
    map_work_status_lock.acquire()  # 上锁
    map_work_status["InputFrequency"] = value
    map_work_status_lock.release()  # 解锁

""" 设置衰减指令 """
def HY_HWF03550357FC_SetAttenuation_CallBack(recv_cmd):
    # print("HY_HWF03550357FC_SetAttenuation_CallBack == recv_cmd",recv_cmd)
    value = recv_cmd[9:15]
    print("HY_HWF03550357FC_SetAttenuation_CallBack == ",value)
    map_work_status_lock.acquire()  # 上锁
    map_work_status["Attenuation"] = value
    map_work_status_lock.release()  # 解锁

""" 查询参数状态指令 回调函数"""
def HY_HWF03550357FC_QueryAllStatus_CallBack(recv_cmd):
    print("HY_HWF03550357FC_QueryAllStatus_CallBack == recv_cmd",recv_cmd)
    map_work_status_lock.acquire()  # 上锁
    tem_packet_str = ">006/RCS_\r"+"FRE_"+ map_work_status["InputFrequency"] + "\r"+\
                                "ATT_"+ map_work_status["Attenuation"] + "\r"+\
                                "RX_" + map_work_status["RFSignalSwitch"] + "\r"+\
                                "LO_" + map_work_status["LOState"] + "\r"+\
                                "POW_"+ map_work_status["Current"]+ "\r" +\
                                "TEM_"+ map_work_status["TEM"] + "\r"+\
                                "EXT_"+ map_work_status["EXT"] +\
                                "\r\n]"
    if (TCP_LINK_STATUS != 0):
        client_socket.send(tem_packet_str.encode("utf-8"))
    map_work_status_lock.release()  # 解锁
    print(" tem_packet_str == ",tem_packet_str)


""" 查询参数状态指令 回调函数"""
def HY_HWF03550357FC_QueryChannelStatusRespond_CallBack(recv_cmd):
    print("HY_HWF03550357FC_QueryChannelStatusRespond_CallBack == recv_cmd",recv_cmd)
    map_work_status_lock.acquire()  # 上锁
    tem_packet_str = ">006/SAS_" + map_work_status["ChannelStatus"] + "\r\n]"
    if (TCP_LINK_STATUS != 0):
        client_socket.send(tem_packet_str.encode("utf-8"))
    map_work_status_lock.release()  # 解锁

""" 查询参数状态指令 回调函数"""
def HY_HWF03550357FC_QueryControlState_CallBack(recv_cmd):
    print("HY_HWF03550357FC_QueryControlState_CallBack == recv_cmd",recv_cmd)
    map_work_status_lock.acquire()  # 上锁
    tem_packet_str = ">006/REM_" + map_work_status["ControlState"] + "\r\n]"
    if (TCP_LINK_STATUS != 0):
        client_socket.send(tem_packet_str.encode("utf-8"))
    map_work_status_lock.release()  # 解锁

map_calBackFun = {"<006/REM_": HY_HWF03550357FC_SetControlState_CallBack,
                  "<006/MUT_": HY_HWF03550357FC_SetRFSignalSwitch_CallBack,
                  "<006/FRE_": HY_HWF03550357FC_SetInputFrequency_CallBack,
                  "<006/ATT_": HY_HWF03550357FC_SetAttenuation_CallBack,
                  "<006/RCS_": HY_HWF03550357FC_QueryAllStatus_CallBack,
                  "<006/SAS_": HY_HWF03550357FC_QueryChannelStatusRespond_CallBack,
                  "<006/REM_\r": HY_HWF03550357FC_QueryControlState_CallBack
                  }

"""定时读取 map_work_status 发布设备状态报文 间隔200ms"""
def SendStatusHandle():
    print("线程1")
    global client_socket
    cont = 0
    cont_print = 0
    max_cont = 10000
    while max_cont:
        map_work_status_lock.acquire()
        # tem_packet_str = "<CF_" + map_work_status["InputFrequency"] + ",BD_" + map_banwith_status[map_work_status["Bandwidth"]]+ "\r\n"
        tem_status_str = map_name_chg["InputFrequency"]+":"+map_work_status["InputFrequency"]+ "\r\n"+\
                    map_name_chg["Attenuation"]+":"+map_work_status["Attenuation"]+ "\r\n"+\
                    map_name_chg["RFSignalSwitch"]+":"+map_work_status["RFSignalSwitch"]+ "\r\n"+\
                    map_name_chg["LOState"]+":"+map_work_status["LOState"]+ "\r\n"+\
                    map_name_chg["TEM"]+":"+map_work_status["TEM"]+ "\r\n"+\
                    map_name_chg["EXT"]+":"+map_work_status["EXT"]+ "\r\n"+\
                    map_name_chg["ControlState"]+":"+map_work_status["ControlState"]+ "\r\n"+\
                    map_name_chg["ChannelStatus"]+":"+map_work_status["ChannelStatus"]       
        # if (TCP_LINK_STATUS != 0):
        #     max_cont = max_cont - 1
        #  client_socket.send(tem_packet_str.encode("utf-8"))
        map_work_status_lock.release()
        cont = cont + 1
        if (cont > 2 and TCP_LINK_STATUS):
            cont_print = cont_print + 1
            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)
        rec_str = data.decode()
        if (len(data) > 0):
            cmd = rec_str[0:9]
            # print("1111111",cmd)
            # print("2222222",rec_str)
            # print("3333333",len(data))

            if(cmd =="<006/REM_" and len(data) == 10):
                cmd = rec_str[0:10]
            if (cmd in map_calBackFun):
                map_calBackFun[cmd](rec_str)
                # SendMessage(rec_str)
            else:
                print("收到未知报文 : " + rec_str)
        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()

"""数据格式：
CF_xxxx.xxx\r\n
解释：
xxxx.xxx:输入频率,范围:2200.000~3000.000,单位:MHz;
BD_x\r\n
解释：
x:带宽,范围:1,2,3 1:50KHz  2:1MHz  3:2MHz   默认 1
"""

