lcm实例(Python API)
文件夹结构
./python$ tree -L 1
.
├── cleanup.sh
├── example_t.lcm
├── gen-types.sh
├── listener.py
├── listener_select.py
├── read-log.py
├── readme.md
└── send-message.py
0 directories, 8 files
-
1.文件example_t.lcm
内容:
package exlcm;
struct example_t
{
int64_t timestamp;
double position[3];
double orientation[4];
int32_t num_ranges;
int16_t ranges[num_ranges];
string name;
boolean enabled;
}
-
lcm-gen -p example_t.lcm
在命令行中执行以下命令生成lcm格式python文件:
# 此处-p是指python
lcm-gen -p example_t.lcm
生成的文件在exlcm/example_t.py
├── example_t.lcm
├── exlcm
│ ├── example_t.py
│ └── __init__.py
-
2. 文件test_publish.py
import lcm
from exlcm import example_t
msg = example_t()
msg.timestamp = 0
msg.position = (1, 2, 3)
msg.orientation = (1, 0, 0, 0)
msg.ranges = range(15)
msg.num_ranges = len(msg.ranges)
msg.name = "example string"
msg.enabled = True
lc = lcm.LCM()
while True:
lc.publish("EXAMPLE", msg.encode())
3. 文件 test_subscribe.py
import lcm
from exlcm import example_t
def my_handler(channel, data):
msg = example_t.decode(data)
print("Received message on channel \"%s\"" % channel)
print(" timestamp = %s" % str(msg.timestamp))
print(" position = %s" % str(msg.position))
print(" orientation = %s" % str(msg.orientation))
print(" ranges: %s" % str(msg.ranges))
print(" name = '%s'" % msg.name)
print(" enabled = %s" % str(msg.enabled))
print("")
lc = lcm.LCM()
subscription = lc.subscribe("EXAMPLE", my_handler)
try:
while True:
lc.handle()
except KeyboardInterrupt:
pass
-
测试
在命令行中测试:python test_publish.py [send-message.py]新开一个命令行窗口输入python test_subscribe.py, [listener.py ]输出结果如下:
Received message on channel "EXAMPLE"
timestamp = 0
position = (1.0, 2.0, 3.0)
orientation = (1.0, 0.0, 0.0, 0.0)
ranges: (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14)
name = 'example string'
enabled = True