jpieper / pygazebo Goto Github PK
View Code? Open in Web Editor NEWPython bindings for the Gazebo multi-robot simulator.
License: Other
Python bindings for the Gazebo multi-robot simulator.
License: Other
I just want to know if this library still functions for Gazebo 4.1 and other recent versions.
There are some messages that are super useful which are sent to debug level, but a lot of things that are 'trace' level which aren't really useful to anyone (like connection.read_raw, read).
I came across this problem which I really don't know how to tackle it:
If when we are connected to gzserver , thisone falls, how could we detect that and start to reconnect to it once gzserver starts again?
Hi, how did you addressed the issue of pygazebo/msg/
generated python files that are not importing each other with relative import?
Your makefile doesn't seem to address this issue
-l
I want to use pygazebo to subscribe to images published by a gazebo plugin.
I found out that pygazebo does not respond to large messages.
The problem becomes visible when the message size is above 40.. 50 kB.
Below are two small programs that demonstrate the issue:
Run the subscriber (sub.py) in one terminal, and the publisher (pub.py) in another.
$ python sub.py
$ python pub.py 10 50000
The subscriber (sub.py):
from pygazebo.msg.gz_string_pb2 import GzString
import eventlet
def callback(data):
message = GzString.FromString(data)
print 'got message %s' % message.data[:4]
topic='/gazebo/default/test/request'
manager = pygazebo.Manager(('localhost', 11345))
sub = manager.subscribe(topic, 'gazebo.msgs.GzString', callback)
while True:
eventlet.sleep(1)
And the publisher (pub.py):
import pygazebo
import sys
from pygazebo.msg.gz_string_pb2 import GzString
import time
n = 10
size = 1000
if len(sys.argv) > 2:
n,size = map(int, sys.argv[1:3])
manager = pygazebo.Manager(('localhost', 11345))
topic = '/gazebo/default/test/request'
publisher = manager.advertise(topic, 'gazebo.msgs.GzString')
publisher.wait_for_listener()
for i in range(n):
msg = GzString(data='%4d' % i + ' '*(size-4))
publisher.publish(msg)
time.sleep(0.2)
I'm having a bit of trouble following the logic, but basically in pygazebo.py at _Connection::handle_read_raw_header()
, if the result is an empty string/byte array, then that means the connection has disconnected. At the moment, it just shows up as a ParseError, which is confusing to the user.
At the moment I'm changing it to a DisconnectError, but I'm not convinced this is the right solution either -- but at least what happened was clearer.
Hello there,
I apologize in advance because I'm new to asynchronous programming with python and I'm afraid I'm doing things the wrong way. I was trying to follow the usage example here:
http://pygazebo.readthedocs.org/en/latest/usage.html
and the closest thing I got to is something like this:
@trollius.coroutine
def main():
manager = yield From(pygazebo.connect())
publisher = yield From(
manager.advertise('/gazebo/default/topic',
'gazebo.msgs.GzString'))
yield From(trollius.sleep(1))
manager.start()
manager.subscribe('/gazebo/default/topic',
'gazebo.msgs.GzString',
callback)
for i in xrange(5):
yield From(publisher.publish(
pygazebo.msg.gz_string_pb2.GzString(data='heloooo')))
yield From(trollius.sleep(1))
# logging.basicConfig(level=logging.ERROR)
loop = trollius.get_event_loop()
loop.run_until_complete(main())
Can someone provide a complete sample example?
PS: How about creating a chat room for this project at https://gitter.im ? it will be useful for the community.
Hi,
I'm executing the example of use in given where you publish in "/gazebo/default/model/joint_cmd".
It connects because when launched gzserver, if we do gztopic list , that topic gets listed. But when echoing that topic, there is nothing to be seen.
Does someone know what's happening?
import trollius
from trollius import From
import pygazebo
import pygazebo.msg.world_stats_pb2
@trollius.coroutine
def publish_loop():
manager = yield From(pygazebo.connect())
print("hello")
@trollius.coroutine
def callback2(data):
print(data)
message = pygazebo.msg.world_stats_pb2.WorldStatistics.ParseFromString(data)
print(message)
subscriber = manager.subscribe('/gazebo/world/world_stats',
'gazebo.msgs.WorldStatistics',
callback2)
subscriber.wait_for_connection()
while(True):
trollius.sleep(1)
loop = trollius.get_event_loop()
loop.run_until_complete(publish_loop())
I wanted to test some basic subscribers. I have been using publishers for two weeks or so and have gotten them working quite well. However, I cannot seem to get subscribers working at all. What am I doing wrong? Before you ask, my SDF has the default_world as world. I have checked and the topic '/gazebo/world/world_stats/' does actually have subscribers according to the gz tool. Unfortunately, no matter how hard I try, I can not get the python to run the callback2 at all. Even if I just have hello world, nothing happens. What am I doing wrong? Is there a bug in the current develop branch?
Hey all, happy holidays :)
I have a question which I'm not sure if this is the right place to ask about (if not, I'm sorry in advance).
In Gazebo, I have 2 boxes and a sphere that I'm controlling using a joystick and a point light. Also I have a subscriber to /gazebo/default/physics/contacts
. In the callback I'm checking for physical contacts between the controlled sphere and one of the boxes, and when a collision happens, the point light turns on. Everything works fine except there is a ~2 seconds delay from when the collision happens till the light is turned on.
I think the reason for this delay is the amount of data sent from the topic (it was around ~30KB/s) which takes a while for the script to find the correct collision and respond by turning the point light.
So my question is, is there a better way to respond to events in pygazebo? (I'm not interested in all the collisions in my example, I just want one specific collision) or am I doing something totally wrong? (which is very plausible).
I'm using Gazebo 4.0 and pygazebo from the development branch.
Here is the callback:
def contacts_callback(data):
message = pygazebo.msg.contacts_pb2.Contacts.FromString(data)
if message.contact:
for contact in message.contact:
col2 = contact.collision2.split("::")[0]
if col2 == "unit_box_1":
turn_light_on()
elif col2 == "unit_box_2":
turn_light_off()
Thanks!
If you attempt to publish a malformed gazebo message, you get only a deferred debug level logging message telling you about it.
Why and how to handle this? I realy don't know why this happens and what could be done to solve this?
ERROR:trollius:Exception in callback (<Future ...tError()>) at /home/ubuntu/pygazebo/pygazebo/pygazebo.py:659
handle: <Handle (<Future ...tError()>) at /home/ubuntu/pygazebo/pygazebo/pygazebo.py:659>
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/trollius-1.0.4-py2.7.egg/trollius/events.py", line 151, in _run
self._callback(*self._args)
File "/home/ubuntu/pygazebo/pygazebo/pygazebo.py", line 659, in
lambda future: self._handle_server_data(future, connection))
File "/home/ubuntu/pygazebo/pygazebo/pygazebo.py", line 662, in _handle_server_data
message = future.result()
File "/usr/local/lib/python2.7/dist-packages/trollius-1.0.4-py2.7.egg/trollius/futures.py", line 287, in result
raise self._exception
DisconnectError
Does someone know how to access all the data in the "pygazebo.msg.response_pb2", is because when accessing the
response = pygazebo.msg.response_pb2.Response.FromString(data)
print "serialized_data Data ==>", response.serialized_data.name
It return nothing and when using "response.serialized_data" the data is not correctly formatted.
this is what the c version of the code does (and works)
`#include <gazebo/gazebo_config.h>
#include <gazebo/transport/transport.hh>
#include <gazebo/msgs/msgs.hh>
// Gazebo's API has changed between major releases. These changes are
// accounted for with #if..#endif blocks in this file.
#if GAZEBO_MAJOR_VERSION < 6
#include <gazebo/gazebo.hh>
#else
#include <gazebo/gazebo_client.hh>
#endif
/////////////////////////////////////////////////
int main(int _argc, char **_argv)
{
// Load gazebo as a client
#if GAZEBO_MAJOR_VERSION < 6
gazebo::setupClient(_argc, _argv);
#else
gazebo::client::setup(_argc, _argv);
#endif
// Create our node for communication
gazebo::transport::NodePtr node(new gazebo::transport::Node());
node->Init();
// Publish to the velodyne topic
gazebo::transport::PublisherPtr pub =
node->Advertisegazebo::msgs::Vector3d("~/my_velodyne/vel_cmd");
// Wait for a subscriber to connect to this publisher
pub->WaitForConnection();
// Create a a vector3 message
gazebo::msgs::Vector3d msg;
// Set the velocity in the x-component
#if GAZEBO_MAJOR_VERSION < 6
gazebo::msgs::Set(&msg, gazebo::math::Vector3(std::atof(_argv[1]), 0, 0));
#else
gazebo::msgs::Set(&msg, ignition::math::Vector3d(std::atof(_argv[1]), 0, 0));
#endif
// Send the message
pub->Publish(msg);
// Make sure to shut everything down.
#if GAZEBO_MAJOR_VERSION < 6
gazebo::shutdown();
#else
gazebo::client::shutdown();
#endif
}`
I am trying to replicate it by using pygazebo. This is what I have:
`import trollius
from trollius import From
import pygazebo
import pygazebo.msg.vector3d_pb2
@trollius.coroutine
def publish_loop():
manager = yield From(pygazebo.connect(('localhost', 11345)))
publisher = yield From(manager.advertise('~/my_velodyne/vel_cmd','gazebo.msgs.vel_cmd'))
message = pygazebo.msg.vector3d_pb2.Vector3d()
message.z = -100
message.x = 200
message.y = 300
while True:
yield From(publisher.publish(message))
yield From(trollius.sleep(1.0))
loop = trollius.get_event_loop()
loop.run_until_complete(publish_loop())
`
It runs without errors, but gazebo is unaffected. Any ideas?
I really love this repository, but the documentation and examples are lacking. I would really appreciate some further example particularly to help people who have no experience with Trollius like myself.
I intend to adapt pygazebo so it can be used successfully on python 3.x -- I don't expect many problems, except that protobuf 2.6 isn't quite py3 compatible yet (see protocolbuffers/protobuf#7), but it looks like that will change very very soon.
I'll try to link my PR's to this bug until all the issues are resolved.
The code in README files is incorrect.
By using $ [sudo] pip install pygazebo
and then running the sample code, the following error is reported:
pygazebo not found
Correct, since only Manager is being imported
Manager has no connections
Again, no port is being provided
The code used was picked up from branch Master
I'm having some issues with wait for conection
I'm connecting to various topics as subscriber and publisher
It sometimes word sometimes doesnt. The only error that I get is this:
WARNING:pygazebo.pygazebo:unhandled message type: topic_namespace_add
Any ideas?
Hello there,
This might be a stupid question but I'm new to gazebo and I was following the "how to write a plugin" tutorial and I'm wondering if I can use pygazebo to write a plugin?
Cheers!
So I am wrote a program to apply some joint PIDs when the server start. However, it only works when I put .sleep between successive Trollius calls and when I put Trollius sleep of .1 BEFORE the first publisher.message. Any idea why this works only in this configuration? I would like to note that it also works if you shove everything into one giant event loop, but otherwise it does not work. Any idea what could be causing it? I fear it might be a race condition on Trollius
Here is the code:
# -*- coding: utf-8 -*-
"""
Created on Tue Jul 14 13:27:48 2015
@author: skylion
"""
import trollius #NOTE: Trollius requires protobuffer from Google
from trollius import From
import pygazebo
import pygazebo.msg.joint_cmd_pb2
import time
import popupcad
from lxml import etree
import subprocess
import os
try:
import itertools.izip as zip
except ImportError:
pass
def apply_joint_pos(world_name, robot_name, joint_names, poses, duration=0):
wait_net_service('localhost', 11345)
time.sleep(1.0)
print("Net serviced detected. Proceeding")
@trollius.coroutine
def joint_pose_loop(world_name, robot_name, joint_name, pose, duration):
manager = yield From(pygazebo.connect())
print("connected")
publisher = yield From(
manager.advertise('/gazebo/' + world_name + '/' + robot_name + '/joint_cmd',
'gazebo.msgs.JointCmd'))
message = pygazebo.msg.joint_cmd_pb2.JointCmd()
message.name = robot_name + '::' + joint_name #format should be: name_of_robot + '::name_of_joint'
print(message.position.target)
message.position.target = pose
print(message.position.target)
# message.force = pose
try:
yield From(trollius.sleep(0.1))
yield From(publisher.publish(message))
except :
print("ugh oh")
pass
print("Connection closed")
def loop_in_thread(loop, tasks):
trollius.set_event_loop(loop)
loop.run_until_complete(trollius.wait(tasks))
tasks = []
for joint_name, pose in zip(joint_names, poses):
tasks.append(trollius.Task(joint_pose_loop(world_name, robot_name, joint_name, pose, duration)))
loop = trollius.get_event_loop()
loop.run_until_complete(trollius.wait(tasks))
#TODO either integrate with PyGazebo or clean up, maybe with sub processes
#This is a Sandbox Nightmare. Poor Coding practices
def wait_net_service(server, port, timeout=None):
""" Wait for network service to appear
@param timeout: in seconds, if None or 0 wait forever
@return: True of False, if timeout is None may return only True or
throw unhandled network exception
"""
import socket
import errno
s = socket.socket()
if timeout:
from time import time as now
# time module is needed to calc timeout shared between two exceptions
end = now() + timeout
while True:
try:
if timeout:
next_timeout = end - now()
if next_timeout < 0:
return False
else:
s.settimeout(next_timeout)
s.connect((server, port))
except socket.timeout as err:
# this exception occurs only if timeout is set
if timeout:
return False
except socket.error as err:
# catch timeout exception from underlying network library
# this one is different from socket.timeout
if type(err.args) != tuple or (err[0] != errno.ETIMEDOUT and err[0] != errno.ECONNREFUSED):
raise err
else:
s.close()
return True
world_name='world'
robot_name='default_body'
joint_names=['hingejoint0', 'hingejoint1', 'hingejoint2', 'hingejoint3', 'hingejoint4', 'hingejoint5', 'hingejoint6', 'hingejoint7', 'hingejoint8']
apply_joint_pos(world_name, robot_name,['hingejoint1'], [9])
apply_joint_pos(world_name, robot_name,['hingejoint2'], [-9])
apply_joint_pos(world_name, robot_name,['hingejoint3'], [-7])
apply_joint_pos(world_name, robot_name,['hingejoint4','hingejoint5'], [-10,-10])
apply_joint_pos(world_name, robot_name,['hingejoint0'], [-21])
apply_joint_pos(world_name, robot_name,['hingejoint4','hingejoint5'], [-15,-15])
apply_joint_pos(world_name, robot_name,['hingejoint3'], [-12])
Hi,
I have two python programs. One is listening all the time while the other only executes in certain moments to publish something in a topic and shutdown when finished.
My question is: Why could it give this error?
ERROR:trollius:Exception in callback (<Future ...50952)")>) at /usr/local/lib/python2.7/dist-packages/pygazebo-3.0.0_2014.1-py2.7.egg/pygazebo/pygazebo.py:171
handle: <Handle (<Future ...50952)")>) at /usr/local/lib/python2.7/dist-packages/pygazebo-3.0.0_2014.1-py2.7.egg/pygazebo/pygazebo.py:171>
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/trollius-1.0.4-py2.7.egg/trollius/events.py", line 151, in _run
self._callback(*self._args)
File "/usr/local/lib/python2.7/dist-packages/pygazebo-3.0.0_2014.1-py2.7.egg/pygazebo/pygazebo.py", line 171, in
lambda future: self._connect2(future, connection, pub))
File "/usr/local/lib/python2.7/dist-packages/pygazebo-3.0.0_2014.1-py2.7.egg/pygazebo/pygazebo.py", line 174, in _connect2
future.result() # Check for error
File "/usr/local/lib/python2.7/dist-packages/trollius-1.0.4-py2.7.egg/trollius/futures.py", line 287, in result
raise self._exception
ConnectionRefusedError: [Errno 111] Connect call failed (u'0.0.0.0', 50952)
It sems as if the conexion from the first program gets severed and it cant connect anymore
Any ideas?
Got this message when subscribing to a topic.
When activated logger, gives error:
ERROR:trollius:Exception in callback (<Future ...00\xf0?'>) at /usr/local/lib/python2.7/dist-packages/pygazebo-3.0.0_2014.1-py2.7.egg/pygazebo/pygazebo.py:198
handle: <Handle (<Future ...00\xf0?'>) at /usr/local/lib/python2.7/dist-packages/pygazebo-3.0.0_2014.1-py2.7.egg/pygazebo/pygazebo.py:198>
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/trollius-1.0.4-py2.7.egg/trollius/events.py", line 151, in _run
self._callback(*self._args)
File "/usr/local/lib/python2.7/dist-packages/pygazebo-3.0.0_2014.1-py2.7.egg/pygazebo/pygazebo.py", line 198, in
lambda future: self._handle_read(future, connection))
File "/usr/local/lib/python2.7/dist-packages/pygazebo-3.0.0_2014.1-py2.7.egg/pygazebo/pygazebo.py", line 209, in _handle_read
self._connect3(connection)
TypeError: _connect3() takes exactly 3 arguments (2 given)
The code is:
"""
import trollius
from trollius import From
import pygazebo
import pygazebo.msg.response_pb2
import logging
logging.basicConfig()
RESPONSE_TOPIC_NAME = '/gazebo/default/response'
RESPONSE_TOPIC_MSG_TYPE = 'gazebo.msgs.Response'
def callback(data):
response = pygazebo.msg.response_pb2.Response()
if not data:
print "No Data..."
else:
response.ParseFromString(data)
print "Response ==>", response.response
print "Response ==>", response.request
@trollius.coroutine
def listen_topics_loop():
manager = yield From(pygazebo.connect())
subscriber = manager.subscribe( RESPONSE_TOPIC_NAME,
RESPONSE_TOPIC_MSG_TYPE,
callback)
while True:
#print "Listening"
yield From(trollius.sleep(2.0))
def request_and_listen():
loop = trollius.get_event_loop()
loop.run_until_complete(listen_topics_loop())
if name == "main":
request_and_listen()
"""
I am using the develop branch and I'm trying to get the range values from a laser scanner sensor in Gazebo 2.3. The laser is defined in my model SDF using the libgazebo_ros_laser.so plugin and the scan appears fine in the Gazebo GUI as well as in the Topic Visualization.
When I run the following code, the range array always appears empty (prints out as []) whereas I expected to see the actual ranges. The header and scan fields of the message print fine so I know the callback is receiving the messages.
Here now is the code:
import trollius
from trollius import From
import pygazebo
import pygazebo.msg.laserscan_stamped_pb2
@trollius.coroutine
def publish_loop():
manager = yield From(pygazebo.connect())
def callback_lidar(data):
message = pygazebo.msg.laserscan_stamped_pb2.LaserScanStamped.FromString(data)
print message.scan.ranges
subscriber = manager.subscribe('/gazebo/default/person_walking_lidar/lidar_link/laser/scan',
'gazebo.msgs.LaserScanStamped',
callback_lidar)
yield From(subscriber.wait_for_connection())
while(True):
yield From(trollius.sleep(0.1))
print('wait...')
print(dir(manager))
import logging
logging.basicConfig()
loop = trollius.get_event_loop()
loop.run_until_complete(publish_loop())
Is there a way of using it with Gazebo 1.9?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.