TCP&UDP&RS485/422 根据指定协议发包

代码整体分为两个部分:造数据和发送数据。

在造数据部分,我们需要注意到其中使用了shot类型的数据。由于Python中没有直接的shot类型,我们可以通过限制int类型并将其转换为相应的十六进制数值来替代。此外,在造数据函数中还包含了取反转hex、有无符号和浮点型转hex的功能。

在发送数据部分,我们建立连接并设置发送间隔,然后通过TCP或UDP发送数据。在TCP通信中,为了正确关闭连接,我们不仅需要调用close方法,还需要调用shutdown方法以发送挥手包。而在UDP通信中,发送数据相对简单,不需要过多考虑异常情况。对于串口通信,我们同样可以选择合适的串口,并根据自定义协议将造好的数据按照一定的分包方式发送出去。

优化的思路如下:

结合造数据和发送数据的部分,因为它们使用的数据是相同的。这样可以减少重复代码,提高代码的可读性和可维护性。

使用Python的struct模块来编码和解码二进制数据。struct模块能够更高效地实现数据的打包和解包操作,使代码更加简洁和可靠。

在发送数据时,使用socket模块的sendall()函数发送完整的消息,并通过头部信息指示消息的长度,确保接收方能够正确接收到完整的消息。

在处理串口通信时,使用PySerial库来简化串口操作。通过PySerial,可以方便地进行串口初始化、读写串口、设置波特率等操作,提高开发效率。

在数据解析过程中,可以考虑使用Pandas库来进行数据处理。Pandas提供了DataFrame等数据结构,可以方便地对数据进行过滤、排序、分组、统计等操作,减少手动处理的工作量。

import time
from socket import *
import struct
import math
import datetime
import threading

def type_hex(value_, type_, Positive_and_Negative=0) -> str:
    """
    输入值和数据类型 默认为正数 并根据对应的解析方式返回16进制的值
    :param value_: 值
    :param type_: 数据类型
    :param Positive_and_Negative: 正负项
    :return: 16进制的值
    """
    if Positive_and_Negative == 1:
        if type_ == 'f':
            data10 = float(value_)
            data10hex = float_to_hex(data10)[2:]
            data10hex = bin(int(data10hex, 16))[2:]
            data10hex = hex(int('1' + data10hex.rjust(31, '0'), 2))[2:]
            return data10hex.rjust(8, '0')
        elif type_ == 'i':
            data10 = int(value_)
            return the_not(data10, 4)
        elif type_ == 's':
            data10 = int(value_)
            return the_not(data10, 2)
        elif type_ == 'c':
            data10 = hex(int(value_))[2:]
            return data10.rjust(2, '0')
    elif Positive_and_Negative == 0:
        if type_ == 'f':
            data10 = float(value_)
            data10hex = float_to_hex(data10)[2:]
            return data10hex.rjust(8, '0')
        elif type_ == 'i':
            data8hex = hex(int(value_))[2:]
            return data8hex.rjust(8, '0')
        elif type_ == 's':
            data8hex = hex(int(value_))[2:]
            return data8hex.rjust(4, '0')
        elif type_ == 'c':
            data10 = hex(int(value_))[2:]
            return data10.rjust(2, '0')
def the_not(value, pos):
    """
    指定位数取反
    :param value:数据
    :param pos: 位数
    leng 传递二进制长度 - 1
    将 获取到的数据转换为2进制后,将数据的最高位去除,
    如数据长度未满足pos长度将会在高位补零,并将其余所
    有位数0和1置换在从最高位补1并返回
    :return:
    """

    if value == 0:
        value = 1
    value = value - 1
    value = "{0:b}".format(value)
    a = ((pos * 8) - 1)
    value = value.rjust(a, '0')
    value = value.replace('1', '2')
    value = value.replace('0', '1')
    value = value.replace('2', '0')
    value = '1' + value
    value = hex((int(value, 2)))[2:]
    value = value.rjust((pos * 2), '0')

    return value


# -> object 描述返回值数据类型
def Override_override(ov: object, value: object, leng: object) -> object:
    """
    更改字符串指定位置的字符
    :param ov: 被更改的老字符串
    :param value: 更改的值
    :param leng: 起始位置
    :return: 更改后的字符串
    """
    len_ = int(len(value))
    # print(f"ov值为:{ov},新的值为:{ov[:leng * 2] + value + ov[leng + (leng * 2):]}")
    return ov[:leng * 2] + value + ov[len_ + (leng * 2):]


def float_to_hex(f):
    return hex(struct.unpack('<I', struct.pack('<f', f))[0])


def print_progress(num, cont):
    # 进度条
    total_length = 30
    progress = int(cont / num * total_length)

    bar = '['+'■' * progress + ' ' * (total_length - progress) + ']'
    print(f'Progress:{bar}{cont}/{num}', end='\r')





def type_hex_new(value_, type_, Positive_and_Negative=0) -> str:
    """
    输入值和数据类型 默认为正数 并根据对应的解析方式返回 置返的16进制的值
    :param value_:
    :param type_:
    :param Positive_and_Negative:
    :return:
    """
    hex_ = type_hex(value_, type_, Positive_and_Negative=Positive_and_Negative)
    if type_ == 'f':
        a = int(hex_[0:2], 16)
        b = int(hex_[2:4], 16) * 256
        c = int(hex_[4:6], 16) * (256 * 256)
        d = int(hex_[6:8], 16) * (256 * 256 * 256)
        max_ = hex(int(a + b + c + d))[2:]
        max_ = max_.rjust(8, '0')
        return max_
    elif type_ == 'i':
        a = int(hex_[0:2], 16)
        b = int(hex_[2:4], 16) * 256
        c = int(hex_[4:6], 16) * (256 * 256)
        d = int(hex_[6:8], 16) * (256 * 256 * 256)
        max_ = hex(int(a + b + c + d))[2:]
        max_ = max_.rjust(8, '0')
        return max_
        # = '0x' + hex_[0:2]
    elif type_ == 's':
        a = int(hex_[0:2], 16)
        b = int(hex_[2:4], 16) * 256
        max_ = hex(int(a + b))[2:]
        max_ = max_.rjust(4, '0')
        return max_
    elif type_ == 'c':
        return hex_


def doConnect(host, port):
    #  TCP
    tcp_soket = socket(AF_INET, SOCK_STREAM)

    # tcp_soket = socket(AF_INET, SOCK_DGRAM)
    try:
        tcp_soket.connect((host, port))
    except:
        ...
    return tcp_soket


def Generate_data(message_len: int, type_='00', models: str = '01') -> object:
    """
    输入 数据长度 和数据类型,以及分机号,返回一个长度400的数组
    data_type:更改为0 返回的数据为1024随机数据类型,1为自定义数据
    :type type_: object
    :param message_len: 报文长度 1 - 1024 int类型
    :param type_: 报文类型 01 00 str
    :param models: 分机号 为 01 - 04 str
    :return:返回制造的数据数组
    """
    message_list = []
    data_num = 0
    for z in range(-200, 201):
        z = int(math.fabs(z))
        a = int((z * z) / (2 * 100))
        data_type = 1

        if data_type == 1:
            # char
            Data1 = type_hex(str(z % 2), 'c')
            # shoar
            data2 = type_hex_new(str(31267 + a), 's')
            # float
            data3 = type_hex_new(str((z * z) / (2 * 100)), 'f')
            # int
            data4 = type_hex_new(str(100000 + (z * 100000)), 'i')
            # char
            data5 = type_hex(str(((z + 1) % 2) * 5), 'c')
            # float
            data6 = type_hex_new(str(0.99 + (z * 10)), 'f')
            # shoar 负数 递增
            data7 = type_hex_new(str(31267 - z), 's', Positive_and_Negative=1)
            # int1
            data8 = type_hex_new(str(800000 + (a * 50000)), 'i')
            # int 负数
            data9 = type_hex_new(str(100000 + (z * 100000)), 'i', Positive_and_Negative=1)
            # float 负数
            data10 = type_hex_new(str((z * z) / (2 * 100)), 'f', Positive_and_Negative=1)
            # char 55
            data11 = type_hex_new(str(z % 2 * 85), 'c')
            # shoar 负数递减
            data12 = type_hex_new(str(31267 + z), 's', Positive_and_Negative=1)
            # float 改
            data13 = type_hex_new(str(0.4 + (z * 2)), 'f')
            # int 改
            data14 = type_hex_new(str(100000 + (z * 83000)), 'i')
            # float 改
            data15 = type_hex_new(str(0.3 + (z * 0.1)), 'f')
            # shoar
            data16 = type_hex_new(str(150 * z), 's')
            # char
            data17 = type_hex_new(str(z % 2 * 165), 'c')
            # shoar 负数
            data18 = type_hex_new(str((30 * a)), 's')
            # int
            data19 = type_hex_new(str((a * 20000)), 'i')
            # char
            data20 = type_hex(str((z % 2) * 90), 'c')
            Data_Sum = '0'
            #设置长度
            Data_Sum = Data_Sum.ljust((2 * message_len), "0")
            Data_Sum = Override_override(Data_Sum, Data1, 0)
            Data_Sum = Override_override(Data_Sum, data2, 1)
            Data_Sum = Override_override(Data_Sum, data3, 3)
            Data_Sum = Override_override(Data_Sum, data4, 7)
            Data_Sum = Override_override(Data_Sum, data5, 11)
            Data_Sum = Override_override(Data_Sum, data6, 12)
            Data_Sum = Override_override(Data_Sum, data7, 16)
            Data_Sum = Override_override(Data_Sum, data8, 18)
            Data_Sum = Override_override(Data_Sum, data9, 22)
            Data_Sum = Override_override(Data_Sum, data10, 26)
            Data_Sum = Override_override(Data_Sum, data11, 30)
            Data_Sum = Override_override(Data_Sum, data12, 31)
            Data_Sum = Override_override(Data_Sum, data13, 33)
            Data_Sum = Override_override(Data_Sum, data14, 37)
            Data_Sum = Override_override(Data_Sum, data15, 41)
            Data_Sum = Override_override(Data_Sum, data16, 45)
            Data_Sum = Override_override(Data_Sum, data17, 47)
            Data_Sum = Override_override(Data_Sum, data18, 48)
            Data_Sum = Override_override(Data_Sum, data19, 50)
            Data_Sum = Override_override(Data_Sum, data20, 54)

            for value_w in range(1, 18):
                Data_Sum = Override_override(Data_Sum, Data_Sum[0:55 * 2], 55 * value_w)
            start = 990
            Data_Sum = Override_override(Data_Sum, Data1, start + 0)
            Data_Sum = Override_override(Data_Sum, data2, start + 1)
            Data_Sum = Override_override(Data_Sum, data3, start + 3)
            Data_Sum = Override_override(Data_Sum, data4, start + 7)
            Data_Sum = Override_override(Data_Sum, data5, start + 11)
            Data_Sum = Override_override(Data_Sum, data6, start + 12)
            Data_Sum = Override_override(Data_Sum, data7, start + 16)
            Data_Sum = Override_override(Data_Sum, data8, start + 18)
            Data_Sum = Override_override(Data_Sum, data9, start + 22)
            Data_Sum = Override_override(Data_Sum, data10, start + 26)
            Data_Sum = Override_override(Data_Sum, data11, start + 30)
            Data_Sum = Override_override(Data_Sum, data12, start + 31)
            Data_Sum = Override_override(Data_Sum, data20, start + 33)
            Data_Sum = Override_override(Data_Sum, Data_Sum, 1024)
            Data_Sum = Override_override(Data_Sum, Data_Sum, 1024 * 2)
            Data_Sum = Override_override(Data_Sum, Data_Sum, 1024 * 3)
            Data_Sum = Override_override(Data_Sum, Data_Sum, 1024 * 4)
            Data_Sum = Override_override(Data_Sum, Data_Sum, 1024 * 5)
            Data_Sum = Override_override(Data_Sum, Data_Sum, 1024 * 6)
            Data_Sum = Override_override(Data_Sum, Data_Sum, 1024 * 7)
            Data_Sum = Override_override(Data_Sum, Data_Sum, 1024 * 8)
            Data_Sum = Override_override(Data_Sum, Data_Sum, 1024 * 9)


        elif data_type == 0:
            data_num = data_num + 1
            if data_num > 255:
                break
            # int 正
            # data_1 = type_hex_new(str(100000 + (z * 100000)), 'i')
            # # flot 负数
            # data_1 = type_hex_new(str((z * z) / (2 * 100)), 'f', Positive_and_Negative=1)
            # # char
            # data_1 = type_hex(str(z % 2), 'c')
            # data_1 = type_hex_new(str(31267 - z), 's', Positive_and_Negative=1)
            # 报文长度
            Data_Sum = str()
            data_num1 = hex(data_num)[2:].rjust(2, '0')
            # print(data_num)
            for i in range(message_len + 1):
                Data_Sum = Data_Sum + data_num1
            # Data_Sum = Data_Sum.rjust(2,message_len, data_num)
            # 填满1024

            # for value_w in range(0, message_len, 2):
            #
            #     Data_Sum = Override_override(Data_Sum, hex(value_w), 2)

        # 设置报文类型
        Message_type = type_
        #
        # if type_ == '00' and '01':
        #     Message_type = type_
        # else:
        #     if z % 2 == 0:
        #         Message_type = '00'
        #     else:
        #         Message_type = '01'

        # 设置长度
        byte_len = int(message_len) * 2
        Data_Sum = Data_Sum[0:byte_len]

        Message_len = hex(int(byte_len / 2))[2:].rjust(4, '0')
        # test = (z, '=======', '1', Data_Sum)
        #
        # with open('test.txt', 'a') as f:
        #     f.write(str(test) + '\n')
        data_sum = ()

        message = '01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 %s %s %s ' \
                  '00 00 00 00 00 00 %s 30 30' % (models, Message_type, Message_len, Data_Sum)

        message_list.append(Data_Sum)
    return message_list


class Tup0001:
    def __init__(self, serve_ip, serve_port):
        self.serve_ip = serve_ip
        self.serve_port = serve_port

    def send_(self, send_gap=0.05, num_=1000000000000000000000000000, time_=1000000000000000000000000000,
               data=None):
        """
        不设置默认为 100000000000000000000000000000000
        :param time_: 发送时间
        :param num_: 发送个数
        :param send_gap: 发送间隔浮点数
        :param data: 导入数组data
        :return:
        """
        # 建立连接
        datalen = len(data[0].replace(' ', ''))/2
        tcp_soket = doConnect(self.serve_ip, self.serve_port)
        send_port = tcp_soket.getsockname()
        # 记录开始时间 data易于查看 time用于计算
        now1_time = datetime.datetime.now()
        Labial_time = time.time()
        time_start = Labial_time
        # 设置发送时间
        Send_time = Labial_time + time_ + 1

        # 设置发送个数
        Send_num = num_

        # 12小时发送时间  === 43200
        print("------------------------------------------------------------------")
        # 打印当前时间
        print(now1_time)
        # 计数器
        counter = 0
        while Labial_time <= Send_time - 1 and counter <= Send_num - 1:
            # 每400包打印一次信息

            # print(Labial_time, '发送个数:', counter,'开始时间 =====', now1_time)
            l = len(data)
            for z in range(l):
                Labial_time = time.time()
                if Labial_time >= Send_time - 1 or counter > Send_num - 1:
                    break

                try:
                    tcp_soket.send(bytes.fromhex(data[z]))
                    counter = counter + 1


                except ConnectionAbortedError:
                    counter = counter - 1
                    now_time = datetime.datetime.now()
                    print('\r\nsocket error,do reconnect ', 'Aborted')
                    print(f"分机号{data[0].replace(' ', '')[60:62]}")
                    print(f"断开端口号为:{send_port}")
                    print('报文个数=====', counter)
                    print('开始时间 =====', now1_time)
                    print('出错时间 =====', now_time)
                    print(f"上位机应接收:{(datalen - 20) * counter}B")
                    time.sleep(10)
                    tcp_soket = doConnect(self.serve_ip, self.serve_port)
                    send_port = tcp_soket.getsockname()
                    tcp_soket.send(bytes.fromhex(data[z]))
                    counter = counter + 1


                except ConnectionResetError:
                    counter = counter - 1
                    now_time = datetime.datetime.now()
                    print('\r\nsocket error,do reconnect ', 'Reseterror')
                    print(f"分机号{data[0].replace(' ', '')[60:62]}")
                    print(f"断开端口号为:{send_port}")
                    print('报文个数=====', counter)
                    print('开始时间 =====', now1_time)
                    print('出错时间 =====', now_time)
                    print(f"上位机应接收:{(datalen - 20) * counter}B")
                    time.sleep(10)
                    # timeee = timeee - 3
                    tcp_soket = doConnect(self.serve_ip, self.serve_port)
                    send_port = tcp_soket.getsockname()
                    tcp_soket.send(bytes.fromhex(data[z]))
                    counter = counter + 1
                # 发送间隔
                time.sleep(send_gap)
                print_progress(num_, counter)
                now_time = datetime.datetime.now()
                # print('time :', now_time)
        tcp_soket.shutdown(1)
        time.sleep(0.1)
        tcp_soket.close()
        now_time = datetime.datetime.now()
        send_time = time.time() - time_start

        print('报文个数=====', counter)
        print(f"上位机发送数量:{(datalen) * counter}B")
        print(f"分机号{data[0].replace(' ', '')[60:62]}下位机应接收:{(datalen - 20) * counter}B")
        print(f"发送端口号为:{send_port}")
        print(f'传输速率为:{(datalen) * counter / send_time / 1024 / 1024} MB/S')
        print(f'发送频率为{counter / send_time}条/秒')
        print('开始时间 =====', now1_time)
        print('结束时间 =====', now_time)
        print("------------------------------------------------------------------")


if __name__ == '__main__':
    ip_port = [('192.188.1.200', 52245), ('192.188.1.223', 10241), ('192.168.2.175', 502), ("192.168.2.253", 10268)]
    w = 1
    prject = Tup0001(ip_port[w][0], ip_port[w][1])

    data1 = Generate_data(1024, type_='01', models='01')
    data2 = Generate_data(1, type_='01', models='02')
    # data3 = Generate_data(1024*10, type_='01', models='03')
    # data4 = Generate_data(1024*10, type_='01', models='04')
    # data5 = Generate_data(1024*8, type_='00', models='05')
    # data6 = Generate_data(1024 * 8, type_='00', models='06')
    # data7 = Generate_data(1024 * 8, type_='00', models='07')
    # data8 = Generate_data(1024 * 8, type_='00', models='08')
    # data9 = Generate_data(1024 * 8, type_='01', models='09')



    thread1 = threading.Thread(target=prject.send_,
                               kwargs={"num_": 3000, "send_gap": 0.05, "data": data1})
    thread2 = threading.Thread(target=prject.send_,
                               kwargs={"num_": 3000,  "send_gap": 0.2, "data": data2})
    thread3 = threading.Thread(target=prject.send_,
                               kwargs={"num_": 3000, "send_gap": 0.2, "data": data2})
    thread4 = threading.Thread(target=prject.send_,
                               kwargs={"num_": 3000, "send_gap": 0.2, "data": data2})
    # thread5 = threading.Thread(target=prject.send_,
    #                            kwargs={"num_": 3000, "send_gap": 0.001, "data": data5})
    # thread6 = threading.Thread(target=prject.send_,
    #                            kwargs={"num_": 3000,  "send_gap": 0.001, "data": data6})
    # thread7 = threading.Thread(target=prject.send_,
    #                            kwargs={"num_": 3000, "send_gap": 0.001, "data": data7})
    # thread8 = threading.Thread(target=prject.send_,
    #                            kwargs={"num_": 3000, "send_gap": 0.001, "data": data8})
    # thread9 = threading.Thread(target=prject.send_,
    #                            kwargs={"num_": 3000, "send_gap": 0.001, "data": data9})

    # Plist = [thread1, thread2, thread3, thread4, thread5, thread6, thread7, thread8]
    # Plist = [thread1, thread2]
    Plist = [thread1]
    # # #,thread2,thread3,thread4
    # # # print(data1[0])
    # # # print(data3[0])
    for i in Plist:
        i.start()
        # i.join()
    #
    for j in Plist:
        j.join()

UDP根据指定协议发包

import time
from socket import *
import struct
import math
import datetime
import threading


def the_not(value, pos):
    """
    指定位数取反
    :param value:数据
    :param pos: 位数
    leng 传递二进制长度 - 1
    将 获取到的数据转换为2进制后,将数据的最高位去除,
    如数据长度未满足pos长度将会在高位补零,并将其余所
    有位数0和1置换在从最高位补1并返回
    :return:
    """

    if value == 0:
        value = 1
    value = value - 1
    value = "{0:b}".format(value)
    a = ((pos * 8) - 1)
    value = value.rjust(a, '0')
    value = value.replace('1', '2')
    value = value.replace('0', '1')
    value = value.replace('2', '0')
    value = '1' + value
    value = hex((int(value, 2)))[2:]
    value = value.rjust((pos * 2), '0')

    return value


# -> object 描述返回值数据类型
def Override_override(ov: object, value: object, leng: object) -> object:
    """
    更改字符串指定位置的字符
    :param ov: 被更改的老字符串
    :param value: 更改的值
    :param leng: 起始位置
    :return: 更改后的字符串
    """
    len_ = int(len(value))
    # print(f"ov值为:{ov},新的值为:{ov[:leng * 2] + value + ov[leng + (leng * 2):]}")
    return ov[:leng * 2] + value + ov[len_ + (leng * 2):]


def float_to_hex(f):
    return hex(struct.unpack('<I', struct.pack('<f', f))[0])


def type_hex(value_, type_, Positive_and_Negative=0) -> str:
    """
    输入值和数据类型 默认为正数 并根据对应的解析方式返回16进制的值
    :param value_: 值
    :param type_: 数据类型
    :param Positive_and_Negative: 正负项
    :return: 16进制的值
    """
    if Positive_and_Negative == 1:
        if type_ == 'f':
            data10 = float(value_)
            data10hex = float_to_hex(data10)[2:]
            data10hex = bin(int(data10hex, 16))[2:]
            data10hex = hex(int('1' + data10hex.rjust(31, '0'), 2))[2:]
            return data10hex.rjust(8, '0')
        elif type_ == 'i':
            data10 = int(value_)
            return the_not(data10, 4)
        elif type_ == 's':
            data10 = int(value_)
            return the_not(data10, 2)
        elif type_ == 'c':
            data10 = hex(int(value_))[2:]
            return data10.rjust(2, '0')
    elif Positive_and_Negative == 0:
        if type_ == 'f':
            data10 = float(value_)
            data10hex = float_to_hex(data10)[2:]
            return data10hex.rjust(8, '0')
        elif type_ == 'i':
            data8hex = hex(int(value_))[2:]
            return data8hex.rjust(8, '0')
        elif type_ == 's':
            data8hex = hex(int(value_))[2:]
            return data8hex.rjust(4, '0')
        elif type_ == 'c':
            data10 = hex(int(value_))[2:]
            return data10.rjust(2, '0')


def type_hex_new(value_, type_, Positive_and_Negative=0) -> str:
    """
    输入值和数据类型 默认为正数 并根据对应的解析方式返回 置返的16进制的值
    :param value_:
    :param type_:
    :param Positive_and_Negative:
    :return:
    """
    hex_ = type_hex(value_, type_, Positive_and_Negative=Positive_and_Negative)
    if type_ == 'f':
        a = int(hex_[0:2], 16)
        b = int(hex_[2:4], 16) * 256
        c = int(hex_[4:6], 16) * (256 * 256)
        d = int(hex_[6:8], 16) * (256 * 256 * 256)
        max_ = hex(int(a + b + c + d))[2:]
        max_ = max_.rjust(8, '0')
        return max_
    elif type_ == 'i':
        a = int(hex_[0:2], 16)
        b = int(hex_[2:4], 16) * 256
        c = int(hex_[4:6], 16) * (256 * 256)
        d = int(hex_[6:8], 16) * (256 * 256 * 256)
        max_ = hex(int(a + b + c + d))[2:]
        max_ = max_.rjust(8, '0')
        return max_
        # = '0x' + hex_[0:2]
    elif type_ == 's':
        a = int(hex_[0:2], 16)
        b = int(hex_[2:4], 16) * 256
        max_ = hex(int(a + b))[2:]
        max_ = max_.rjust(4, '0')
        return max_
    elif type_ == 'c':
        return hex_


def doConnect(host, port):
    # tcp_soket = socket(AF_INET, SOCK_STREAM)

    tcp_soket = socket(AF_INET, SOCK_DGRAM)
    try:
        tcp_soket.connect((host, port))
    except:
        ...
    return tcp_soket


def Generate_data(message_len: int, type_='00', models: str = '01') -> object:
    """
    输入 数据长度 和数据类型,以及分机号,返回一个长度400的数组
    data_type:更改为0 返回的数据为1024随机数据类型,1为自定义数据
    :type type_: object
    :param message_len: 报文长度 1 - 1024 int类型
    :param type_: 报文类型 01 00 str
    :param models: 分机号 为 01 - 04 str
    :return:返回制造的数据数组
    """
    message_list = []
    data_num = 0
    for z in range(-200, 201):
        z = int(math.fabs(z))
        a = int((z * z) / (2 * 100))
        data_type = 1

        if data_type == 1:
            # char
            Data1 = type_hex(str(z % 2), 'c')
            # shoar
            data2 = type_hex_new(str(31267 + a), 's')
            # float
            data3 = type_hex_new(str((z * z) / (2 * 100)), 'f')
            # int
            data4 = type_hex_new(str(100000 + (z * 100000)), 'i')
            # char
            data5 = type_hex(str(((z + 1) % 2) * 5), 'c')
            # float
            data6 = type_hex_new(str(0.99 + (z * 10)), 'f')
            # shoar 负数 递增
            data7 = type_hex_new(str(31267 - z), 's', Positive_and_Negative=1)
            # int1
            data8 = type_hex_new(str(800000 + (a * 50000)), 'i')
            # int 负数
            data9 = type_hex_new(str(100000 + (z * 100000)), 'i', Positive_and_Negative=1)
            # float 负数
            data10 = type_hex_new(str((z * z) / (2 * 100)), 'f', Positive_and_Negative=1)
            # char 55
            data11 = type_hex_new(str(z % 2 * 85), 'c')
            # shoar 负数递减
            data12 = type_hex_new(str(31267 + z), 's', Positive_and_Negative=1)
            # float 改
            data13 = type_hex_new(str(0.4 + (z * 2)), 'f')
            # int 改
            data14 = type_hex_new(str(100000 + (z * 83000)), 'i')
            # float 改
            data15 = type_hex_new(str(0.3 + (z * 0.1)), 'f')
            # shoar
            data16 = type_hex_new(str(150 * z), 's')
            # char
            data17 = type_hex_new(str(z % 2 * 165), 'c')
            # shoar 负数
            data18 = type_hex_new(str((30 * a)), 's')
            # int
            data19 = type_hex_new(str((a * 20000)), 'i')
            # char
            data20 = type_hex(str((z % 2) * 90), 'c')
            Data_Sum = '0'
            #设置长度
            Data_Sum = Data_Sum.ljust((2 * message_len), "0")
            Data_Sum = Override_override(Data_Sum, Data1, 0)
            Data_Sum = Override_override(Data_Sum, data2, 1)
            Data_Sum = Override_override(Data_Sum, data3, 3)
            Data_Sum = Override_override(Data_Sum, data4, 7)
            Data_Sum = Override_override(Data_Sum, data5, 11)
            Data_Sum = Override_override(Data_Sum, data6, 12)
            Data_Sum = Override_override(Data_Sum, data7, 16)
            Data_Sum = Override_override(Data_Sum, data8, 18)
            Data_Sum = Override_override(Data_Sum, data9, 22)
            Data_Sum = Override_override(Data_Sum, data10, 26)
            Data_Sum = Override_override(Data_Sum, data11, 30)
            Data_Sum = Override_override(Data_Sum, data12, 31)
            Data_Sum = Override_override(Data_Sum, data13, 33)
            Data_Sum = Override_override(Data_Sum, data14, 37)
            Data_Sum = Override_override(Data_Sum, data15, 41)
            Data_Sum = Override_override(Data_Sum, data16, 45)
            Data_Sum = Override_override(Data_Sum, data17, 47)
            Data_Sum = Override_override(Data_Sum, data18, 48)
            Data_Sum = Override_override(Data_Sum, data19, 50)
            Data_Sum = Override_override(Data_Sum, data20, 54)

            for value_w in range(1, 18):
                Data_Sum = Override_override(Data_Sum, Data_Sum[0:55 * 2], 55 * value_w)
            start = 990
            Data_Sum = Override_override(Data_Sum, Data1, start + 0)
            Data_Sum = Override_override(Data_Sum, data2, start + 1)
            Data_Sum = Override_override(Data_Sum, data3, start + 3)
            Data_Sum = Override_override(Data_Sum, data4, start + 7)
            Data_Sum = Override_override(Data_Sum, data5, start + 11)
            Data_Sum = Override_override(Data_Sum, data6, start + 12)
            Data_Sum = Override_override(Data_Sum, data7, start + 16)
            Data_Sum = Override_override(Data_Sum, data8, start + 18)
            Data_Sum = Override_override(Data_Sum, data9, start + 22)
            Data_Sum = Override_override(Data_Sum, data10, start + 26)
            Data_Sum = Override_override(Data_Sum, data11, start + 30)
            Data_Sum = Override_override(Data_Sum, data12, start + 31)
            Data_Sum = Override_override(Data_Sum, data20, start + 33)
            Data_Sum = Override_override(Data_Sum, Data_Sum, 1024)
            Data_Sum = Override_override(Data_Sum, Data_Sum, 1024*2)
            Data_Sum = Override_override(Data_Sum, Data_Sum, 1024*3)
            Data_Sum = Override_override(Data_Sum, Data_Sum, 1024*4)
            Data_Sum = Override_override(Data_Sum, Data_Sum, 1024*5)
            Data_Sum = Override_override(Data_Sum, Data_Sum, 1024*6)
            Data_Sum = Override_override(Data_Sum, Data_Sum, 1024*7)
            Data_Sum = Override_override(Data_Sum, Data_Sum, 1024 * 8)
            Data_Sum = Override_override(Data_Sum, Data_Sum, 1024 * 9)




        elif data_type == 0:
            data_num = data_num + 1
            if data_num > 255:
                break
            # int 正
            # data_1 = type_hex_new(str(100000 + (z * 100000)), 'i')
            # # flot 负数
            # data_1 = type_hex_new(str((z * z) / (2 * 100)), 'f', Positive_and_Negative=1)
            # # char
            # data_1 = type_hex(str(z % 2), 'c')
            # data_1 = type_hex_new(str(31267 - z), 's', Positive_and_Negative=1)
            # 报文长度
            Data_Sum = str()
            data_num1 = hex(data_num)[2:].rjust(2, '0')
            # print(data_num)
            for i in range(message_len + 1):
                Data_Sum = Data_Sum + data_num1
            # Data_Sum = Data_Sum.rjust(2,message_len, data_num)
            # 填满1024

            # for value_w in range(0, message_len, 2):
            #
            #     Data_Sum = Override_override(Data_Sum, hex(value_w), 2)

        # 设置报文类型
        Message_type = type_
        #
        # if type_ == '00' and '01':
        #     Message_type = type_
        # else:
        #     if z % 2 == 0:
        #         Message_type = '00'
        #     else:
        #         Message_type = '01'

        # 设置长度
        byte_len = int(message_len) * 2
        Data_Sum = Data_Sum[0:byte_len]

        Message_len = hex(int(byte_len / 2))[2:].rjust(4, '0')
        # test = (z, '=======', '1', Data_Sum)
        #
        # with open('test.txt', 'a') as f:
        #     f.write(str(test) + '\n')
        data_sum = ()

        message = '01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 %s %s %s ' \
                  '00 00 00 00 00 00 %s 30 30' % (models, Message_type, Message_len, Data_Sum)

        message_list.append(Data_Sum)
    return message_list


class Tup0001:
    def __init__(self, serve_ip, serve_port):
        self.serve_ip = serve_ip
        self.serve_port = serve_port

    def send_(self, send_gap=0.05, num_=1000000000000000000000000000, time_=1000000000000000000000000000,
               data=None):
        """
        不设置默认为 100000000000000000000000000000000
        :param time_: 发送时间
        :param num_: 发送个数
        :param send_gap: 发送间隔浮点数
        :param data: 导入数组data
        :return:
        """
        # 建立连接
        datalen = len(data[0].replace(' ', ''))/2
        tcp_soket = doConnect(self.serve_ip, self.serve_port)
        send_port = tcp_soket.getsockname()
        # 记录开始时间 data易于查看 time用于计算
        now1_time = datetime.datetime.now()
        Labial_time = time.time()
        time_start = Labial_time
        # 设置发送时间
        Send_time = Labial_time + time_ + 1

        # 设置发送个数
        Send_num = num_

        # 12小时发送时间  === 43200

        # 打印当前时间
        print(now1_time)
        # 计数器
        counter = 0
        while Labial_time <= Send_time - 1 and counter <= Send_num - 1:
            # 每400包打印一次信息

            # print(Labial_time, '发送个数:', counter,'开始时间 =====', now1_time)
            l = len(data)
            for z in range(l):
                Labial_time = time.time()
                if Labial_time >= Send_time - 1 or counter > Send_num - 1:
                    break

                try:
                    tcp_soket.send(bytes.fromhex(data[z]))
                    counter = counter + 1

                except ConnectionAbortedError:
                    counter = counter - 1
                    now_time = datetime.datetime.now()
                    print('\r\nsocket error,do reconnect ', 'Aborted')
                    print(f"分机号{data[0].replace(' ', '')[60:62]}")
                    print('报文个数=====', counter)
                    print('开始时间 =====', now1_time)
                    print('出错时间 =====', now_time)
                    print(f"上位机应接收:{(datalen - 20) * counter}B")
                    time.sleep(10)
                    tcp_soket = doConnect(self.serve_ip, self.serve_port)
                    tcp_soket.send(bytes.fromhex(data[z]))
                    counter = counter + 1


                except ConnectionResetError:
                    counter = counter - 1
                    now_time = datetime.datetime.now()
                    print('\r\nsocket error,do reconnect ', 'Reseterror')
                    print(f"分机号{data[0].replace(' ', '')[60:62]}")
                    print('报文个数=====', counter)
                    print('开始时间 =====', now1_time)
                    print('出错时间 =====', now_time)
                    print(f"上位机应接收:{(datalen - 20) * counter}B")
                    time.sleep(10)
                    # timeee = timeee - 3
                    tcp_soket = doConnect(self.serve_ip, self.serve_port)
                    tcp_soket.send(bytes.fromhex(data[z]))
                    counter = counter + 1
                # 发送间隔
                time.sleep(send_gap)
                now_time = datetime.datetime.now()
                # print('time :', now_time)
        tcp_soket.shutdown(1)
        time.sleep(0.1)
        tcp_soket.close()
        now_time = datetime.datetime.now()
        send_time = time.time() - time_start

        print('报文个数=====', counter)
        print(f"上位机发送数量:{(datalen) * counter}B")
        print(f"分机号{data[0].replace(' ', '')[60:62]}下位机应接收:{(datalen - 20) * counter}B")
        print(f"端口号为:{send_port}")
        print(f'传输速率为:{(datalen) * counter / send_time / 1024 / 1024} MB/S')
        print(f'发送频率为{counter/send_time}条/秒')
        print('开始时间 =====', now1_time)
        print('结束时间 =====', now_time)
        print("------------------------------------------------------------")


if __name__ == '__main__':
    ip_port = [('192.188.1.200', 52245), ('192.188.1.223', 10242), ('10.4.0.9', 8080), ("192.168.2.253", 10268)]
    w = 1
    prject = Tup0001(ip_port[w][0], ip_port[w][1])

    data1 = Generate_data(1, type_='01', models='01')
    data2 = Generate_data(1024 * 10, type_='01', models='02')
    data3 = Generate_data(1024 * 10, type_='01', models='03')
    data4 = Generate_data(1024 * 10, type_='01', models='04')
    data5 = Generate_data(1024 * 10, type_='00', models='05')
    data6 = Generate_data(1024 * 10, type_='00', models='06')
    data7 = Generate_data(1024 * 10, type_='00', models='07')
    data8 = Generate_data(1024 * 10, type_='00', models='08')
    data9 = Generate_data(1024 * 10, type_='01', models='09')



    thread1 = threading.Thread(target=prject.send_,
                               kwargs={"num_": 3000, "send_gap": 0.05, "data": data1})
    thread2 = threading.Thread(target=prject.send_,
                               kwargs={"num_": 1000,  "send_gap": 0.2, "data": data2})
    thread3 = threading.Thread(target=prject.send_,
                               kwargs={"num_": 1000, "send_gap": 0.2, "data": data3})
    thread4 = threading.Thread(target=prject.send_,
                               kwargs={"num_": 1000, "send_gap": 0.2, "data": data4})
    thread5 = threading.Thread(target=prject.send_,
                               kwargs={"num_": 1000, "send_gap": 0.2, "data": data5})
    thread6 = threading.Thread(target=prject.send_,
                               kwargs={"num_": 1000,  "send_gap": 0.2, "data": data6})
    thread7 = threading.Thread(target=prject.send_,
                               kwargs={"num_": 1000, "send_gap": 0.2, "data": data7})
    thread8 = threading.Thread(target=prject.send_,
                               kwargs={"num_": 1000, "send_gap": 0.2, "data": data8})
    thread9 = threading.Thread(target=prject.send_,
                               kwargs={"num_": 1000, "send_gap": 0.2, "data": data9})

    # Plist = [thread1, thread2, thread3, thread4, thread5, thread6, thread7, thread8]
    # # #,thread2,thread3,thread4
    # Plist = [thread1, thread2, thread3, thread4]
    Plist = [thread1]
    # # # print(data1[0])
    # # # print(data3[0])
    for i in Plist:
        i.start()
        # i.join()
    #
    for j in Plist:
        j.join()

import serial
import serial.tools.list_ports
import threading
import time
import struct
import math
import datetime
import threading


def the_not(value, pos):
    """
    指定位数取反
    :param value:数据
    :param pos: 位数
    leng 传递二进制长度 - 1
    将 获取到的数据转换为2进制后,将数据的最高位去除,
    如数据长度未满足pos长度将会在高位补零,并将其余所
    有位数0和1置换在从最高位补1并返回
    :return:
    """

    if value == 0:
        value = 1
    value = value - 1
    value = "{0:b}".format(value)
    a = ((pos * 8) - 1)
    value = value.rjust(a, '0')
    value = value.replace('1', '2')
    value = value.replace('0', '1')
    value = value.replace('2', '0')
    value = '1' + value
    value = hex((int(value, 2)))[2:]
    value = value.rjust((pos * 2), '0')

    return value


# -> object 描述返回值数据类型
def Override_override(ov: object, value: object, leng: object) -> object:
    """
    更改字符串指定位置的字符
    :param ov: 被更改的老字符串
    :param value: 更改的值
    :param leng: 起始位置
    :return: 更改后的字符串
    """
    len_ = int(len(value))
    # print(f"ov值为:{ov},新的值为:{ov[:leng * 2] + value + ov[leng + (leng * 2):]}")
    return ov[:leng * 2] + value + ov[len_ + (leng * 2):]


def float_to_hex(f):
    return hex(struct.unpack('<I', struct.pack('<f', f))[0])


def type_hex(value_, type_, Positive_and_Negative=0) -> str:
    """
    输入值和数据类型 默认为正数 并根据对应的解析方式返回16进制的值
    :param value_: 值
    :param type_: 数据类型
    :param Positive_and_Negative: 正负项
    :return: 16进制的值
    """
    if Positive_and_Negative == 1:
        if type_ == 'f':
            data10 = float(value_)
            data10hex = float_to_hex(data10)[2:]
            data10hex = bin(int(data10hex, 16))[2:]
            data10hex = hex(int('1' + data10hex.rjust(31, '0'), 2))[2:]
            return data10hex.rjust(8, '0')
        elif type_ == 'i':
            data10 = int(value_)
            return the_not(data10, 4)
        elif type_ == 's':
            data10 = int(value_)
            return the_not(data10, 2)
        elif type_ == 'c':
            data10 = hex(int(value_))[2:]
            return data10.rjust(2, '0')
    elif Positive_and_Negative == 0:
        if type_ == 'f':
            data10 = float(value_)
            data10hex = float_to_hex(data10)[2:]
            return data10hex.rjust(8, '0')
        elif type_ == 'i':
            data8hex = hex(int(value_))[2:]
            return data8hex.rjust(8, '0')
        elif type_ == 's':
            data8hex = hex(int(value_))[2:]
            return data8hex.rjust(4, '0')
        elif type_ == 'c':
            data10 = hex(int(value_))[2:]
            return data10.rjust(2, '0')


def type_hex_new(value_, type_, Positive_and_Negative=0) -> str:
    """
    输入值和数据类型 默认为正数 并根据对应的解析方式返回 置返的16进制的值
    :param value_:
    :param type_:
    :param Positive_and_Negative:
    :return:
    """
    hex_ = type_hex(value_, type_, Positive_and_Negative=Positive_and_Negative)
    if type_ == 'f':
        a = int(hex_[0:2], 16)
        b = int(hex_[2:4], 16) * 256
        c = int(hex_[4:6], 16) * (256 * 256)
        d = int(hex_[6:8], 16) * (256 * 256 * 256)
        max_ = hex(int(a + b + c + d))[2:]
        max_ = max_.rjust(8, '0')
        return max_
    elif type_ == 'i':
        a = int(hex_[0:2], 16)
        b = int(hex_[2:4], 16) * 256
        c = int(hex_[4:6], 16) * (256 * 256)
        d = int(hex_[6:8], 16) * (256 * 256 * 256)
        max_ = hex(int(a + b + c + d))[2:]
        max_ = max_.rjust(8, '0')
        return max_
        # = '0x' + hex_[0:2]
    elif type_ == 's':
        a = int(hex_[0:2], 16)
        b = int(hex_[2:4], 16) * 256
        max_ = hex(int(a + b))[2:]
        max_ = max_.rjust(4, '0')
        return max_
    elif type_ == 'c':
        return hex_




def Generate_data(message_len: int, type_='00', models: str = '01') -> object:
    """
    输入 数据长度 和数据类型,以及分机号,返回一个长度400的数组
    data_type:更改为0 返回的数据为1024随机数据类型,1为自定义数据
    :type type_: object
    :param message_len: 报文长度 1 - 1024 int类型
    :param type_: 报文类型 01 00 str
    :param models: 分机号 为 01 - 04 str
    :return:返回制造的数据数组
    """
    message_list = []
    data_num = 0
    for z in range(-200, 201):
        z = int(math.fabs(z))
        a = int((z * z) / (2 * 100))
        data_type = 1

        if data_type == 1:
            # char
            Data1 = type_hex(str(z % 2), 'c')
            # shoar
            data2 = type_hex_new(str(31267 + a), 's')
            # float
            data3 = type_hex_new(str((z * z) / (2 * 100)), 'f')
            # int
            data4 = type_hex_new(str(100000 + (z * 100000)), 'i')
            # char
            data5 = type_hex(str(((z + 1) % 2) * 5), 'c')
            # float
            data6 = type_hex_new(str(0.99 + (z * 10)), 'f')
            # shoar 负数 递增
            data7 = type_hex_new(str(31267 - z), 's', Positive_and_Negative=1)
            # int1
            data8 = type_hex_new(str(800000 + (a * 50000)), 'i')
            # int 负数
            data9 = type_hex_new(str(100000 + (z * 100000)), 'i', Positive_and_Negative=1)
            # float 负数
            data10 = type_hex_new(str((z * z) / (2 * 100)), 'f', Positive_and_Negative=1)
            # char 55
            data11 = type_hex_new(str(z % 2 * 85), 'c')
            # shoar 负数递减
            data12 = type_hex_new(str(31267 + z), 's', Positive_and_Negative=1)
            # float 改
            data13 = type_hex_new(str(0.4 + (z * 2)), 'f')
            # int 改
            data14 = type_hex_new(str(100000 + (z * 83000)), 'i')
            # float 改
            data15 = type_hex_new(str(0.3 + (z * 0.1)), 'f')
            # shoar
            data16 = type_hex_new(str(150 * z), 's')
            # char
            data17 = type_hex_new(str(z % 2 * 165), 'c')
            # shoar 负数
            data18 = type_hex_new(str((30 * a)), 's')
            # int
            data19 = type_hex_new(str((a * 20000)), 'i')
            # char
            data20 = type_hex(str((z % 2) * 90), 'c')
            Data_Sum = '0'
            #设置长度
            Data_Sum = Data_Sum.ljust((2 * message_len), "0")
            Data_Sum = Override_override(Data_Sum, Data1, 0)
            Data_Sum = Override_override(Data_Sum, data2, 1)
            Data_Sum = Override_override(Data_Sum, data3, 3)
            Data_Sum = Override_override(Data_Sum, data4, 7)
            Data_Sum = Override_override(Data_Sum, data5, 11)
            Data_Sum = Override_override(Data_Sum, data6, 12)
            Data_Sum = Override_override(Data_Sum, data7, 16)
            Data_Sum = Override_override(Data_Sum, data8, 18)
            Data_Sum = Override_override(Data_Sum, data9, 22)
            Data_Sum = Override_override(Data_Sum, data10, 26)
            Data_Sum = Override_override(Data_Sum, data11, 30)
            Data_Sum = Override_override(Data_Sum, data12, 31)
            Data_Sum = Override_override(Data_Sum, data13, 33)
            Data_Sum = Override_override(Data_Sum, data14, 37)
            Data_Sum = Override_override(Data_Sum, data15, 41)
            Data_Sum = Override_override(Data_Sum, data16, 45)
            Data_Sum = Override_override(Data_Sum, data17, 47)
            Data_Sum = Override_override(Data_Sum, data18, 48)
            Data_Sum = Override_override(Data_Sum, data19, 50)
            Data_Sum = Override_override(Data_Sum, data20, 54)

            for value_w in range(1, 18):
                Data_Sum = Override_override(Data_Sum, Data_Sum[0:55 * 2], 55 * value_w)
            start = 990
            Data_Sum = Override_override(Data_Sum, Data1, start + 0)
            Data_Sum = Override_override(Data_Sum, data2, start + 1)
            Data_Sum = Override_override(Data_Sum, data3, start + 3)
            Data_Sum = Override_override(Data_Sum, data4, start + 7)
            Data_Sum = Override_override(Data_Sum, data5, start + 11)
            Data_Sum = Override_override(Data_Sum, data6, start + 12)
            Data_Sum = Override_override(Data_Sum, data7, start + 16)
            Data_Sum = Override_override(Data_Sum, data8, start + 18)
            Data_Sum = Override_override(Data_Sum, data9, start + 22)
            Data_Sum = Override_override(Data_Sum, data10, start + 26)
            Data_Sum = Override_override(Data_Sum, data11, start + 30)
            Data_Sum = Override_override(Data_Sum, data12, start + 31)
            Data_Sum = Override_override(Data_Sum, data20, start + 33)
            Data_Sum = Override_override(Data_Sum, Data_Sum, 1024)
            Data_Sum = Override_override(Data_Sum, Data_Sum, 1024*2)
            Data_Sum = Override_override(Data_Sum, Data_Sum, 1024*3)
            Data_Sum = Override_override(Data_Sum, Data_Sum, 1024*4)
            Data_Sum = Override_override(Data_Sum, Data_Sum, 1024*5)
            Data_Sum = Override_override(Data_Sum, Data_Sum, 1024*6)
            Data_Sum = Override_override(Data_Sum, Data_Sum, 1024*7)


        elif data_type == 0:
            data_num = data_num + 1
            if data_num > 255:
                break
            # int 正
            # data_1 = type_hex_new(str(100000 + (z * 100000)), 'i')
            # # flot 负数
            # data_1 = type_hex_new(str((z * z) / (2 * 100)), 'f', Positive_and_Negative=1)
            # # char
            # data_1 = type_hex(str(z % 2), 'c')
            # data_1 = type_hex_new(str(31267 - z), 's', Positive_and_Negative=1)
            # 报文长度
            Data_Sum = str()
            data_num1 = hex(data_num)[2:].rjust(2, '0')
            # print(data_num)
            for i in range(message_len + 1):
                Data_Sum = Data_Sum + data_num1
            # Data_Sum = Data_Sum.rjust(2,message_len, data_num)
            # 填满1024

            # for value_w in range(0, message_len, 2):
            #
            #     Data_Sum = Override_override(Data_Sum, hex(value_w), 2)

        # 设置报文类型
        Message_type = type_
        #
        # if type_ == '00' and '01':
        #     Message_type = type_
        # else:
        #     if z % 2 == 0:
        #         Message_type = '00'
        #     else:
        #         Message_type = '01'

        # 设置长度
        byte_len = int(message_len) * 2
        Data_Sum = Data_Sum[0:byte_len]

        Message_len = hex(int(byte_len / 2))[2:].rjust(4, '0')
        # test = (z, '=======', '1', Data_Sum)
        #
        # with open('test.txt', 'a') as f:
        #     f.write(str(test) + '\n')
        data_sum = ()

        message = '01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 %s %s %s ' \
                  '00 00 00 00 00 00 %s 30 30' % (models, Message_type, Message_len, Data_Sum)

        message_list.append(Data_Sum)
    return message_list



class RS485:
    def __init__(self, baudrate, pods):
        self.port = pods
        self.baudrate = baudrate
        self.ser = serial.Serial(self.port, self.baudrate)


    def slice_data(slef,data):
        data = data.replace(' ', '')


        def split_string(data):
            sub = 20
            length = len(data)
            avg_length = length // sub  # 每个子字符串的平均长度
            remainder = length % sub  # 余数,用于判断最后一个子字符串的长度
            
            result = []
            start = 0
            end = avg_length
            
            for i in range(sub):
                # 判断是否为最后一个子字符串,并调整结束索引
                if i == 7:
                    end += remainder
                
                substring = data[start:end]
                result.append(substring)
                
                start = end
                end += avg_length
            
            return result
        
        
        def generate_data_packets(datalist):
            for index,value in enumerate(datalist):
                datalist[index] = '5a5a' + hex(int(index + 1))[2:].rjust(2, '0')+ hex(int(len(value)/2 + 5))[2:].rjust(2, '0') + value + 'cf'
            return datalist
        return generate_data_packets(split_string(data))


    def send_com(self, send_gap=0.5, num_=1000000000000000000000000000, time_=1000000000000000000000000000,
               data=None):
        # 获取data长度
        datalen = len(data[0].replace(' ', ''))/2
        # 读取当前时间
        now1_time = datetime.datetime.now()

        Labial_time = time.time()
        time_start = Labial_time
        Send_time = Labial_time + time_ + 1

        # 设置发送个数
        Send_num = num_

        # 12小时发送时间  === 43200

        # 打印当前时间
        print(Labial_time)
        # 计数器
        counter = 0
        while Labial_time <= Send_time - 1 and counter <= Send_num - 1:
            for z in range(len(data)):
                #更新时间
                Labial_time = time.time()
                if Labial_time >= Send_time - 1 or counter > Send_num - 1:
                    break
                for j in self.slice_data(data[z]):
                    self.ser.write(bytes.fromhex(j))
                    print(j)
                    time.sleep(send_gap)
                counter = counter + 1
            now_time = datetime.datetime.now()
        print('报文个数=====', counter)
        print(f"上位机发送数量:{(datalen) * counter}B")
        print(f"分机号{data[0].replace(' ', '')[60:62]}下位机应接收:{(datalen - 20) * counter}B")
        print(f'传输速率为:{(datalen) * counter / Send_time / 1024 / 1024} MB/S')
        print('开始时间 =====', now1_time)
        print('结束时间 =====', now_time)
    

if __name__ == '__main__':

    data1 = Generate_data(400, type_='01', models='03')
    data2 = Generate_data(1024*8, type_='01', models='02')
    data3 = Generate_data(1024*8, type_='01', models='03')
    data4 = Generate_data(1024*8, type_='01', models='04')
    
    def print_available_ports():
        ports = serial.tools.list_ports.comports()
        port_list = []
        for port in ports:
            port_list.append(port.device)
        return port_list

    pods = print_available_ports()

    for i in range(len(pods)):
        print(f"串口:{i}\t{pods[i]}")

    num = int(input("输入对应编号选择响应的串口"))
    # num = 1


    # 串口配置
    port = pods[num]
    baudrate = 115200
    prject = RS485(baudrate,pods[num])
    # 创建串口对象
    print(len(data1))
    prject.send_com(num_=1000, data=data1)


最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 213,992评论 6 493
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 91,212评论 3 388
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 159,535评论 0 349
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 57,197评论 1 287
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 66,310评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,383评论 1 292
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,409评论 3 412
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,191评论 0 269
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,621评论 1 306
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,910评论 2 328
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,084评论 1 342
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,763评论 4 337
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,403评论 3 322
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,083评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,318评论 1 267
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,946评论 2 365
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,967评论 2 351

推荐阅读更多精彩内容