2
0

flashmax.pl 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708
  1. #!/usr/bin/perl
  2. use strict;
  3. use integer;
  4. use PerlIO::gzip;
  5. use File::Temp;
  6. use File::Spec;
  7. use Time::HiRes qw(usleep tv_interval);
  8. use Digest::CRC qw(crc32);
  9. use v5.10; # For "state"
  10. my $esptool = 'esptool.py';
  11. $esptool = $ENV{'ESPTOOL'} || $esptool;
  12. my $esp_retries = 10;
  13. my @FW_MAGIC = (undef, 0x7a07fbd6, 0xa924ed0b);
  14. my %datatypes = (
  15. 'end' => 0, # End of data
  16. 'data' => 1, # FPGA flash data
  17. 'target' => 2, # Firmware target string
  18. 'note' => 3, # Informative string
  19. 'espota' => 4, # ESP32 OTA image
  20. 'fpgainit' => 5, # FPGA bypass (transient) image during update
  21. 'esppart' => 6, # ESP32 partition table
  22. 'espsys' => 7, # ESP32 boot loader, OTA control partition...
  23. 'esptool' => 8, # esptool.py options for flashing
  24. 'boardinfo' => 9 # board_info base address
  25. );
  26. my @type;
  27. foreach my $t (keys(%datatypes)) {
  28. $type[$datatypes{$t}] = $t;
  29. }
  30. my $FDF_OPTIONAL = 0x0001;
  31. my $FDF_PRETARGET = 0x0002;
  32. my $STRING_MAX_LEN = 4095;
  33. my $boardinfo_addr = 0;
  34. my $boardinfo_len = 4096;
  35. # For debug; DC1-4 replaced with functional names
  36. my @ascii = qw(NUL SOH STX ETX EOT ENQ ACK BEL BS HT LF VT FF CR SO SI
  37. DLE XON WRST XOFF WGO NAK SYN ETB CAN EM SUB ESC FS GS RS US);
  38. foreach my $i (9, 10, 13, 32..126) {
  39. $ascii[$i] = chr($i);
  40. }
  41. $ascii[127] = 'DEL';
  42. for (my $i = 128; $i < 256; $i++) {
  43. $ascii[$i] = sprintf("%02X", $i);
  44. }
  45. my @a = map { length($_) == 1 ? $_ : '<'.$_.'>' } @ascii;
  46. # Simple base64 encode using 3F-7E, bytewise bigendian
  47. sub mybaseencode {
  48. my $nbits = 0;
  49. my $bitbuf = 0;
  50. my $out = '';
  51. foreach my $s (@_) {
  52. foreach my $c (unpack('C*', $s)) {
  53. $nbits += 8;
  54. $bitbuf = ($bitbuf << 8) + $c;
  55. while ($nbits >= 6) {
  56. $nbits -= 6;
  57. $out .= pack('C', 63 + (($bitbuf >> $nbits) & 63));
  58. }
  59. }
  60. }
  61. if ($nbits) {
  62. $out .= pack('C', 63 + ($bitbuf & ((1 << $nbits) - 1)));
  63. }
  64. return $out;
  65. }
  66. sub getint($) {
  67. my($s) = @_;
  68. return undef
  69. unless ($s =~ /^(([1-9][0-9]+)|(0(x[0-9a-f]+|[0-7]*)))([kmgtpe]?)$/i);
  70. my $o = oct($3) + $2;
  71. my $p = lc($5);
  72. if ($p eq 'k') {
  73. $o <<= 10;
  74. } elsif ($p eq 'm') {
  75. $o <<= 20;
  76. } elsif ($p eq 'g') {
  77. $o <<= 30;
  78. } elsif ($p eq 't') {
  79. $o <<= 40;
  80. } elsif ($p eq 'p') {
  81. $o <<= 50;
  82. } elsif ($p eq 'e') {
  83. $o <<= 60;
  84. }
  85. return $o;
  86. }
  87. sub match_version($$) {
  88. my($ver,$pattern) = @_;
  89. return 1; # FIX THIS
  90. }
  91. sub filelen($) {
  92. my($f) = @_;
  93. my @s = stat($f);
  94. return $s[7];
  95. }
  96. sub unquote_cmd($) {
  97. my($s) = @_;
  98. my @a;
  99. $s =~ s/[\r\n]+/ /g;
  100. while ($s =~ /^\s*(?:\"((?:[^\"]+|\"\")*)\"|(\S+))(\s.*)?$/) {
  101. push(@a, $1.$2);
  102. $s = $3;
  103. }
  104. return @a;
  105. }
  106. # Similar to grep, but for a hash; also filters out
  107. sub hgrep(&%) {
  108. my($mfunc, %hash) = @_;
  109. return map { $_ => $hash{$_} } grep(&$mfunc, keys %hash);
  110. }
  111. # Wrapper for running esptool, returns a hash with info output
  112. # or dies on failure
  113. sub hash2opt($)
  114. {
  115. my($h) = @_;
  116. return () unless (defined($h));
  117. return map { $h->{$_} ne '' ? ('--'.$_, $h->{$_}) : () } sort keys %{$h};
  118. }
  119. sub run_esptool($$$$@)
  120. {
  121. my($port,$common_options,$cmd,$cmd_options,@args) = @_;
  122. my @espcmd = unquote_cmd($esptool);
  123. push(@espcmd, '--port', $port);
  124. push(@espcmd, hash2opt($common_options));
  125. push(@espcmd, unquote_cmd($cmd));
  126. push(@espcmd, hash2opt($cmd_options));
  127. push(@espcmd, @args);
  128. my $retries = $esp_retries;
  129. my $ok = 0;
  130. my %outinfo;
  131. my @output;
  132. while (!$ok && $retries--) {
  133. %outinfo = ();
  134. @output = ();
  135. print STDERR 'Command: ', join(' ', @espcmd), "\n";
  136. print STDERR "Running $espcmd[0] $cmd... ";
  137. my $esp;
  138. if (!open($esp, '-|', @espcmd)) {
  139. print STDERR $!, "\n";
  140. exit 1;
  141. }
  142. while (defined(my $l = <$esp>)) {
  143. if ($l =~ /^Chip is (\S+)/) {
  144. $outinfo{'chip'} = $1;
  145. } elsif ($l =~ /^MAC: ([0-9a-f:]+)/) {
  146. $outinfo{'mac'} = $1;
  147. }
  148. push(@output, $l);
  149. }
  150. $ok = close($esp);
  151. if ($ok) {
  152. print STDERR "ok\n";
  153. last;
  154. } elsif ($retries) {
  155. @output = ();
  156. print STDERR "failed, retrying\n";
  157. usleep(1000000);
  158. } else {
  159. print STDERR "failed, giving up\n";
  160. }
  161. }
  162. print STDERR @output;
  163. die "$0: $espcmd[0] $cmd failed\n" unless ($ok);
  164. return %outinfo;
  165. }
  166. sub target_string_valid($)
  167. {
  168. my($v) = @_;
  169. return $v =~ /^(\S+) v((?:0|[1-9][0-9]*)(?:\.0|\.[1-9][0-9]*)*)(?: ([a-zA-Z0-9]*))?$/;
  170. }
  171. sub match_version($$)
  172. {
  173. my($version,$pattern) = @_;
  174. my @vv = target_string_valid($version);
  175. return 0 unless (defined($vv[0]));
  176. my $v_board = $vv[0];
  177. my @v_ver = split(/\./, $vv[1]);
  178. my $v_flags = $vv[2];
  179. return 1 if ($pattern eq $v_board); # Board only matchall pattern
  180. if ($pattern !~ /^(\S+) v((?:0|[1-9][0-9]*)(?:\.\.0|\.[1-9][0-9]*)*)(?:(\-)((?:0|[1-9][0-9]*)(?:\.\.0|\.[1-9][0-9]*)*))?(?: ([\+\-a-zA-Z0-9]*))?$/) {
  181. return 0;
  182. }
  183. return 0 if ($1 ne $v_board);
  184. my @p_min = split(/\./, $2);
  185. my @p_max = split(/\./, $3 eq '' ? $2 : $4);
  186. my $p_flags = $5;
  187. while (scalar(@p_min) || scalar(@p_max)) {
  188. my $mi = shift(@p_min);
  189. my $ma = shift(@p_max);
  190. my $ve = shift(@v_ver) || 0;
  191. return 0 if (defined($mi) && $ve < $mi);
  192. return 0 if (defined($ma) && $ve > $ma);
  193. }
  194. my $flag_pol = 1;
  195. foreach my $c (split(//, $p_flags)) {
  196. if ($c eq '-') {
  197. $flag_pol = 0;
  198. } elsif ($c eq '+') {
  199. $flag_pol = 1;
  200. } else {
  201. return 0 if ((index($v_flags, $c) != -1) != $flag_pol);
  202. }
  203. }
  204. return 1;
  205. }
  206. sub get_target_board($$)
  207. {
  208. my($port,$boardinfo) = @_;
  209. run_esptool($port, { 'before' => 'default_reset', 'after' => 'hard_reset' },
  210. 'read_flash', { },
  211. ''.$boardinfo_addr, ''.$boardinfo_len, $boardinfo);
  212. open(my $bi, '<:raw', $boardinfo) or return undef;
  213. my $bid;
  214. read($bi, $bid, $boardinfo_len);
  215. close($bi);
  216. return undef if (length($bid) != $boardinfo_len);
  217. my @bh = unpack('VVVVZ[256]', $bid);
  218. if ($bh[0] == 0x6682df97 && $bh[1] == 0xe2a0d506) {
  219. # Standard format board_info structure
  220. substr($bid, 12, 4) = "\0\0\0\0"; # Clear the CRC field
  221. if ($bh[2] >= 16 && $bh[2] <= $boardinfo_len &&
  222. crc32(substr($bid, 0, $bh[2])) == $bh[3]) {
  223. return $bh[4];
  224. }
  225. } elsif ($bid =~ /^([[:print:]]+)\0/) {
  226. # Preliminary board_info (only version string)
  227. return $1;
  228. }
  229. return undef;
  230. }
  231. my @args = @ARGV;
  232. my $esponly = 0;
  233. my $file;
  234. my $target_board = undef;
  235. my $setver = 0;
  236. while (1) {
  237. $file = shift(@args);
  238. last if ($file !~ /^\-/);
  239. if ($file eq '--esponly') {
  240. $esponly = 1;
  241. } elsif ($file eq '--setver') {
  242. $target_board = shift(@args);
  243. $setver = defined($target_board);
  244. } elsif ($file eq '--') {
  245. $file = shift(@args);
  246. last;
  247. } else {
  248. undef $file; # Invalid argument, print usage
  249. last;
  250. }
  251. }
  252. my $port = shift(@args);
  253. if (!defined($port)) {
  254. die "Usage: $0 [--esponly][--setver versionoptions] file.fw port [esptool_options...]\n";
  255. }
  256. if (!File::Spec->file_name_is_absolute($port)) {
  257. if (-c "/dev/$port") {
  258. $port = "/dev/$port";
  259. } elsif (-c "/dev/tty$port") {
  260. $port = "/dev/tty$port";
  261. } elsif ($^O eq 'MSWin32') {
  262. $port = "\\\\.\\$port";
  263. } else {
  264. die "$0: no such serial port: $port\n";
  265. }
  266. }
  267. print STDERR "Using serial port device $port\n";
  268. my $td = File::Temp->newdir(CLEANUP => 1);
  269. my $boardinfo = File::Spec->catfile($td, 'boardinfo.bin');
  270. my @espfiles = ();
  271. if (defined($target_board)) {
  272. # Forcibly write target board version
  273. if (!target_string_valid($target_board)) {
  274. die "$0: $port: invalid firmware target string: $target_board\n";
  275. }
  276. open(my $bi, '>:raw', $boardinfo)
  277. or die "$0: $port: $boardinfo: $!\n";
  278. my $bid = $target_board . "\0";
  279. $bid .= "\xff" x ($boardinfo_len - length($bid));
  280. print $bi $bid;
  281. close($bi);
  282. push(@espfiles, ''.$boardinfo_addr, $boardinfo);
  283. } else {
  284. # Get the board version from target flash
  285. $target_board = get_target_board($port, $boardinfo);
  286. if (!defined($target_board) || !target_string_valid($target_board)) {
  287. die "$0: $port: board version not programmed, specify with --setver\n";
  288. }
  289. }
  290. open(my $fw, '<:gzip', $file)
  291. or die "$0: $file: $!\n";
  292. my @chunks = ();
  293. my $version_match = undef;
  294. my $err = 0;
  295. my $hdr;
  296. while (read($fw, $hdr, 16) == 16) {
  297. # magic type flags data_len addr
  298. my @h = unpack('VvvVV', $hdr);
  299. my $c = { 'hdr' => $hdr, 'magic' => $h[0], 'type' => $h[1],
  300. 'flags' => $h[2], 'len' => $h[3], 'addr' => $h[4],
  301. 'vmatch' => 0, 'vmask' => 0, 'vmin' => 0, 'vmax' => 0xffff };
  302. if ($c->{'magic'} == $FW_MAGIC[2]) {
  303. if (read($fw, $hdr, 16) != 16) {
  304. print STDERR "$0: $file: short header read\n";
  305. $err = 1;
  306. last;
  307. }
  308. my @h = unpack('VVvvV', $hdr);
  309. $c->{'hdr'} .= $hdr;
  310. $c->{'vmatch'} = $h[0];
  311. $c->{'vmask'} = $h[1];
  312. $c->{'vmin'} = $h[2];
  313. $c->{'vmax'} = $h[3];
  314. } elsif ($c->{'magic'} != $FW_MAGIC[1]) {
  315. print STDERR "$0: $file: bad chunk magic\n";
  316. $err = 1;
  317. last;
  318. }
  319. my $t = $type[$c->{'type'}];
  320. my $d;
  321. if (read($fw, $d, $c->{'len'}) != $c->{'len'}) {
  322. print STDERR "$0: $file: short chunk read\n";
  323. $err = 1;
  324. last;
  325. }
  326. $c->{'data'} = $d;
  327. if ($t eq 'target') {
  328. my $is_match = match_version($target_board, $d);
  329. if ($c->{'magic'} == $FW_MAGIC[1] || $is_match) {
  330. $version_match = $c;
  331. }
  332. print STDERR "$0: $file: supports hardware: $d",
  333. ($is_match ? ' (match)' : ''), "\n";
  334. } elsif ($t eq 'end' || $t eq 'note' || ($c->{'flags'} & $FDF_PRETARGET)) {
  335. # Not filtered
  336. } else {
  337. if (!defined($version_match)) {
  338. print STDERR "$0: $file: hardware version $target_board not supported\n";
  339. $err = 1;
  340. last;
  341. }
  342. if ($c->{'vmin'} > $version_match->{'vmax'} ||
  343. $c->{'vmax'} < $version_match->{'vmin'} ||
  344. (($c->{'vmatch'} ^ $version_match->{'vmatch'}) & $c->{'vmask'})) {
  345. # Not applicable to this board
  346. next;
  347. }
  348. }
  349. push(@chunks, $c);
  350. last if ($t eq 'end'); # End of stream
  351. }
  352. close($fw);
  353. exit $err if ($err);
  354. my %espopt = ('before' => 'default_reset', 'after' => 'hard_reset',
  355. 'baud' => 115200, 'port' => undef, 'chip' => undef,
  356. 'flash_mode' => undef, 'flash_freq' => undef,
  357. 'flash_size' => undef);
  358. # Create a compressed data buffer without the ESP32 chunks
  359. my $fpgadata;
  360. open(my $fpgafh, '>:gzip', \$fpgadata) or die;
  361. my $nc = 0;
  362. foreach my $c ( @chunks ) {
  363. my $t = $type[$c->{'type'}];
  364. if ($t eq 'esptool') {
  365. my $s = $c->{'data'};
  366. $s =~ s/[\r\n]+/ /g;
  367. while ($s =~ /^\s*(\S+)\s+(\S+)(.*)/) {
  368. $espopt{$1} = $2;
  369. $s = $3;
  370. }
  371. } elsif ($t =~ /^esp/ && $c->{'addr'}) {
  372. my $addr = sprintf('%x', $c->{'addr'});
  373. my $tff = File::Spec->catfile($td, $t.$nc.'_'.$addr.'.bin');
  374. open(my $tf, '>', $tff) or die "$0: $tff: $!\n";
  375. print $tf $c->{'data'};
  376. close($tf);
  377. push(@espfiles, '0x'.$addr, $tff);
  378. } elsif ($t eq 'note' || ($t eq 'target' && $c != $version_match)) {
  379. # Skip
  380. } else {
  381. print $fpgafh $c->{'hdr'};
  382. print $fpgafh $c->{'data'};
  383. }
  384. $nc++;
  385. }
  386. close($fpgafh);
  387. foreach my $e (keys %espopt) {
  388. my $ev = $ENV{"ESP\U$e"};
  389. if (defined($ev)) {
  390. $espopt{$e} = $ev;
  391. }
  392. }
  393. run_esptool($port, { hgrep {!/^flash_/} %espopt },
  394. 'write_flash', { hgrep {/^flash_/} %espopt },
  395. '-z', @espfiles);
  396. my $SerialPort = eval {
  397. require Device::SerialPort;
  398. Device::SerialPort->import(qw(:PARAM));
  399. 'Device::SerialPort';
  400. } || eval {
  401. require Win32::SerialPort;
  402. Win32::SerialPort->import(qw(:STAT));
  403. 'Win32::SerialPort';
  404. } || die "$0: need Device::SerialPort or Win32::SerialPort\n";
  405. print STDERR "Waiting for reinit...\n";
  406. usleep(4000000);
  407. my $tty = $SerialPort->new($port);
  408. die "$0: $port: $!\n" if (!$tty);
  409. $tty->buffers($tty->buffer_max);
  410. $tty->reset_error;
  411. $tty->user_msg(1);
  412. $tty->error_msg(1);
  413. $tty->handshake('none');
  414. $tty->databits(8);
  415. $tty->baudrate(115200);
  416. $tty->stopbits(1);
  417. $tty->parity('none');
  418. $tty->stty_istrip(0);
  419. $tty->stty_inpck(0);
  420. $tty->datatype('raw');
  421. $tty->stty_icanon(0);
  422. $tty->stty_opost(0);
  423. $tty->stty_ignbrk(0);
  424. $tty->stty_inlcr(0);
  425. $tty->stty_igncr(0);
  426. $tty->stty_icrnl(0);
  427. $tty->stty_echo(0);
  428. $tty->stty_echonl(0);
  429. $tty->stty_isig(0);
  430. $tty->read_char_time(0);
  431. $tty->write_settings;
  432. # In case DTR and/or RTS was asserted on the physical serial port.
  433. # Note that DTR needs to be deasserted before RTS!
  434. # However, deasserting DTR on the ACM port prevents it from working,
  435. # so only do this if we don't see CTS (which is always enabled on ACM)...
  436. if ($tty->can_modemlines && !($tty->modemlines & $tty->MS_CTS_ON)) {
  437. usleep(100000);
  438. $tty->dtr_active(0);
  439. usleep(100000);
  440. $tty->rts_active(0);
  441. usleep(100000);
  442. }
  443. sub tty_read {
  444. state %old_timeout;
  445. my($tty,$bufref,$timeout) = @_;
  446. my $d = $$bufref;
  447. if ($d eq '') {
  448. my $c;
  449. if (!defined($old_timeout{$tty}) || $timeout != $old_timeout{$tty}) {
  450. $tty->read_const_time($timeout);
  451. $old_timeout{$tty} = $timeout;
  452. }
  453. ($c,$d) = $tty->read(256);
  454. return '' if (!$c);
  455. }
  456. my $r = substr($d,0,1);
  457. $$bufref = substr($d,1);
  458. return $r;
  459. }
  460. my $ttybuf = '';
  461. sub tty_write($$) {
  462. my($tty,$data) = @_;
  463. my $bytes = length($data);
  464. my $offs = 0;
  465. while ($bytes) {
  466. my $cnt = $tty->write(substr($data,$offs,$bytes));
  467. usleep(10000) unless ($cnt);
  468. $offs += $cnt;
  469. $bytes -= $cnt;
  470. }
  471. return $offs;
  472. }
  473. my $found = 0;
  474. my $tt = time();
  475. my $start_enq = $tt;
  476. tty_write($tty, "\005"); # ENQ
  477. while (($tt = time()) - $start_enq < 30) {
  478. my $d = tty_read($tty, \$ttybuf, 1000);
  479. if ($d eq '') {
  480. tty_write($tty, "\005"); # ENQ
  481. } else {
  482. my $ix = index("\026\004\027", $d);
  483. if ($ix < 0) {
  484. print STDERR $d;
  485. next;
  486. }
  487. $found = $found == $ix ? $found+1 : 0;
  488. last if ($found == 3);
  489. }
  490. }
  491. if ($found < 3) {
  492. die "$0: $port: no MAX80 ESP32 detected\n";
  493. }
  494. $start_enq = $tt;
  495. my $last_req;
  496. my $winspc;
  497. while (!defined($winspc)) {
  498. $tt = time();
  499. if ($tt - $start_enq >= 10) {
  500. die "$0: $port: failed to start FPGA firmware upload\n";
  501. }
  502. if ($tt != $last_req) {
  503. tty_write($tty, "\034\001: /// MAX80 FW UPLOAD \~\@\~ \$\r\n\035");
  504. $last_req = $tt;
  505. }
  506. my $d;
  507. while (1) {
  508. $d = tty_read($tty, \$ttybuf, 100);
  509. last if ($d eq '');
  510. my $dc = unpack('C', $d);
  511. print STDERR $a[$dc];
  512. if ($dc == 036) {
  513. $winspc = 0;
  514. last;
  515. }
  516. }
  517. }
  518. my $bytes = length($fpgadata);
  519. my $offset = 0;
  520. my $maxchunk = 64;
  521. my $maxahead = 256;
  522. my $last_ack = 0;
  523. my @pktends = ();
  524. my $last_enq = 0;
  525. my $last_ack_time = 0;
  526. print STDERR "\nStarting packet transmit...\n";
  527. while ($last_ack < $bytes) {
  528. my $chunk;
  529. my $now;
  530. while (1) {
  531. $chunk = $bytes - $offset;
  532. $chunk = $winspc if ($chunk > $winspc);
  533. if ($offset + $chunk > $last_ack + $maxahead) {
  534. $chunk = $last_ack + $maxahead - $offset;
  535. }
  536. $chunk = 0 if ($chunk <= 0);
  537. $chunk = $maxchunk if ($chunk > $maxchunk);
  538. my $d = tty_read($tty, \$ttybuf, $chunk ? 0 : $maxchunk/10);
  539. $now = time();
  540. last if ($d eq '');
  541. my $dc = unpack('C', $d);
  542. if ($dc == 022) {
  543. $winspc = 0;
  544. } elsif ($dc == 024) {
  545. if (defined($winspc)) {
  546. $winspc += 256;
  547. }
  548. } elsif ($dc == 006) {
  549. $last_ack = shift(@pktends) || $last_ack;
  550. if ($now != $last_ack_time) {
  551. printf STDERR "%s: %s: %d/%d (%d%%) uploaded\n",
  552. $0, $port, $last_ack, $bytes, $last_ack*100/$bytes;
  553. $last_ack_time = $now;
  554. }
  555. } else {
  556. print STDERR $a[$dc];
  557. if ($dc == 025 || $dc == 031 || $dc == 037) {
  558. $offset = $last_ack;
  559. @pktends = ();
  560. undef $winspc; # Wait for WRST before resuming
  561. } elsif ($dc == 030) {
  562. print STDERR "\n";
  563. die "$0: $port: upload aborted by target system\n";
  564. }
  565. }
  566. }
  567. if (!$chunk) {
  568. if ($bytes > $offset) {
  569. if ($now != $last_enq) {
  570. tty_write($tty, "\026"); # SYN: request window resync
  571. $last_enq = $now;
  572. }
  573. }
  574. next;
  575. }
  576. my $data = substr($fpgadata, $offset, $chunk);
  577. my $hdr = pack("CvVV", $chunk-1, 0, $offset, crc32($data));
  578. tty_write($tty, "\002".mybaseencode($hdr, $data));
  579. push(@pktends, $offset + $chunk);
  580. $offset += $chunk;
  581. $winspc -= $chunk;
  582. }
  583. tty_write($tty, "\004"); # EOT
  584. # Final messages out
  585. while (1) {
  586. my $d = tty_read($tty, \$ttybuf, 1000);
  587. last if ($d eq '');
  588. print STDERR $d;
  589. }
  590. $tty->close;
  591. print STDERR "\n$0: $port: firmware upload complete\n";
  592. exit 0;