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 = {"InputFrequency": "2200.000", "Bandwidth": "50KHz"}
"""字段中文名"""
map_name_chg = {"InputFrequency": "输入频率", "Bandwidth": "带宽"}
map_banwith_status = {"50KHz":"1","1MHz":"2","2MHz":"3"}

tem_packet_str = map_name_chg["InputFrequency"]+":"+map_work_status["InputFrequency"]+"  "+map_name_chg["Bandwidth"]+":"+map_work_status["Bandwidth"]

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_TrackingReceiver_SetInputFrequency_CallBack(recv_cmd):
    InputFrequency = recv_cmd[3:11]
    print("HY_TrackingReceiver_SetInputFrequency_CallBack InputFrequency = ",InputFrequency)
    map_work_status_lock.acquire()  # 上锁
    map_work_status["InputFrequency"] = InputFrequency
    map_work_status_lock.release()  # 解锁


""" 处理带宽指令 回调函数"""
def HY_TrackingReceiver_Bandwidth_CallBack(recv_cmd):
    Bandwith = recv_cmd[3]
    print("HY_TrackingReceiver_Bandwidth_CallBack Bandwith = ",Bandwith)

    map_work_status_lock.acquire()  # 上锁
    if int(Bandwith) == 1:
        map_work_status["Bandwidth"] = "50KHz"
    elif int(Bandwith) == 2:
        map_work_status["Bandwidth"] = "1MHz"
    elif int(Bandwith) == 3:
        map_work_status["Bandwidth"] = "2MHz"
    else:
        map_work_status["Bandwidth"] = "50KHz"
    map_work_status_lock.release()  # 解锁


""" 处理查询状态指令 回调函数"""
def HY_TrackingReceiver_QueryState_CallBack(recv_cmd):
    map_work_status_lock.acquire()  # 上锁
    # print("2222222222222",recv_cmd)
    #map_work_status = map_work_status
    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["Bandwidth"]+":"+map_work_status["Bandwidth"]+"\r\n"
    if (TCP_LINK_STATUS != 0):
        client_socket.send(tem_packet_str.encode("utf-8"))
    map_work_status_lock.release()  # 解锁


map_calBackFun = {"C": HY_TrackingReceiver_SetInputFrequency_CallBack,
                  "B": HY_TrackingReceiver_Bandwidth_CallBack,
                  "?": HY_TrackingReceiver_QueryState_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["Bandwidth"]+":"+map_work_status["Bandwidth"]+"\r\n"
        # 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]
            # print("1111111",cmd)
            # print("2222222",rec_str)
            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
"""
