from socket import *
import time
from threading import Thread

from test.msg_list import *

BUILDING_NAME = "cc_test"
GATEWAY_NUM = 1
TEST_BUILDING = [BUILDING_NAME] * GATEWAY_NUM
TEST_GATEWAY = ["B1_G" + str(i+1) for i in range(GATEWAY_NUM)]
METER_NUM = 1
TCP_SERVER_IP = "115.159.155.201"
TCP_SERVER_PORT = 9000


def identify_msg(building_id, gateway_id):
    body = xml_identify(building_id, gateway_id)
    length = hex(len(body))[2:].zfill(8)
    head = a2b_hex('1f1f01'+length)
    msg = head + body
    return msg


def power_msg(building_id, gateway_id, meter_num):
    body = xml_power(building_id, gateway_id, meter_num)
    length = hex(len(body))[2:].zfill(8)
    head = a2b_hex('1f1f03'+length)
    msg = head + body
    # print(len(msg))

    m = []
    while len(msg) > 1000:
        m.append(msg[:1000])
        msg = msg[1000:]
    m.append(msg)
    return m


def tcp_client(building_id, gateway_id, meter_num):
    tcp_client_socket = socket(AF_INET, SOCK_STREAM)
    tcp_client_socket.connect((TCP_SERVER_IP, TCP_SERVER_PORT))

    tcp_client_socket.send(identify_msg(building_id, gateway_id))
    recv_data = tcp_client_socket.recv(1024)
    print("返回的消息为:", recv_data)
    time.sleep(5)

    while True:
        msg_list = power_msg(building_id, gateway_id, meter_num)
        for msg in msg_list:
            tcp_client_socket.send(msg)
            recv_data = tcp_client_socket.recv(1024)
            print("返回的消息为:", recv_data)
            # time.sleep(0.1)
        time.sleep(300)


class MyThread(Thread):
    def __init__(self, building_id, gateway_id):
        Thread.__init__(self)
        self.building_id = building_id
        self.gateway_id = gateway_id

    def run(self):
        tcp_client(self.building_id, self.gateway_id, METER_NUM)


if __name__ == '__main__':
    thread_list = []
    for bld, gtw in zip(TEST_BUILDING, TEST_GATEWAY):
        thread_list.append(MyThread(bld, gtw))

    for t in thread_list:
        t.start()

    for t in thread_list:
        t.join()
    print("退出主线程")
