remote_flash_cpld.py 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144
  1. #!/usr/bin/env python3
  2. import sys
  3. import os
  4. import time
  5. import subprocess
  6. import argparse
  7. TD_BW = '/home/user/td/bin/bw.sh'
  8. def run_tcl(script_content):
  9. tcl_file = '/tmp/_tmp_bw_script.tcl'
  10. with open(tcl_file, 'w') as f:
  11. f.write(script_content)
  12. try:
  13. res = subprocess.run([TD_BW, tcl_file], capture_output=True, text=True, timeout=60)
  14. return res.returncode, res.stdout, res.stderr
  15. except Exception as e:
  16. return -1, '', str(e)
  17. finally:
  18. if os.path.exists(tcl_file):
  19. try:
  20. os.remove(tcl_file)
  21. except OSError:
  22. pass
  23. def cmd_check():
  24. print('=== 1. Checking USB Devices ===')
  25. lsusb = subprocess.run(['lsusb'], capture_output=True, text=True).stdout
  26. anlogic_cable = '336c:1002' in lsusb
  27. serial_ok = ('1a86:7523' in lsusb) or ('0403:6001' in lsusb)
  28. print(f'Anlogic Programmer (336c:1002): {"FOUND [OK]" if anlogic_cable else "NOT FOUND [FAIL]"}')
  29. print(f'Serial Port (CH340/FT232): {"FOUND [OK]" if serial_ok else "NOT FOUND [FAIL]"}')
  30. print('\n=== 2. Checking JTAG Cable & CPLD Device ===')
  31. tcl = """
  32. set ret [catch {list_cable} out]
  33. set ret2 [catch {read_device_id} dev]
  34. puts "DEVICE_DETECTED: $dev"
  35. exit
  36. """
  37. code, stdout, stderr = run_tcl(tcl)
  38. detected = False
  39. for line in stdout.splitlines():
  40. if 'Connect device:' in line or 'DEVICE_DETECTED:' in line or 'ERROR' in line:
  41. print(line)
  42. if 'EF2L45' in line:
  43. detected = True
  44. if detected:
  45. print('\n>>> CPLD EF2L45 Detected Successfully! Hardware is READY! <<<')
  46. else:
  47. print('\n>>> Device not detected or Chip validation failed. Check cable connection & board power. <<<')
  48. def cmd_burn(bit_file):
  49. bit_path = os.path.abspath(bit_file)
  50. if not os.path.exists(bit_path):
  51. print(f'Error: File not found: {bit_path}')
  52. sys.exit(1)
  53. print(f'=== Burning {bit_path} to CPLD SPI Flash ===')
  54. tcl = f"""
  55. catch {{download -mode program_spi -bit "{bit_path}"}} err1
  56. puts "PROG_RES: $err1"
  57. catch {{download -mode refresh -bit "{bit_path}"}} err2
  58. puts "REFRESH_RES: $err2"
  59. exit
  60. """
  61. t0 = time.time()
  62. code, stdout, stderr = run_tcl(tcl)
  63. t1 = time.time()
  64. success = 'Chip validation success: EF2L45' in stdout and 'finish command "download -mode refresh' in stdout
  65. if success:
  66. print(f'\n>>> SUCCESS: Firmware burned and chip refreshed in {t1-t0:.1f}s! <<<')
  67. else:
  68. print('\n>>> FAILED: Burning process encountered an issue. Output log: <<<')
  69. print(stdout)
  70. if stderr:
  71. print('STDERR:', stderr)
  72. def cmd_sram(bit_file):
  73. bit_path = os.path.abspath(bit_file)
  74. if not os.path.exists(bit_path):
  75. print(f'Error: File not found: {bit_path}')
  76. sys.exit(1)
  77. print(f'=== Downloading {bit_path} to CPLD volatile SRAM ===')
  78. tcl = f"""
  79. catch {{download -mode jtag -bit "{bit_path}"}} err
  80. puts "JTAG_RES: $err"
  81. exit
  82. """
  83. t0 = time.time()
  84. code, stdout, stderr = run_tcl(tcl)
  85. t1 = time.time()
  86. if 'finish command "download -mode jtag' in stdout:
  87. print(f'>>> SUCCESS: Downloaded to SRAM in {t1-t0:.2f}s! <<<')
  88. else:
  89. print('>>> FAILED: Download to SRAM failed: <<<')
  90. print(stdout)
  91. def cmd_uart(baud, duration):
  92. import serial
  93. print(f'=== Listening to /dev/ttyUSB0 at {baud} baud for {duration} seconds ===')
  94. try:
  95. s = serial.Serial('/dev/ttyUSB0', baud, timeout=0.5)
  96. except Exception as e:
  97. print(f'Error opening serial port: {e}')
  98. return
  99. t0 = time.time()
  100. total_bytes = 0
  101. while time.time() - t0 < duration:
  102. b = s.read(128)
  103. if b:
  104. total_bytes += len(b)
  105. print(f'[{len(b)} B] HEX: {b.hex()} | ASCII: {b.decode("latin1", errors="replace")}')
  106. s.close()
  107. print(f'=== Finished: received {total_bytes} bytes total ===')
  108. def main():
  109. parser = argparse.ArgumentParser(description='CPLD EF2L45 Remote Flash & Test Tool')
  110. subparsers = parser.add_subparsers(dest='command', required=True)
  111. subparsers.add_parser('check', help='Check cable and detect CPLD chip')
  112. p_burn = subparsers.add_parser('burn', help='Burn bitstream to non-volatile SPI Flash')
  113. p_burn.add_argument('file', help='Path to .bit bitstream file')
  114. p_sram = subparsers.add_parser('sram', help='Download bitstream to volatile SRAM')
  115. p_sram.add_argument('file', help='Path to .bit bitstream file')
  116. p_uart = subparsers.add_parser('uart', help='Listen to CPLD serial port /dev/ttyUSB0')
  117. p_uart.add_argument('--baud', type=int, default=115200, help='Baud rate (default 115200)')
  118. p_uart.add_argument('--duration', type=float, default=3.0, help='Listening duration in seconds')
  119. args = parser.parse_args()
  120. if args.command == 'check':
  121. cmd_check()
  122. elif args.command == 'burn':
  123. cmd_burn(args.file)
  124. elif args.command == 'sram':
  125. cmd_sram(args.file)
  126. elif args.command == 'uart':
  127. cmd_uart(args.baud, args.duration)
  128. if __name__ == '__main__':
  129. main()