1#!/usr/bin/env python 2# Copyright 2020 The Pigweed Authors 3# 4# Licensed under the Apache License, Version 2.0 (the "License"); you may not 5# use this file except in compliance with the License. You may obtain a copy of 6# the License at 7# 8# https://www.apache.org/licenses/LICENSE-2.0 9# 10# Unless required by applicable law or agreed to in writing, software 11# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13# License for the specific language governing permissions and limitations under 14# the License. 15"""Simple example script that uses pw_rpc.""" 16 17import argparse 18import os 19from pathlib import Path 20 21import serial 22 23from pw_hdlc.rpc import HdlcRpcClient, default_channels 24 25# Point the script to the .proto file with our RPC services. 26PROTO = Path(os.environ['PW_ROOT'], 'pw_rpc/echo.proto') 27 28 29def script(device: str, baud: int) -> None: 30 # Set up a pw_rpc client that uses HDLC. 31 ser = serial.Serial(device, baud, timeout=0.01) 32 client = HdlcRpcClient( 33 lambda: ser.read(4096), [PROTO], default_channels(ser.write) 34 ) 35 36 # Make a shortcut to the EchoService. 37 echo_service = client.rpcs().pw.rpc.EchoService 38 39 # Call some RPCs and check the results. 40 status, payload = echo_service.Echo(msg='Hello') 41 42 if status.ok(): 43 print('The status was', status) 44 print('The payload was', payload) 45 else: 46 print('Uh oh, this RPC returned', status) 47 48 status, payload = echo_service.Echo(msg='Goodbye!') 49 50 print('The device says:', payload.msg) 51 52 53def main(): 54 parser = argparse.ArgumentParser( 55 description=__doc__, 56 formatter_class=argparse.ArgumentDefaultsHelpFormatter, 57 ) 58 parser.add_argument( 59 '--device', '-d', default='/dev/ttyACM0', help='serial device to use' 60 ) 61 parser.add_argument( 62 '--baud', 63 '-b', 64 type=int, 65 default=115200, 66 help='baud rate for the serial device', 67 ) 68 script(**vars(parser.parse_args())) 69 70 71if __name__ == '__main__': 72 main() 73