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 # type: ignore 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(lambda: ser.read(4096), [PROTO], 33 default_channels(ser.write)) 34 35 # Make a shortcut to the EchoService. 36 echo_service = client.rpcs().pw.rpc.EchoService 37 38 # Call some RPCs and check the results. 39 status, payload = echo_service.Echo(msg='Hello') 40 41 if status.ok(): 42 print('The status was', status) 43 print('The payload was', payload) 44 else: 45 print('Uh oh, this RPC returned', status) 46 47 status, payload = echo_service.Echo(msg='Goodbye!') 48 49 print('The device says:', payload.msg) 50 51 52def main(): 53 parser = argparse.ArgumentParser( 54 description=__doc__, 55 formatter_class=argparse.ArgumentDefaultsHelpFormatter) 56 parser.add_argument('--device', 57 '-d', 58 default='/dev/ttyACM0', 59 help='serial device to use') 60 parser.add_argument('--baud', 61 '-b', 62 type=int, 63 default=115200, 64 help='baud rate for the serial device') 65 script(**vars(parser.parse_args())) 66 67 68if __name__ == '__main__': 69 main() 70