b8b2b0fbdf65bd4d1b1dc97354d11062db3f4d78
[platform/upstream/connectedhomeip.git] / third_party / pigweed / repo / pw_hdlc_lite / rpc_example / example_script.py
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
17 import argparse
18 import os
19 from pathlib import Path
20
21 import serial
22
23 from pw_hdlc_lite.rpc import HdlcRpcClient
24
25 # Point the script to the .proto file with our RPC services.
26 PROTO = Path(os.environ['PW_ROOT'], 'pw_rpc/pw_rpc_protos/echo.proto')
27
28
29 def script(device: str, baud: int) -> None:
30     # Set up a pw_rpc client that uses HDLC.
31     client = HdlcRpcClient(serial.Serial(device, baud), [PROTO])
32
33     # Make a shortcut to the EchoService.
34     echo_service = client.rpcs().pw.rpc.EchoService
35
36     # Call some RPCs and check the results.
37     status, payload = echo_service.Echo(msg='Hello')
38
39     if status.ok():
40         print('The status was', status)
41         print('The payload was', payload)
42     else:
43         print('Uh oh, this RPC returned', status)
44
45     status, payload = echo_service.Echo(msg='Goodbye!')
46
47     print('The device says:', payload.msg)
48
49
50 def main():
51     parser = argparse.ArgumentParser(
52         description=__doc__,
53         formatter_class=argparse.ArgumentDefaultsHelpFormatter)
54     parser.add_argument('--device',
55                         '-d',
56                         default='/dev/ttyACM0',
57                         help='serial device to use')
58     parser.add_argument('--baud',
59                         '-b',
60                         type=int,
61                         default=115200,
62                         help='baud rate for the serial device')
63     script(**vars(parser.parse_args()))
64
65
66 if __name__ == '__main__':
67     main()