import signal
import sys
import os
import time
from google.protobuf import json_format
from google.protobuf.timestamp_pb2 import Timestamp
from datetime import datetime
import cmmstruct_pb2
import re

cmd = cmmstruct_pb2.TDSCmd()
cmd.interface_id = cmmstruct_pb2.IID.IID_AGI_xxx
cmd.dst_suid = 0x12330000
cmd.src_suid = 0x10030000
cmd.priority = 100
cmd.ts.GetCurrentTime()
#测试使用,可以存放任意repeated值
for i in range(0, 5):
    param = cmmstruct_pb2.TestParams()
    param.key = "username"+str(i)
    param.value = "admin"+str(i)
    cmd.parameters.add().Pack(param)

cmdlen = len(cmd.SerializeToString())
print(json_format.MessageToJson(cmd))

import json
import sys
import time
import paho.mqtt.client as mqtt
import threading

REPORT_TOPIC_1 = '/1/3/0/3'  # 主题，监听了具体的子系统
REPORT_TOPIC_2 = '/1/3/#'  # 主题 监听了2级站以及以下的所有站点
REPORT_TOPIC = '/1/0/0/2'  # 主题 系统所有消息都被监控


def publishmessage(client):
    pubcnt = 0
    while True:
        #print("publish")
        pubcnt = pubcnt + 1
        cmd.priority = pubcnt
        cmd.ts.GetCurrentTime()
        client.publish("/1/3/0/3", cmd.SerializeToString())
        time.sleep(5)
        print("pubpacket %d cmdlen %d" % (pubcnt, cmdlen))
        client.loop_start()  # 以forever方式阻塞运行。



def on_connect(client, userdata, flags, rc):
    print('connected to mqtt with resurt code ', rc)
    client.subscribe(REPORT_TOPIC_2)  # 订阅主题

subcnt = 0
def on_message(client, userdata, msg):
    global subcnt
    """
    接收客户端发送的消息
    :param client: 连接信息
    :param userdata:
    :param msg: 客户端返回的消息
    :return:
    """
    print("on_message")
    cmdsub = cmmstruct_pb2.TDSCmd()
    cmdsub.ParseFromString(msg.payload)
    subcnt = subcnt + 1
    rtnstr = json_format.MessageToJson(cmdsub)

    print(rtnstr)

    iidlist=re.findall(r'"interfaceId":\s+"(\w+)"', rtnstr, re.S)
    if iidlist != []:
        print("IID:%s"%iidlist)

    paramlist=re.findall(r'"key":\s+"(\w+)",.\s+"value":\s+"(\w+)"', rtnstr, re.S)
    if paramlist != []: 
        print("keys:%s"%paramlist)

def server_conenet(client):
    client.on_connect = on_connect   # 启用订阅模式
    client.on_message = on_message   # 接收消息
    client.connect("124.222.246.93", 8686, 60)   # 链接
    #client.connect("47.96.160.63", 10233, 60)   # 链接
    #client.connect("192.168.0.80", 1883, 60)   # 链接
    client.loop_start()  # 以start方式运行，需要启动一个守护线程，让服务端运行，否则会随主线程死亡
    #client.loop_forever()  # 以forever方式阻塞运行。


def server_stop(client):
    client.loop_stop()     # 停止服务端
    sys.exit(0)

def server_main():
    client_id = time.strftime('%Y%m%d%H%M%S', time.localtime(time.time()))
    client = mqtt.Client(client_id, transport='tcp')
    tr = threading.Thread(target=publishmessage, args=(client, ))
    server_conenet(client)
    tr.setDaemon(True)
    tr.start()



if __name__ == '__main__':
    # 启动监听
    server_main()

    print(123)
    def quit(signum, frame):
        print("Shutdown...")
        sys.exit(0)

    signal.signal(signal.SIGINT, quit)
    while True:
        time.sleep(1)


