ROS callback not working from OpenGL spinOnce (glut)

asked 2018-04-02 07:53:49 -0500

charles.fox gravatar image

updated 2018-04-02 07:54:50 -0500

I'm trying to write a simple OpenGL/glut viewer program which subscribes to a chatter message. I've read in other posts that to do this we should pass control to glutMainLoop then call ros::spinOnce() from a glut idle function. However this is not working here. Is this is ROS bug or am I doing something wrong in the following code? (It prints "idle1" and "idle2" but not the chatter message.)

#include <GL/glut.h>
#include <GL/gl.h>
#include <GL/glu.h>
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include "ros/ros.h"
#include "std_msgs/String.h"
using namespace std;
void myinit(void)
{
    glClearColor (0.5, 0.5, 0.5, 0.0);
}   
void display(void){
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glutSolidTeapot(1.0);
    glutSwapBuffers();
}   
void chatterCallback(const std_msgs::String::ConstPtr& msg)
{
    ROS_INFO("I heard: [%s]", msg->data.c_str());
}   
void myidle()
{
    cout << "idle" << endl;
    ros::spinOnce();   //is not doing anything !?
    cout << "idle2" << endl;
}   
int main(int argc, char** argv)
{
    ros::init(argc, argv, "display");
    ros::NodeHandle n;
    ros::Subscriber sub = n.subscribe("chatter", 1000, chatterCallback);
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
    glutCreateWindow("test");
    glutDisplayFunc(display);
    myinit();
    glutIdleFunc(myidle);
    glutMainLoop();  
    return 0;
}
edit retag flag offensive close merge delete

Comments

especially weird is that it works if I call spinOnce myself the main loop like the below (but then I get no graphics). This looks like some strange internal interaction going on between glut and ROS, can anyone help?

 //  glutMainLoop();      //removed glut control
  while(1)
    ros::spinOnce()
charles.fox gravatar image charles.fox  ( 2018-04-02 07:58:52 -0500 )edit

I'm guessing it's some kind of thread scoping issue, with the glut thread not able to see the same message queue as the main program ... ?

charles.fox gravatar image charles.fox  ( 2018-04-02 08:20:01 -0500 )edit