Attenuator.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. # Copyright 2015-2017 Espressif Systems (Shanghai) PTE LTD
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http:#www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. """
  15. Internal use only.
  16. This file provide method to control programmable attenuator.
  17. """
  18. import codecs
  19. import time
  20. import serial
  21. def set_att(port, att, att_fix=False):
  22. """
  23. set attenuation value on the attenuator
  24. :param port: serial port for attenuator
  25. :param att: attenuation value we want to set
  26. :param att_fix: fix the deviation with experience value
  27. :return: True or False
  28. """
  29. assert 0 <= att <= 62
  30. # fix att
  31. if att_fix:
  32. if att >= 33 and (att - 30 + 1) % 4 == 0:
  33. att_t = att - 1
  34. elif att >= 33 and (att - 30) % 4 == 0:
  35. att_t = att + 1
  36. else:
  37. att_t = att
  38. else:
  39. att_t = att
  40. serial_port = serial.Serial(port, baudrate=9600, rtscts=False, timeout=0.1)
  41. if serial_port.isOpen() is False:
  42. raise IOError('attenuator control, failed to open att port')
  43. cmd_hex = '7e7e10{:02x}{:x}'.format(att_t, 0x10 + att_t)
  44. exp_res_hex = '7e7e20{:02x}00{:x}'.format(att_t, 0x20 + att_t)
  45. cmd = codecs.decode(cmd_hex, 'hex')
  46. exp_res = codecs.decode(exp_res_hex, 'hex')
  47. serial_port.write(cmd)
  48. res = b''
  49. for i in range(5):
  50. res += serial_port.read(20)
  51. if res == exp_res:
  52. result = True
  53. break
  54. time.sleep(0.1)
  55. else:
  56. result = False
  57. serial_port.close()
  58. return result