Services quiz custom message

Hello everyone
I have a easy problem but I don’t know why I can’t fix it, I was trying to solve it for hours.
I want to create a custom message but I can’t run the python file due to the error it show on the line
“from services_quiz.srv import BB8CustomServiceMessage, BB8CustomServiceMessageResponse”
attached is the related part.

#! /usr/bin/env python
import rospy
from services_quiz.srv import BB8CustomServiceMessage, BB8CustomServiceMessageResponse

the error says : "Unable to import ‘services_quiz.srv’ "

but I already defined the package
even when I search the service it shows ---->

user:~/catkin_ws$ rossrv list | grep BB8CustomServiceMessage
services_quiz/BB8CustomServiceMessage

Hi @ptgh

First of all, Make sure that you have Compiled using catkin_make and sourced the work after compilation.

If the error still persist, can you share the following:
1.The BB8CustomServiceMessage.srv file you created
2.The changes made in CMake file
3.The changes made in Package.xml file.
4.Confirm that the package containing the newly created service message and the python file you created are the same.
5. Share the python file you created.

Share the result for the following command (after catkin_make ofcourse)
6. rossrv list | grep BB8
(above command will tell us if the service message is registered with ROS
7. rosservice list | grep

Welcome to the community :grinning:

2 Likes

I compiled it with catkin_make previously but the problem persist.

here is the The BB8CustomServiceMessage.srv file:

float64 side # The distance of each side of the square
int32 repetitions # The number of times BB-8 has to execute the square movement when the service is called

bool success # Did it achieve it?

CMake file:

cmake_minimum_required(VERSION 3.0.2)

project(services_quiz)

find_package(catkin REQUIRED COMPONENTS

rospy

std_msgs

message_generation

roscpp

)

add_service_files(

FILES

BB8CustomServiceMessage.srv

)

generate_messages(

DEPENDENCIES

std_msgs

)

catkin_package(

CATKIN_DEPENDS rospy

)

include_directories(

include

${catkin_INCLUDE_DIRS}

)

Package.xml file:

<?xml version="1.0"?>

services_quiz

0.0.0

The services_quiz package

user

TODO

<buildtool_depend>catkin</buildtool_depend>

<build_depend>rospy</build_depend>

<build_export_depend>rospy</build_export_depend>

<exec_depend>rospy</exec_depend>

<build_depend>message_generation</build_depend>

<build_export_depend>message_runtime</build_export_depend>

<exec_depend>message_runtime</exec_depend>

<!-- Other tools can request additional information be placed here -->

I could not underestand number 4.

Python file:

  1. user:~$ rossrv list | grep BB8
    services_quiz/BB8CustomServiceMessage

thank you for you help.

Hi @ptgh , i will try to go thorugh the data you shared, but can you send the same data again using image from

image

This is used to display the code , instead of opting to copy paste directly which gives code within random fonts and random indents.

Just click on image and then copy the code you want to share in it.
This will make

Look like below, much easier to understand right?

float64 side # The distance of each side of the square
int32 repetitions # The number of times BB-8 has to execute the square movement when the service is called
bool success # Did it achieve it?

Corrections:

From based on what i can see,

  • I think you missed the 3 dashes (no spaces) between request and response, it should look like below:
float64 side # The distance of each side of the square
int32 repetitions # The number of times BB-8 has to execute the square movement when the service is called
---
bool success # Did it achieve it?

Correction in Cmake:
rosccp not required since we are using any C++ files

find_package(catkin REQUIRED COMPONENTS
  std_msgs
  message_generation
)

add message_runtime

catkin_package(
      CATKIN_DEPENDS
      rospy message_runtime
)

Let me know if the changes made any difference

Hey, thank you for your guide,
I made the changes and still same error, I will attach the code and files based on what you mentioned.

float64 side         # The distance of each side of the square
int32 repetitions    # The number of times BB-8 has to execute the square movement when the service is called
---
bool success         # Did it achieve it?

CMake file:

cmake_minimum_required(VERSION 3.0.2)
project(services_quiz)

find_package(catkin REQUIRED COMPONENTS
  rospy
  std_msgs
  message_generation
)

 add_service_files(
   FILES
   BB8CustomServiceMessage.srv
 )

 generate_messages(
   DEPENDENCIES
   std_msgs  
 )

catkin_package(

  CATKIN_DEPENDS 
  rospy message_runtime
)

include_directories(
# include
  ${catkin_INCLUDE_DIRS}
)

## Declare a C++ library
# add_library(${PROJECT_NAME}
#   src/${PROJECT_NAME}/services_quiz.cpp
# )

## Add cmake target dependencies of the library
## as an example, code may need to be generated before libraries
## either from message generation or dynamic reconfigure
# add_dependencies(${PROJECT_NAME} ${${PROJECT_NAME}_EXPORTED_TARGETS} ${catkin_EXPORTED_TARGETS})

## Declare a C++ executable
## With catkin_make all packages are built within a single CMake context
## The recommended prefix ensures that target names across packages don't collide
# add_executable(${PROJECT_NAME}_node src/services_quiz_node.cpp)

## Rename C++ executable without prefix
## The above recommended prefix causes long target names, the following renames the
## target back to the shorter version for ease of user use
## e.g. "rosrun someones_pkg node" instead of "rosrun someones_pkg someones_pkg_node"
# set_target_properties(${PROJECT_NAME}_node PROPERTIES OUTPUT_NAME node PREFIX "")

## Add cmake target dependencies of the executable
## same as for the library above
# add_dependencies(${PROJECT_NAME}_node ${${PROJECT_NAME}_EXPORTED_TARGETS} ${catkin_EXPORTED_TARGETS})

## Specify libraries to link a library or executable target against
# target_link_libraries(${PROJECT_NAME}_node
#   ${catkin_LIBRARIES}
# )

#############
## Install ##
#############

# all install targets should use catkin DESTINATION variables
# See http://ros.org/doc/api/catkin/html/adv_user_guide/variables.html

## Mark executable scripts (Python etc.) for installation
## in contrast to setup.py, you can choose the destination
# catkin_install_python(PROGRAMS
#   scripts/my_python_script
#   DESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION}
# )

## Mark executables for installation
## See http://docs.ros.org/melodic/api/catkin/html/howto/format1/building_executables.html
# install(TARGETS ${PROJECT_NAME}_node
#   RUNTIME DESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION}
# )

## Mark libraries for installation
## See http://docs.ros.org/melodic/api/catkin/html/howto/format1/building_libraries.html
# install(TARGETS ${PROJECT_NAME}
#   ARCHIVE DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION}
#   LIBRARY DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION}
#   RUNTIME DESTINATION ${CATKIN_GLOBAL_BIN_DESTINATION}
# )

## Mark cpp header files for installation
# install(DIRECTORY include/${PROJECT_NAME}/
#   DESTINATION ${CATKIN_PACKAGE_INCLUDE_DESTINATION}
#   FILES_MATCHING PATTERN "*.h"
#   PATTERN ".svn" EXCLUDE
# )

## Mark other files for installation (e.g. launch and bag files, etc.)
# install(FILES
#   # myfile1
#   # myfile2
#   DESTINATION ${CATKIN_PACKAGE_SHARE_DESTINATION}
# )

#############
## Testing ##
#############

## Add gtest based cpp test target and link libraries
# catkin_add_gtest(${PROJECT_NAME}-test test/test_services_quiz.cpp)
# if(TARGET ${PROJECT_NAME}-test)
#   target_link_libraries(${PROJECT_NAME}-test ${PROJECT_NAME})
# endif()

## Add folders to be run by python nosetests
# catkin_add_nosetests(test)


Package.xml file:

<?xml version="1.0"?>
<package format="2">
  <name>services_quiz</name>
  <version>0.0.0</version>
  <description>The services_quiz package</description>

  <!-- One maintainer tag required, multiple allowed, one person per tag -->
  <!-- Example:  -->
  <!-- <maintainer email="jane.doe@example.com">Jane Doe</maintainer> -->
  <maintainer email="user@todo.todo">user</maintainer>


  <!-- One license tag required, multiple allowed, one license per tag -->
  <!-- Commonly used license strings: -->
  <!--   BSD, MIT, Boost Software License, GPLv2, GPLv3, LGPLv2.1, LGPLv3 -->
  <license>TODO</license>


  <!-- Url tags are optional, but multiple are allowed, one per tag -->
  <!-- Optional attribute type can be: website, bugtracker, or repository -->
  <!-- Example: -->
  <!-- <url type="website">http://wiki.ros.org/services_quiz</url> -->


  <!-- Author tags are optional, multiple are allowed, one per tag -->
  <!-- Authors do not have to be maintainers, but could be -->
  <!-- Example: -->
  <!-- <author email="jane.doe@example.com">Jane Doe</author> -->


  <!-- The *depend tags are used to specify dependencies -->
  <!-- Dependencies can be catkin packages or system dependencies -->
  <!-- Examples: -->
  <!-- Use depend as a shortcut for packages that are both build and exec dependencies -->
  <!--   <depend>roscpp</depend> -->
  <!--   Note that this is equivalent to the following: -->
  <!--   <build_depend>roscpp</build_depend> -->
  <!--   <exec_depend>roscpp</exec_depend> -->
  <!-- Use build_depend for packages you need at compile time: -->
  <!--   <build_depend>message_generation</build_depend> -->
  <!-- Use build_export_depend for packages you need in order to build against this package: -->
  <!--   <build_export_depend>message_generation</build_export_depend> -->
  <!-- Use buildtool_depend for build tool packages: -->
  <!--   <buildtool_depend>catkin</buildtool_depend> -->
  <!-- Use exec_depend for packages you need at runtime: -->
  <!--   <exec_depend>message_runtime</exec_depend> -->
  <!-- Use test_depend for packages you need only for testing: -->
  <!--   <test_depend>gtest</test_depend> -->
  <!-- Use doc_depend for packages you need only for building documentation: -->
  <!--   <doc_depend>doxygen</doc_depend> -->
  <buildtool_depend>catkin</buildtool_depend>
  <build_depend>rospy</build_depend>
  <build_export_depend>rospy</build_export_depend>
  <exec_depend>rospy</exec_depend>
  <build_depend>message_generation</build_depend>
  <build_export_depend>message_runtime</build_export_depend>
  <exec_depend>message_runtime</exec_depend>




  <!-- The export tag contains other, unspecified, tags -->
  <export>
    <!-- Other tools can request additional information be placed here -->

  </export>
</package>

the package of python file and the message are the same.
Python file:

#! /usr/bin/env python

import rospy
from services_quiz.srv import BB8CustomServiceMessage, BB8CustomServiceMessageResponse
from geometry_msgs.msg import Twist

def my_callback(request):

    cmd.linear.x = 0.3
    cmd.angular.z = 0.31
    cmd.linear.y = 0.3
    cmd.angular.z = 0.31
    cmd.linear.x = -0.3
    cmd.angular.z = 0.31
    cmd.linear.y = -0.3
    cmd.angular.z = 0.31

    r= 0
    while r <= request.repetitions :
         pub.publish(cmd)
         rate.sleep()
         r=r+1
        
    cmd.linear.x = 0
    cmd.linear.y = 0
    cmd.angular.z = 0
    pub.publish(cmd)
    
    response.success = True
    return response # the service Response class, in this case EmptyResponse

rospy.init_node('service_move_bb8_in_square_custom_server') 
my_service = rospy.Service('/move_bb8_in_square_custom', BB8CustomServiceMessage, my_callback) 
response = BB8CustomServiceMessageResponse()
pub = rospy.Publisher('/cmd_vel', Twist, queue_size=1)
#pub2 = rospy.Publisher('/counter', Int32, queue_size=1)
cmd= Twist()
#count=Int32()
rate = rospy.Rate(5)


$ rossrv list | grep BB8
services_quiz/BB8CustomServiceMessage

thank you in advance.

I tried the content based on the code you provided as is and did not get any errors regarding the service messages.

Most errors happen due to improper compilation,so compile using below cmds.

cd catkin_ws
catkin_make
source devel/setup.bash

during compilation check for any errors in that web shell



Anyways, the error i did see in you code is as follows:

   cmd.linear.x = 0.3
    cmd.angular.z = 0.31
    cmd.linear.y = 0.3
    cmd.angular.z = 0.31
    cmd.linear.x = -0.3
    cmd.angular.z = 0.31
    cmd.linear.y = -0.3
    cmd.angular.z = 0.31

    r= 0
    while r <= request.repetitions :
         pub.publish(cmd)
         rate.sleep()
         r=r+1

You see ,here cmd.linear.x = 0.3, changes to cmd.linear.x = -0.3, the value gets updated to the new value you assigned and 0.3 is ignored. this error is repeated for all the values of x, y and z. You need to publish the values using pub.Publish() else there is nothing happening with the value you assigned.

Also, to move linearly, you only need to make changes in X, and Z is to be used only when you need it to rotate there is no need for Y.

In the case, above, unless you mentioned pub.publish(cmd) every time, only the very last values of x=-0.3 and Z=0.31 will be published. You also need to tell how long you want a command to run using rospy.sleep(time in secs). everytime.

The correct way is as follows:


def my_callback(request):
    print("callback called")
    r=0
    while r <= request.repetitions :
        print("callback called")
        #move forward
        print("moving forward")
        cmd.linear.x=0.2
        cmd.angular.z=0
        pub.publish(cmd)
        rospy.sleep(2)
        #stop
        print("stop")
        cmd.linear.x=0
        cmd.angular.z=0
        pub.publish(cmd)
        rospy.sleep(2)
        #rotate
        print("Rotate")
        cmd.linear.x=0
        cmd.angular.z=0.2
        pub.publish(cmd)
        #modify the time 2 below to till the right angle rotation is achived
        rospy.sleep(2)
        #stop
        print("stop")
        cmd.linear.x=0
        cmd.angular.z=0
        pub.publish(cmd)
        rospy.sleep(2)
        #update r
        r=r+1

    
    response.success = True
    return response # the service Response class, in this case EmptyResponse

PLEASE note that the above code is only to show that the robot can move forward and rotate based on the code and not the complete solution. Since this is a quiz, i can’t reveal everything at the start, but if you are stuck, I will definitely help out.

You still need to modify the code to make the robot rotate at right angle by tweaking the rospy.sleep(modify_value) and modifying the cmd.linear,x value and corresponding rospy.sleep() values to make sure that the distance traveled is based on the side value provided.

The python file

#! /usr/bin/env python

import rospy
from services_quiz.srv import BB8CustomServiceMessage, BB8CustomServiceMessageResponse
from geometry_msgs.msg import Twist

def my_callback(request):
    print("callback called")
    r=0
    while r <= request.repetitions :
        print("callback called")
        #move forward
        print("moving forward")
        cmd.linear.x=0.2
        cmd.angular.z=0
        pub.publish(cmd)
        rospy.sleep(2)
        #stop
        print("stop")
        cmd.linear.x=0
        cmd.angular.z=0
        pub.publish(cmd)
        rospy.sleep(2)
        #rotate
        print("Rotate")
        cmd.linear.x=0
        cmd.angular.z=0.2
        pub.publish(cmd)
        #modify the time 2 below to till the right angle rotation is achived
        rospy.sleep(2)
        #stop
        print("stop")
        cmd.linear.x=0
        cmd.angular.z=0
        pub.publish(cmd)
        rospy.sleep(2)
        #update r
        r=r+1

    
    response.success = True
    return response # the service Response class, in this case EmptyResponse

rospy.init_node('service_move_bb8_in_square_custom_server') 
my_service = rospy.Service('/move_bb8_in_square_custom', BB8CustomServiceMessage, my_callback) 
response = BB8CustomServiceMessageResponse()
pub = rospy.Publisher('/cmd_vel', Twist, queue_size=1)
while pub.get_num_connections()<1:
    pass
#pub2 = rospy.Publisher('/counter', Int32, queue_size=1)
cmd= Twist()
#count=Int32()
rate = rospy.Rate(5)
rospy.spin()


All the other files remain unchanged.

Let me know if this solution worked out, (just in case, why dont you start over with a fresh package, while deleting the previous package in case the error persists)

1 Like

Hey
Many thanks, I changed my program and fixed the issues you mentioned, it is working now.

Glad it was helpful, do reach out in the future :grinning:

(Do mark solution checkbox in this page to close this topics now that we have found the solution)

Hello sir.
I am trying to solve the quiz since many days, yet the service is not starting so that i can call it. My python code is –

#! /usr/bin/env python

import rospy
from services_quiz.srv import BB8CustomServiceMessage, BB8CustomServiceMessageResponse
from geometry_msgs.msg import Twist

def callback (request):
    distance = request.side 
    i=0
    while i< request.repetitions:
        j=0
        while j < 4:
            move.linear.x = 0.3
            move.angular.z = 0.0
            pub.publish(move)
            rospy.sleep(distance)
            move.linear.x = 0.0
            move.angular.z = 0.0
            pub.publish(move)
            rospy.sleep(1)
            move.linear.x = 0.0
            move.angular.z = 0.1
            pub.publish(move)
            rospy.sleep(1.5)
            move.linear.x = 0.0
            move.angular.z = 0.0
            pub.publish(move)
            rospy.sleep(0.5)
            j+=1
        move.linear.x = 0.0
        move.angular.z=0.0
        pub.publish(move)
        i+=1
    move.linear.x=0.0
    move.angular.z=0.0
    pub.publish(move)
    response = BB8CustomServiceMessageResponse()
    response.success = True
    return response

rospy.init_node('services_quiz_node')
move_bb8_in_square_custom = rospy.Service('/move_bb8_in_square_custom',BB8CustomServiceMessage, callback)
pub = rospy.Publisher('/cmd_vel',Twist,queue_size=1)
move=Twist()

I try to run the python file by –

rosrun services_quiz bb8_move_custom_service_server.py

But output is nothing (as shown in screenshot below) –

It would be of great help if you can plz tell where am i going wrong here.

add rospy.spin() at the end of the code. This will keep the program from exiting once it reaches the last line of code. Try this and see if there are any changes.

#! /usr/bin/env python

import rospy
from services_quiz.srv import BB8CustomServiceMessage, BB8CustomServiceMessageResponse
from geometry_msgs.msg import Twist

def callback (request):
    distance = request.side 
    i=0
    while i< request.repetitions:
        j=0
        while j < 4:
            move.linear.x = 0.3
            move.angular.z = 0.0
            pub.publish(move)
            rospy.sleep(distance)
            move.linear.x = 0.0
            move.angular.z = 0.0
            pub.publish(move)
            rospy.sleep(1)
            move.linear.x = 0.0
            move.angular.z = 0.1
            pub.publish(move)
            rospy.sleep(1.5)
            move.linear.x = 0.0
            move.angular.z = 0.0
            pub.publish(move)
            rospy.sleep(0.5)
            j+=1
        move.linear.x = 0.0
        move.angular.z=0.0
        pub.publish(move)
        i+=1
    move.linear.x=0.0
    move.angular.z=0.0
    pub.publish(move)
    response = BB8CustomServiceMessageResponse()
    response.success = True
    return response

rospy.init_node('services_quiz_node')
move_bb8_in_square_custom = rospy.Service('/move_bb8_in_square_custom',BB8CustomServiceMessage, callback)
pub = rospy.Publisher('/cmd_vel',Twist,queue_size=1)
move=Twist()
rospy.spin()

Thank you so much sir !! It worked successfully finally !! Actually I read this statement (screenshot attached) and didn’t write rospy.spin().
tips

I didn’t understand that this tip is for the client file, not server file. Thanks again!

1 Like