ROS Resources: Documentation | Support | Discussion Forum | Index | Service Status | Q&A answers.ros.org
Ask Your Question
0

Python node for publishing keyboard events

asked 2019-02-15 03:14:35 -0600

Drkstr gravatar image

updated 2019-02-15 03:14:53 -0600

I am trying to build a node in python that publishes key press as strings onto a topic. I am able to print out the keypress on the console, but when I publish it I get this error :(

RuntimeError: maximum recursion depth exceeded

This is all of my code:

class KeyboardPublisher:

def __init__(self):
    # logging the node start
    rospy.loginfo("Starting node keyboard_publisher")

    # Initialise the node
    rospy.init_node("keypress_publisher", anonymous=True)

    # Create a publisher to the keypress topic
    self.keyboard_publisher = rospy.Publisher('/keypress', String, queue_size=1)

def publish_keypress(self, key_press):
    self.publish_keypress(key_press)

def on_press(self, key):
    print(key) #<-- this prints out the key press and then crashes
    self.publish_keypress(key)

def on_release(self, key):
    print('{0} release'.format(
        key))
    if key == Key.esc:
        # Stop listener
        return False

def keyboard_listener(self):
    # Collect events until released
    with Listener(
            on_press=self.on_press,
            on_release=self.on_release) as listener:
        listener.join()


if __name__ == '__main__':
   keyboard_publisher = KeyboardPublisher()
   keyboard_publisher.keyboard_listener()

    try:
      rospy.spin()
    except rospy.ROSInterruptException:
        print("Stopping keyboard_publisher"
edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2019-02-15 04:14:37 -0600

Delb gravatar image

updated 2019-02-15 04:15:51 -0600

There is something wrong here :

def publish_keypress(self, key_press):
    self.publish_keypress(key_press)

You call your function within itself so you end up in an infinite loop. I think you meant this instead :

def publish_keypress(self, key_press):
    keyboard_publisher.publish(key_press)
edit flag offensive delete link more

Comments

Ahhhh... Thanks for pointing that out.

Drkstr gravatar image Drkstr  ( 2019-02-15 06:03:44 -0600 )edit

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower

Stats

Asked: 2019-02-15 03:14:35 -0600

Seen: 2,248 times

Last updated: Feb 15 '19