うごくものづくりのために

技術的な備忘録がメインです。

PythonとGoogleProtocolBuffersを用いてgrSimのデータを取得する

GoogleProtocolBuffers for Pythonのインストール

grSimをインストールした時 にダウンロードした GoogleProtocolBuffers のフォルダ内に、Python用セットアップファイルが同梱されているので、それを用いてインストールします。

まずは、このフォルダに移動。 今回は、Downloadsフォルダ内に解凍しているので、以下のパスとなっています。 適宜変えてください。

cd ~/Downloads/protobuf-2.5.0/python/

このフォルダ内にあるreadme.txtを参考にしながら、インストールを進めていきます。

python setup.py build
python setup.py test #このテストを全部通らないとまずい

python setup.py install #自分はsudoで実行する必要がありました

grSimのprotoファイルをPythonコンパイル

まずは、適当に作業フォルダを作ります。

mkdir -p ~/Documents/SSL_develop/temp_proto/
cd ~/Documents/SSL_develop/temp_proto/

grSimが通信に用いるprotoファイルは、grSim/src/proto/ 内にあります。

このファイルたちを作業フォルダへとコピーします。

cp -r ~/Documents/SSL_develop/grSim/src/proto ./proto
ls ./proto

そのうち、 messages_robocup_ssl_*** というファイルが、grSimが吐き出すシミュレータデータのprotoファイルですので、それらをprotocコンパイラPythonへと変換します。

protoc -I=./proto --python_out=./ ./proto/messages_robocup_ssl_detection.proto
protoc -I=./proto --python_out=./ ./proto/messages_robocup_ssl_geometry.proto
protoc -I=./proto --python_out=./ ./proto/messages_robocup_ssl_refbox_log.proto
protoc -I=./proto --python_out=./ ./proto/messages_robocup_ssl_wrapper.proto
ls

これで、messages_robocup_ssl***pb2.pyというファイルが4つできていれば成功です。

grSimのデータを取得

以下のページに、GoogleProtocolBuffersの使い方がまとまっています。 このページの下の方にある、"Reading A Message"というサンプルコードを参考に、 昨日書いたマルチキャストのソースコードを改造していきます。

Protocol Buffer Basics: Python - Protocol Buffers — Google Developers

#!/usr/bin/env python

import  socket
import  messages_robocup_ssl_wrapper_pb2

multicast_if_addr='192.168.0.10'  

multicast_group='224.5.23.2'
multicast_port=10020

my_addr='0.0.0.0'
server_address=(my_addr, multicast_port)

sock=socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind(server_address)

mreq=socket.inet_aton(multicast_group)+socket.inet_aton(multicast_if_addr)
sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)

#make protobuf instance
ssl_wrapper = messages_robocup_ssl_wrapper_pb2.SSL_WrapperPacket()

while True:

    data    = sock.recv(1024)
    ssl_wrapper.ParseFromString(data)
    
    print   '-------------------------------------------'
    print   ssl_wrapper

あとは、grSimを起動したあとに、このコードを実行!

f:id:tilt_silvie:20140927151417p:plain

座標データやらなんやら取得できたーっ!