remote_flash_cpld.py 5.6 KB

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