文件夾結構
.
├── example_t.lcm
├── exlcm
│ ├── example_t.py
│ ├── __init__.py
│ └── __pycache__
│ ├── example_t.cpython-36.pyc
│ └── __init__.cpython-36.pyc
├── test_publish.py
└── test_subscribe.py
2 directories, 7 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格式python文件:
# 此處-p是指python
lcm-gen -p example_t.lcm
生成的文件在exlcm/example_t.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
新開一個命令行窗口輸入python test_subscribe.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