#!/usr/bin/env python

"""
This example shows how sending a single message works.
"""

import can
import time
import os
import psutil
import gc  # 导入垃圾回收模块

def send_one():
    """Sends a single message."""

    # this uses the default configuration (for example from the config file)
    # see https://python-can.readthedocs.io/en/stable/configuration.html
    with can.interface.Bus(
        bustype='bmcan', channel=4, data_bitrate=2000000, tres=True
    ) as bus:
        print('Bus opened: ' + str(bus))
        msg = can.Message(
            arbitration_id=0xC0FFEE, data=[0, 25, 0, 1, 3, 1, 4, 1], is_extended_id=True
        )

        try:
            bus.send(msg, timeout=5)
            print(f"Message sent on {bus.channel_info}")
        except can.CanError:
            print("Message NOT sent")
    bus.shutdown()
    # 不需要手动调用bus.shutdown()，因为使用了with语句，它会自动处理

if __name__ == "__main__":
    pid = os.getpid()
    process = psutil.Process(pid)
    print('started')

    initial_mem = process.memory_info().rss / (1024 * 1024)

    for i in range(10000):
        send_one()
        time.sleep(0.001)


        # 打印占用的内存
        time_str = time.strftime(
            "%H:%M:%S", time.localtime(time.time()))
        memory = process.memory_info().rss / (1024 * 1024)
        print(f'{time_str} - {memory:.1f} MB, {1024.0 * (memory - initial_mem) / (i + 1):.3f}kB/call\n')
        print(i)
                # 手动调用垃圾回收
        #gc.collect()