ROS Subscriber and Publisher node
Hello ROS community,
I want to implement a ROS node that is both subscriber and publisher. The idea is that each time the subscribed topic changes, the node will publish to another topic. The node takes a detection command and gives a door command controlling a USB latch.
Here is the code :
#!/usr/bin/env python
import rospy
from std_msgs.msg import String
import serial
#Declaring USB port related to relay
relayport = serial.Serial(port = "/dev/ttyUSB0",
baudrate = 9600,
bytesize = serial.EIGHTBITS,
parity = serial.PARITY_NONE,
stopbits = serial.STOPBITS_ONE,
timeout = 1,
writeTimeout = 2)
#Declaring open and close commands in bytes used to control relay
open_cmd = b'\xA0\x01\x01\xA2'
close_cmd = b'\xA0\x01\x00\xA1'
door_state = ''
def Lock_callback(detection): #Callback function to be used when receiving detection topic data
global door_state
rospy.loginfo("Command is %s", detection.data)
if detection.data == 'SH' or detection.data == 'MH' : #Close relay (ON) in Short High and Medium High states to lock door
relayport.write(close_cmd)
door_state = 'closed'
rospy.loginfo("door_state %s", door_state)
else : #Open relay (OFF) in other detection states
relayport.write(open_cmd)
door_state = 'opened'
rospy.loginfo("door_state %s", door_state)
def Lock_decision(): #Lock decision function to subscribe to detection state topic and publish Lock topic
Lock_pub = rospy.Publisher('/doorcmd', String, queue_size=10)
rospy.init_node('Latch_decision', anonymous=True) #Create ROS node for relay
Lock_sub = rospy.Subscriber('/detection', String, Lock_callback) #Subscribe node to relay command topic
Lock_pub.publish(door_state)
rospy.spin()
if __name__ == '__main__':
Lock_decision()
The Lock_pub.publish only gives one value at the start and stops which is not what I want. I want to publish the /doorcmd topic everytime it is changed by the /detection topic. Any clues on how to do that ? What is the problem in my code ?
Thanks and regards. Lilia.