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 ( 24 HdlcRpcClient, 25 default_channels, 26 SerialReader, 27) 28 29# Point the script to the .proto file with our RPC services. 30PROTO = Path(os.environ['PW_ROOT'], 'pw_rpc/echo.proto') 31 32 33def script(device: str, baud: int) -> None: 34 # Set up a pw_rpc client that uses HDLC. 35 ser = serial.Serial(device, baud, timeout=0.01) 36 reader = SerialReader(ser, 4096) 37 with reader: 38 client = HdlcRpcClient(reader, [PROTO], default_channels(ser.write)) 39 with client: 40 # Make a shortcut to the EchoService. 41 echo_service = client.rpcs().pw.rpc.EchoService 42 43 # Call some RPCs and check the results. 44 status, payload = echo_service.Echo(msg='Hello') 45 46 if status.ok(): 47 print('The status was', status) 48 print('The payload was', payload) 49 else: 50 print('Uh oh, this RPC returned', status) 51 52 status, payload = echo_service.Echo(msg='Goodbye!') 53 54 print('The device says:', payload.msg) 55 56 57def main(): 58 parser = argparse.ArgumentParser( 59 description=__doc__, 60 formatter_class=argparse.ArgumentDefaultsHelpFormatter, 61 ) 62 parser.add_argument( 63 '--device', '-d', default='/dev/ttyACM0', help='serial device to use' 64 ) 65 parser.add_argument( 66 '--baud', 67 '-b', 68 type=int, 69 default=115200, 70 help='baud rate for the serial device', 71 ) 72 script(**vars(parser.parse_args())) 73 74 75if __name__ == '__main__': 76 main() 77