ROS Resources: Documentation | Support | Discussion Forum | Index | Service Status | ros @ Robotics Stack Exchange
Ask Your Question

Revision history [back]

I'm not sure if I got your question, however, I made a code like yours but using a class to subscribe and publish the data, with this, you avoid using global variables. With this code, you receive data from /cmd_vel and publish it into modbus_wrapper/output.

import rospy
from geometry_msgs.msg import Twist

class PublisherAndSubscriber():

    def __init__(self, pub_topic, sub_topic):
        self.publisher = rospy.Publisher(pub_topic, HoldingRegister, queue_size=500)
        self.subscriber = rospy.Subscriber(sub_topic, Twist, self.callback)
        self.x, self.y, self.z = 0, 0, 0
        self.cxx, self.cyy, self.czz = 0, 2, 0

    def publishera(self, x, y, z):
        output = HoldingRegister()
        output.data = [self.x, self.y, self.z, self.cxx, self.cyy, self.czz]

        emptyMsg = HoldingRegister()
        emptyMsg.data = 6*[0]

        rospy.loginfo("Sending arrays to the modbus server")
        for _ in xrange(10):
            self.publisher.publish(output)
            rospy.sleep(1)
            self.publisher.publish(emptyMsg)


    def callback(self, cmd_vel_msg):
        self.x = cmd_vel_msg.linear.x
        self.y = cmd_vel_msg.linear.y
        self.z = cmd_vel_msg.linear.z


if __name__ == "__main__":
    rospy.init_node("modbus_client_s7_1200")
    host = "192.168.0.199"
    port = 502
    if rospy.has_param("~ip"):
        host =  rospy.get_param("~ip")
    else:
        rospy.loginfo("For not using the default IP %s, add an arg e.g.: '_ip:=\"192.168.0.198\"'",host)
    if rospy.has_param("~port"):
        port =  rospy.get_param("~port")
    else:
        rospy.loginfo("For not using the default port %d, add an arg e.g.: '_port:=1234'",port)

    # setup modbus client for siemens s7 PLC  
    modclient = S7ModbusClient(host,port)
    rospy.loginfo("Setup complete")

    pubAndSub = PublisherAndSubscriber("modbus_wrapper/output", "cmd_vel")

    rate = rospy.Rate(100)

    while not rospy.is_shutdown():
        pubAndSub.publishera()
        rate.sleep()