1#!/usr/bin/env python3

2# Copyright 2018 Canonical Ltd.

3# All rights reserved.

4#

5# Written by:

6# Vinay Simha BN <vinaysimha@inforcecomputing.com>

7# Jonathan Cave <jonathan.cave@canonical.com>

8

9 import argparse

10

11 import serial

12

13

14 def main():

15 parser = argparse.ArgumentParser()

16 parser.add_argument("device", help="Serial port device e.g. /dev/ttyS1")

17 parser.add_argument("--baudrate", default=115200, type=int)

18 parser.add_argument(

19 "--bytesize",

20 choices=[5, 6, 7, 8],

21 type=int,

22 help="set bytesize, one of {5, 6, 7, 8}, default: 8",

23 default=8,

24 )

25 parser.add_argument(

26 "--parity",

27 choices=["N", "E", "O", "S", "M"],

28 type=lambda c: c.upper(),

29 help="set parity, one of {N E O S M}, default: N",

30 default="N",

31 )

32 parser.add_argument(

33 "--stopbits",

34 choices=[1, 2],

35 type=int,

36 help="set stopbits, one of {1, 2}, default: 1",

37 default=1,

38 )

39 args = parser.parse_args()

40 print("Test parameters:", vars(args))

41 with serial.Serial(

42 args.device,

43 baudrate=args.baudrate,

44 bytesize=args.bytesize,

45 parity=args.parity,

46 stopbits=args.stopbits,

47 timeout=1,

48 ) as ser:

49 test_str = "loopback\n"

50 ser.write(test_str.encode("UTF-8"))

51 rcv = ser.readline().decode("UTF-8")

52 print("Sent:", repr(test_str))

53 print("Received:", repr(rcv))

54 if rcv != test_str:

55 raise SystemExit("SERIAL LOOPBACK TEST FAILED")

56 print("SERIAL LOOPBACK TEST PASSED")

57

58

59 if __name__ == "__main__":

60 main()