remote_flash_cpld.py 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183
  1. #!/usr/bin/env python3
  2. import sys
  3. import os
  4. import time
  5. import subprocess
  6. import argparse
  7. import tempfile
  8. import re
  9. from pathlib import Path
  10. TD_BW = '/home/user/td/bin/bw.sh'
  11. def td_error_lines(stdout, stderr):
  12. """TD can return zero and finish a command after a programmer error."""
  13. errors = []
  14. for line in (stdout + '\n' + stderr).splitlines():
  15. if (re.search(r'\bPRG-9\d{3}\b', line) or
  16. re.match(r'^\s*(?:[A-Z]+-\d+\s+)?(?:ERROR|FATAL)\b', line, re.IGNORECASE) or
  17. re.search(r'\bProgram done check failed\b', line, re.IGNORECASE)):
  18. errors.append(line)
  19. return errors
  20. def td_result_ok(code, stdout, stderr, marker):
  21. """A completion marker is necessary but cannot override an error log."""
  22. return code == 0 and marker in stdout.splitlines() and not td_error_lines(stdout, stderr)
  23. def run_tcl(script_content, timeout=120):
  24. with tempfile.NamedTemporaryFile(mode='w', suffix='.tcl', prefix='prod2u-bw-', delete=False) as f:
  25. f.write(script_content)
  26. tcl_file = f.name
  27. try:
  28. res = subprocess.run([TD_BW, tcl_file], stdin=subprocess.DEVNULL, capture_output=True, text=True, timeout=timeout)
  29. return res.returncode, res.stdout, res.stderr
  30. except Exception as e:
  31. return -1, '', str(e)
  32. finally:
  33. if os.path.exists(tcl_file):
  34. try:
  35. os.remove(tcl_file)
  36. except OSError:
  37. pass
  38. def cmd_check():
  39. print('=== 1. Checking USB Devices ===')
  40. lsusb = subprocess.run(['lsusb'], capture_output=True, text=True).stdout
  41. anlogic_cable = '336c:1002' in lsusb
  42. serial_ok = ('1a86:7523' in lsusb) or ('0403:6001' in lsusb)
  43. print(f'Anlogic Programmer (336c:1002): {"FOUND [OK]" if anlogic_cable else "NOT FOUND [FAIL]"}')
  44. print(f'Serial Port (CH340/FT232): {"FOUND [OK]" if serial_ok else "NOT FOUND [FAIL]"}')
  45. print('\n=== 2. Checking JTAG Cable & CPLD Device ===')
  46. tcl = """
  47. if {[catch {list_cable} out]} {puts stderr $out; exit 1}
  48. if {[catch {read_device_id} dev]} {puts stderr $dev; exit 1}
  49. puts "DEVICE_DETECTED: $dev"
  50. exit 0
  51. """
  52. code, stdout, stderr = run_tcl(tcl)
  53. detected = False
  54. for line in stdout.splitlines():
  55. if 'Connect device:' in line or 'DEVICE_DETECTED:' in line or 'ERROR' in line:
  56. print(line)
  57. if line == 'DEVICE_DETECTED: EF2L45':
  58. detected = td_result_ok(code, stdout, stderr, line)
  59. if detected:
  60. print('\n>>> CPLD EF2L45 Detected Successfully! Hardware is READY! <<<')
  61. else:
  62. print('\n>>> Device not detected or Chip validation failed. Check cable connection & board power. <<<')
  63. return 0 if detected else 1
  64. def cmd_burn(bit_file):
  65. """Program SPI Flash, verify, boot from Flash and check masked SRAM (200K)."""
  66. bit = Path(bit_file).resolve()
  67. if not bit.is_file() or not bit.with_suffix('.bmk').is_file():
  68. print('Error: Flash requires the selected .bit and matching bitgen .bmk')
  69. return 1
  70. if any(c in str(bit) for c in '{}\n\r'):
  71. raise ValueError('BIT path contains unsupported Tcl characters')
  72. # Vendor doc/config/config.json PROGRAM_FLASH is 'program_spi -v'.
  73. # EF2 uses program_spief; its integrated verify avoids the generic SPI vector path.
  74. stages = [('program_spi -v', 'PROD2U_FLASH_PROGRAMMED_VERIFIED'),
  75. ('refresh', 'PROD2U_FLASH_REFRESHED'),
  76. ('x_rdbk', 'PROD2U_FLASH_BOOT_VERIFIED')]
  77. print(f'=== SPI Flash program/verify/refresh/SRAM readback, 200K: {bit} ===', flush=True)
  78. t0 = time.monotonic()
  79. with tempfile.TemporaryDirectory(prefix='prod2u-flash-200k-') as directory:
  80. for mode, marker in stages:
  81. vector_name = mode.split()[0]
  82. tcl = f"""
  83. if {{[catch {{download -mode {mode} -spd 3 -cable 0 -bit {{{bit}}} -vec {{{directory}/{vector_name}.vec}}}} err]}} {{puts stderr $err; exit 1}}
  84. puts "{marker}"
  85. exit 0
  86. """
  87. code, stdout, stderr = run_tcl(tcl, timeout=600)
  88. print(stdout, flush=True)
  89. if stderr:
  90. print(stderr, file=sys.stderr, flush=True)
  91. if not td_result_ok(code, stdout, stderr, marker):
  92. print(f'FLASH FAILED at {mode}; no following stage executed', flush=True)
  93. return 1
  94. print(f'FLASH PROGRAM + VERIFY + REFRESH + READBACK PASS (200K), {time.monotonic()-t0:.1f}s', flush=True)
  95. return 0
  96. def cmd_sram(bit_file):
  97. """6400V2.0 .79 cable: legacy speed 3 is 200 kHz, verified on this cable.
  98. TD 2026.1 requires an explicit vector path for real transfer. A marker
  99. without that path returned in 0.24 s while the old firmware kept running.
  100. Readback uses the bitgen .bmk to exclude live user RAM contents.
  101. """
  102. bit = Path(bit_file).resolve()
  103. if not bit.is_file() or not bit.with_suffix('.bmk').is_file():
  104. print('Error: SRAM requires the selected .bit and its matching bitgen .bmk')
  105. return 1
  106. if any(c in str(bit) for c in '{}\n\r'):
  107. raise ValueError('BIT path contains unsupported Tcl characters')
  108. print(f'=== 6400V2.0 SRAM program + readback, 200K: {bit} ===')
  109. with tempfile.TemporaryDirectory(prefix='prod2u-sram-200k-') as directory:
  110. tcl = f"""
  111. if {{[catch {{download -mode jtag -spd 3 -cable 0 -bit {{{bit}}} -vec {{{directory}/program.vec}}}} err]}} {{puts stderr $err; exit 1}}
  112. puts "PROD2U_SRAM_PROGRAMMED"
  113. if {{[catch {{download -mode x_rdbk -spd 3 -cable 0 -bit {{{bit}}} -vec {{{directory}/verify.vec}}}} err]}} {{puts stderr $err; exit 1}}
  114. puts "PROD2U_SRAM_VERIFIED"
  115. exit 0
  116. """
  117. code, stdout, stderr = run_tcl(tcl)
  118. success = td_result_ok(code, stdout, stderr, 'PROD2U_SRAM_VERIFIED')
  119. print(stdout)
  120. if stderr:
  121. print(stderr, file=sys.stderr)
  122. print('SRAM PROGRAM + READBACK PASS (200K)' if success else 'SRAM PROGRAM/READBACK FAILED')
  123. return 0 if success else 1
  124. def cmd_uart(baud, duration, port):
  125. import serial
  126. print(f'=== Listening to {port} at {baud} baud for {duration} seconds ===')
  127. try:
  128. s = serial.Serial(port, baud, timeout=0.5)
  129. except Exception as e:
  130. print(f'Error opening serial port: {e}')
  131. return 1
  132. t0 = time.time()
  133. total_bytes = 0
  134. while time.time() - t0 < duration:
  135. b = s.read(128)
  136. if b:
  137. total_bytes += len(b)
  138. print(f'[{len(b)} B] HEX: {b.hex()} | ASCII: {b.decode("latin1", errors="replace")}')
  139. s.close()
  140. print(f'=== Finished: received {total_bytes} bytes total ===')
  141. return 0 if total_bytes else 1
  142. def main():
  143. parser = argparse.ArgumentParser(description='CPLD EF2L45 Remote Flash & Test Tool')
  144. subparsers = parser.add_subparsers(dest='command', required=True)
  145. subparsers.add_parser('check', help='Check cable and detect CPLD chip')
  146. p_burn = subparsers.add_parser('burn', help='Burn bitstream to non-volatile SPI Flash')
  147. p_burn.add_argument('file', help='Path to .bit bitstream file')
  148. p_sram = subparsers.add_parser('sram', help='Download bitstream to volatile SRAM')
  149. p_sram.add_argument('file', help='Path to .bit bitstream file')
  150. p_uart = subparsers.add_parser('uart', help='Listen to an explicitly selected CPLD serial port')
  151. p_uart.add_argument('--baud', type=int, choices=(921600, 460800, 230400, 115200), default=921600, help='Host baud rate (default 921600)')
  152. p_uart.add_argument('--port', required=True)
  153. p_uart.add_argument('--duration', type=float, default=3.0, help='Listening duration in seconds')
  154. args = parser.parse_args()
  155. if args.command == 'check':
  156. return cmd_check()
  157. elif args.command == 'burn':
  158. return cmd_burn(args.file)
  159. elif args.command == 'sram':
  160. return cmd_sram(args.file)
  161. elif args.command == 'uart':
  162. return cmd_uart(args.baud, args.duration, args.port)
  163. if __name__ == '__main__':
  164. raise SystemExit(main())