Attenuator.py 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. # SPDX-FileCopyrightText: 2015-2022 Espressif Systems (Shanghai) CO LTD
  2. # SPDX-License-Identifier: Apache-2.0
  3. """
  4. Internal use only.
  5. This file provide method to control programmable attenuator.
  6. """
  7. import codecs
  8. import time
  9. import serial
  10. def set_att(port, att, att_fix=False):
  11. """
  12. set attenuation value on the attenuator
  13. :param port: serial port for attenuator
  14. :param att: attenuation value we want to set
  15. :param att_fix: fix the deviation with experience value
  16. :return: True or False
  17. """
  18. assert 0 <= att <= 62
  19. # fix att
  20. if att_fix:
  21. if att >= 33 and (att - 30 + 1) % 4 == 0:
  22. att_t = att - 1
  23. elif att >= 33 and (att - 30) % 4 == 0:
  24. att_t = att + 1
  25. else:
  26. att_t = att
  27. else:
  28. att_t = att
  29. serial_port = serial.Serial(port, baudrate=9600, rtscts=False, timeout=0.1)
  30. if serial_port.isOpen() is False:
  31. raise IOError('attenuator control, failed to open att port')
  32. cmd_hex = '7e7e10{:02x}{:x}'.format(att_t, 0x10 + att_t)
  33. exp_res_hex = '7e7e20{:02x}00{:x}'.format(att_t, 0x20 + att_t)
  34. cmd = codecs.decode(cmd_hex, 'hex')
  35. exp_res = codecs.decode(exp_res_hex, 'hex')
  36. serial_port.write(cmd)
  37. res = b''
  38. for i in range(5):
  39. res += serial_port.read(20)
  40. if res == exp_res:
  41. result = True
  42. break
  43. time.sleep(0.1)
  44. else:
  45. result = False
  46. serial_port.close()
  47. return result