First, install gRPC. It seems that Protocol Buffers, which is responsible for serializing RPC, will be installed along with gRPC.
$ curl -fsSL https://goo.gl/getgrpc | bash -s python
If you get the following error during installation, homebrew is out of date and you should try brew update
. (For Mac)
Error: undefined method `desc' for Grpc:Class
Please report this bug:
http://git.io/brew-troubleshooting
/usr/local/Library/Taps/grpc/homebrew-grpc/Formula/grpc.rb:2:in `<class:Grpc>'
・ ・ ・
Write the IDL for Protocol Buffers. The following example defines an RPC that drives the servo.
gRPC itself is a plugin for Protocol Buffers. (There are many [RPC implementations] besides gRPC (https://github.com/google/protobuf/wiki/Third-Party-Add-ons#rpc-implementations))
gateway.proto
syntax = "proto3";
package gateway;
message MoveServoRequest {
int32 servo_id = 1;
int32 position = 2;
}
message MoveServoResponse {
int32 current_position = 1;
}
service AVRGateway {
rpc MoveServo (MoveServoRequest) returns (MoveServoResponse) {}
}
The following protoc
command will generate gateway_pb2.py
.
$ protoc --python_out=. --grpc_out=. --plugin=protoc-gen-grpc=`which grpc_python_plugin` gateway.proto
You can easily write a server / client by importing the Python script generated by the above command. Since the gRPC Python library itself is still Alpha version, various methods are prefixed with early_adopter_ *.
gateway_server.py
import time
import gateway_pb2
class AVRGateway(gateway_pb2.EarlyAdopterAVRGatewayServicer):
def MoveServo(self, request, context):
print 'servo_id: %d, position: %d' % (request.servo_id, request.position)
return gateway_pb2.MoveServoResponse(current_position=150)
def serve():
server = gateway_pb2.early_adopter_create_AVRGateway_server(AVRGateway(), 9494, None, None)
server.start()
try:
while True:
time.sleep(100000)
except KeyboardInterrupt:
server.stop()
if __name__ == '__main__':
serve()
gateway_client.py
import gateway_pb2
def run():
with gateway_pb2.early_adopter_create_AVRGateway_stub('localhost', 9494) as stub:
response = stub.MoveServo(gateway_pb2.MoveServoRequest(servo_id=1, position=200), 10)
print "current position: " + str(response.current_position)
if __name__ == '__main__':
run()
First, start the server.
$ ls
gateway.proto gateway_client.py gateway_pb2.py gateway_server.py
$ python gateway_server.py
And the client in another terminal.
$ python gateway_client.py
current position: 150
D0729 10:42:14.835677000 140735135564544 iomgr.c:119] Waiting for 1 iomgr objects to be destroyed and executing final callbacks
On the server side
$ python gateway_server.py
servo_id: 1, position: 200
If it is output like that, it's OK.
Recommended Posts