controlarduino.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. #!/usr/bin/python3 -u
  2. #
  3. import serial
  4. import sys
  5. import argparse
  6. from datetime import datetime
  7. serialPort='/dev/serial/by-id/usb-Prolific_Technology_Inc._USB-Serial_Controller-if00-port0'
  8. serialBaud=57600
  9. serialTimeout=1
  10. doReset = False
  11. enableMonitor = False
  12. ser = serial.Serial(port=serialPort,
  13. baudrate = serialBaud,
  14. parity=serial.PARITY_NONE,
  15. stopbits=serial.STOPBITS_ONE,
  16. bytesize=serial.EIGHTBITS,
  17. timeout=serialTimeout)
  18. parser = argparse.ArgumentParser()
  19. parser.add_argument('--reset',
  20. help='reset board via serial command, parameter is timeout in ms to reset.')
  21. parser.add_argument('--monitor', default=False,
  22. help='Monitor serial output.', action='store_true')
  23. parser.add_argument('--addts', default=False,
  24. help='Add timestamp to monitor output.', action='store_true')
  25. args = parser.parse_args()
  26. if args.reset:
  27. if int(args.reset) >= 1:
  28. doReset = True
  29. delayTime = args.reset
  30. if doReset:
  31. cmdStr = 'reset ' + str(delayTime) + '\n'
  32. #print('cmd: >' + cmdStr + '<')
  33. cmdStr = cmdStr.encode('utf-8')
  34. ser.write(cmdStr)
  35. if args.monitor:
  36. while True:
  37. #ser.flushInput()
  38. #read buffer until cr/lf
  39. serLine = ser.readline().strip()
  40. # catch exception on invalid char coming in: UnicodeDecodeError: 'ascii' codec can't decode byte 0xf4 in position 6: ordinal not in range(128)
  41. try:
  42. serLine = serLine.decode('ascii')
  43. except:
  44. serLine = ""
  45. if(serLine):
  46. if args.addts:
  47. #print (datetime.now().isoformat(), serLine) #Echo the serial buffer bytes up to the CRLF back to screen
  48. print ("[" + str(datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]) + "]:", serLine)
  49. else:
  50. print (serLine) #Echo the serial buffer bytes up to the CRLF back to screen