多机时间同步

ROS1多机时,如果时间不同步,会导致某些topic频率下降严重。

# -*- coding: utf-8 -*-

import rospy ,time 
from std_msgs.msg import Float64
  
# 初始化ROS节点  
rospy.init_node('time_publisher')  
  

# 创建一个发布器,将Time消息发布到名为'time_topic'的主题上  
publisher = rospy.Publisher('/ftime_topic', Float64, queue_size=1)  
  
# 设置发布频率为1秒/次  
rate = rospy.Rate(2)  
time_message = Float64() 
while not rospy.is_shutdown(): 
    time_message = Float64() 

 
    time_message.data = time.time()
    print(time_message)
    # 发布Time消息  
    publisher.publish(time_message)  
      
    # 等待下一个循环周期  
    rate.sleep()
# -*- coding: utf-8 -*-
import rospy  
import time  ,datetime
import subprocess  
from std_msgs.msg import Float64
  
# 初始化ROS节点  
rospy.init_node('time_converter', anonymous=True)  
# mysub=rospy.Subscriber("/ftime_topic", Float64, callback)  

# 创建一个订阅者,订阅名为"float64_topic"的主题,数据类型为float64  
def callback(data):  
    global mysub
    # 将接收到的数据转换为年月日十分秒格式  
     
    dt_object = datetime.datetime.fromtimestamp(data.data)  

    formatted_time = dt_object.strftime("%Y-%m-%d %H:%M:%S")  
    print(formatted_time)
    
    # 尝试使用date命令设置系统时间  
    try:  
        subprocess.call(['sudo', 'date', '-s', formatted_time])  
        print("System time set successfully!")  
        mysub.unregister()
    except Exception as e:  
        print("Failed to set system time:", e)  
  
# 创建一个名为"float64_topic"的订阅者,数据类型为float64,队列大小为10  
mysub=rospy.Subscriber("/ftime_topic", Float64, callback)  

# 开始循环处理主题数据  
rospy.spin()

你可能感兴趣的:(ros,多机)