2
0

flashmax.pl 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911
  1. #!/usr/bin/perl
  2. use strict;
  3. use integer;
  4. use IO::Handle;
  5. use PerlIO::gzip;
  6. use File::Temp;
  7. use File::Spec;
  8. use File::HomeDir;
  9. use Time::HiRes qw(usleep tv_interval);
  10. use Digest::CRC qw(crc32);
  11. use v5.10; # For "state"
  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 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. my $a = $1;
  102. $a =~ s/\"\"/\"/g;
  103. push(@a, $a.$2);
  104. $s = $3;
  105. }
  106. return @a;
  107. }
  108. # Similar to grep, but for a hash; also filters out
  109. sub hgrep(&%) {
  110. my($mfunc, %hash) = @_;
  111. return map { $_ => $hash{$_} } grep(&$mfunc, keys %hash);
  112. }
  113. # Wrapper for running esptool, returns a hash with info output
  114. # or dies on failure
  115. sub hash2opt($)
  116. {
  117. my($h) = @_;
  118. return () unless (defined($h));
  119. return map { $h->{$_} ne '' ? ('--'.$_, $h->{$_}) : () } sort keys %{$h};
  120. }
  121. my $esptool;
  122. # Try running esptool --help and look for a version string
  123. sub try_esptool($) {
  124. my($cmd) = @_;
  125. return undef if ($cmd eq '');
  126. my @espcmd = unquote_cmd($cmd);
  127. # Make sure stderr is unbuffered
  128. STDERR->autoflush(1);
  129. open(my $old_stderr, '>&', \*STDERR) or die;
  130. $old_stderr->autoflush(1);
  131. open(STDERR, '>', File::Spec->devnull()) or return undef;
  132. STDERR->autoflush(1);
  133. my $ver;
  134. my $espok = open(my $esp, '-|', @espcmd, '--help');
  135. if ($espok) {
  136. while (defined(my $l = <$esp>)) {
  137. if (!defined($ver) &&
  138. $l =~ /\besptool\S*\s+(v\S+)/) {
  139. $ver = $1;
  140. }
  141. }
  142. close($esp);
  143. }
  144. open(STDERR, '>&', $old_stderr) or die;
  145. close($old_stderr);
  146. if ($ver) {
  147. $esptool = $cmd;
  148. }
  149. return $ver;
  150. }
  151. sub updir($) {
  152. my($dir) = @_;
  153. return File::Spec->catdir($dir, File::Spec->updir());
  154. }
  155. sub find_esptool() {
  156. my $ver;
  157. my $python = '"' . ($ENV{'PYTHON'} || 'python') . '"';
  158. # The easy variants
  159. foreach my $et ($ENV{'ESPTOOL'}, 'esptool', 'esptool.py') {
  160. next unless ($et ne '');
  161. $ver = try_esptool($et);
  162. return $ver if ($ver);
  163. }
  164. # More complicated
  165. foreach my $p ($ENV{'ESPTOOL'}, File::Spec->path()) {
  166. next unless ($p ne '');
  167. next unless ( -d $p );
  168. my $et = File::Spec->catfile($p, 'esptool.py');
  169. if ( -f $et ) {
  170. $ver = try_esptool("${python} \"${et}\"");
  171. return $ver if ($ver);
  172. }
  173. }
  174. # Try to find it in an Arduino directory
  175. foreach my $dp (File::HomeDir->my_data,
  176. File::HomeDir->my_documents,
  177. updir(File::HomeDir->my_data),
  178. File::HomeDir->my_home) {
  179. next unless ( -d $dp );
  180. foreach my $dn ('.arduino15', 'Arduino15', 'ArduinoData') {
  181. my $etr = File::Spec->catdir($dp, $dn,
  182. qw(packages esp32 tools esptool_py));
  183. opendir(my $dh, $etr) or next;
  184. while (defined(my $sd = readdir($dh))) {
  185. next if ($sd eq File::Spec->curdir);
  186. next if ($sd eq File::Spec->updir);
  187. my $etd = File::Spec->catdir($etr, $sd);
  188. next unless ( -d $etd );
  189. my $esppath = File::Spec->catfile($etd, 'esptool');
  190. if ( ! -d $esppath ) {
  191. $ver = try_esptool("\"$esppath\"");
  192. last if ($ver);
  193. }
  194. $esppath .= '.py';
  195. if ( -f $esppath ) {
  196. $ver = try_esptool("${python} \"$esppath\"");
  197. last if ($ver);
  198. }
  199. }
  200. closedir($dh);
  201. return $ver if ($ver);
  202. }
  203. }
  204. return $ver;
  205. }
  206. sub run_esptool($$$$@)
  207. {
  208. my($port,$common_options,$cmd,$cmd_options,@args) = @_;
  209. my @espcmd = unquote_cmd($esptool);
  210. if (defined($port) && $common_options->{'port'} ne '') {
  211. push(@espcmd, '--port', $port);
  212. }
  213. push(@espcmd, hash2opt($common_options));
  214. push(@espcmd, unquote_cmd($cmd));
  215. push(@espcmd, hash2opt($cmd_options));
  216. push(@espcmd, @args);
  217. my $retries = $esp_retries;
  218. my $ok = 0;
  219. my %outinfo;
  220. my @output;
  221. while (!$ok && $retries--) {
  222. %outinfo = ();
  223. @output = ();
  224. print STDERR 'Command: ', join(' ', @espcmd), "\n";
  225. print STDERR "Running $espcmd[0] $cmd... ";
  226. my $esp;
  227. if (!open($esp, '-|', @espcmd)) {
  228. print STDERR $!, "\n";
  229. exit 1 if (defined($port));
  230. return undef;
  231. }
  232. while (defined(my $l = <$esp>)) {
  233. if ($l =~ /^Chip is (\S+)/) {
  234. $outinfo{'chip'} = $1;
  235. } elsif ($l =~ /^MAC: ([0-9a-f:]+)/) {
  236. $outinfo{'mac'} = $1;
  237. }
  238. push(@output, $l);
  239. }
  240. $ok = close($esp);
  241. if ($ok) {
  242. print STDERR "ok\n";
  243. last;
  244. } elsif ($retries) {
  245. @output = ();
  246. print STDERR "failed, retrying\n";
  247. usleep(1000000);
  248. } else {
  249. print STDERR "failed, giving up\n";
  250. }
  251. }
  252. print STDERR @output;
  253. if (!$ok) {
  254. if (defined($port)) {
  255. die "$0: $espcmd[0] $cmd failed\n";
  256. }
  257. return undef;
  258. }
  259. return %outinfo;
  260. }
  261. sub target_string_valid($)
  262. {
  263. my($v) = @_;
  264. return $v =~ /^(\S+) v((?:0|[1-9][0-9]*)(?:\.0|\.[1-9][0-9]*)*)(?: ([a-zA-Z0-9]*))?$/;
  265. }
  266. sub match_version($$)
  267. {
  268. my($version,$pattern) = @_;
  269. my @vv = target_string_valid($version);
  270. return 0 unless (defined($vv[0]));
  271. my $v_board = $vv[0];
  272. my @v_ver = split(/\./, $vv[1]);
  273. my $v_flags = $vv[2];
  274. return 1 if ($pattern eq $v_board); # Board only matchall pattern
  275. 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]*))?$/) {
  276. return 0;
  277. }
  278. return 0 if ($1 ne $v_board);
  279. my @p_min = split(/\./, $2);
  280. my @p_max = split(/\./, $3 eq '' ? $2 : $4);
  281. my $p_flags = $5;
  282. while (scalar(@p_min) || scalar(@p_max)) {
  283. my $mi = shift(@p_min);
  284. my $ma = shift(@p_max);
  285. my $ve = shift(@v_ver) || 0;
  286. return 0 if (defined($mi) && $ve < $mi);
  287. return 0 if (defined($ma) && $ve > $ma);
  288. }
  289. my $flag_pol = 1;
  290. foreach my $c (split(//, $p_flags)) {
  291. if ($c eq '-') {
  292. $flag_pol = 0;
  293. } elsif ($c eq '+') {
  294. $flag_pol = 1;
  295. } else {
  296. return 0 if ((index($v_flags, $c) != -1) != $flag_pol);
  297. }
  298. }
  299. return 1;
  300. }
  301. my %espopt = ('before' => 'default_reset', 'after' => 'hard_reset',
  302. 'connect-attempts' => 8);
  303. my $tmpdir;
  304. # Get a filename in $tmpdir
  305. sub tmpfilename($) {
  306. my($filename) = @_;
  307. if (!defined($tmpdir)) {
  308. die "$0: tmpfilename() called before tmpdir exists\n";
  309. }
  310. return File::Spec->catfile($tmpdir, $filename);
  311. }
  312. sub get_target_board($)
  313. {
  314. my($port) = @_;
  315. my $boardinfo = tmpfilename('boardinfo.bin');
  316. my %myespopt = (%espopt);
  317. $myespopt{'after'} = 'no_reset';
  318. run_esptool($port, { hgrep {!/^flash_/} \%myespopt },
  319. 'read_flash', { },
  320. sprintf('0x%x', $boardinfo_addr),
  321. $boardinfo_len, $boardinfo);
  322. open(my $bi, '<:raw', $boardinfo) or return undef;
  323. my $bid;
  324. read($bi, $bid, $boardinfo_len);
  325. close($bi);
  326. unlink($boardinfo);
  327. return undef if (length($bid) != $boardinfo_len);
  328. my @bh = unpack('VVVVZ[256]', $bid);
  329. if ($bh[0] == 0x6682df97 && $bh[1] == 0xe2a0d506) {
  330. # Standard format board_info structure
  331. substr($bid, 12, 4) = "\0\0\0\0"; # Clear the CRC field
  332. if ($bh[2] >= 16 && $bh[2] <= $boardinfo_len &&
  333. crc32(substr($bid, 0, $bh[2])) == $bh[3]) {
  334. return $bh[4];
  335. }
  336. } elsif ($bid =~ /^([[:print:]]+)\0/) {
  337. # Preliminary board_info (only version string)
  338. return $1;
  339. }
  340. return undef;
  341. }
  342. sub read_fwfile($$) {
  343. my($file, $target_board) = @_;
  344. return undef if (!defined($file));
  345. open(my $fw, '<:gzip', $file)
  346. or die "$0: $file: $!\n";
  347. my @chunks = ();
  348. my $version_match = undef;
  349. my $err = 0;
  350. my $hdr;
  351. while (read($fw, $hdr, 16) == 16) {
  352. # magic type flags data_len addr
  353. my @h = unpack('VvvVV', $hdr);
  354. my $c = { 'hdr' => $hdr, 'magic' => $h[0], 'type' => $h[1],
  355. 'flags' => $h[2], 'len' => $h[3], 'addr' => $h[4],
  356. 'vmatch' => 0, 'vmask' => 0, 'vmin' => 0, 'vmax' => 0xffff };
  357. if ($c->{'magic'} == $FW_MAGIC[2]) {
  358. if (read($fw, $hdr, 16) != 16) {
  359. print STDERR "$0: $file: short header read\n";
  360. $err = 1;
  361. last;
  362. }
  363. my @h = unpack('VVvvV', $hdr);
  364. $c->{'hdr'} .= $hdr;
  365. $c->{'vmatch'} = $h[0];
  366. $c->{'vmask'} = $h[1];
  367. $c->{'vmin'} = $h[2];
  368. $c->{'vmax'} = $h[3];
  369. } elsif ($c->{'magic'} != $FW_MAGIC[1]) {
  370. print STDERR "$0: $file: bad chunk magic\n";
  371. $err = 1;
  372. last;
  373. }
  374. my $t = $type[$c->{'type'}];
  375. my $d;
  376. if (read($fw, $d, $c->{'len'}) != $c->{'len'}) {
  377. print STDERR "$0: $file: short chunk read\n";
  378. $err = 1;
  379. last;
  380. }
  381. $c->{'data'} = $d;
  382. if ($t eq 'target') {
  383. my $is_match = match_version($target_board, $d);
  384. if ($c->{'magic'} == $FW_MAGIC[1] || $is_match) {
  385. $version_match = $c;
  386. }
  387. print STDERR "$0: $file: supports hardware: $d",
  388. ($is_match ? ' (match)' : ''), "\n";
  389. } elsif ($t eq 'end' || $t eq 'note' || ($c->{'flags'} & $FDF_PRETARGET)) {
  390. # Not filtered
  391. } else {
  392. if (!defined($version_match)) {
  393. print STDERR "$0: $file: hardware version $target_board not supported\n";
  394. $err = 1;
  395. last;
  396. }
  397. if ($c->{'vmin'} > $version_match->{'vmax'} ||
  398. $c->{'vmax'} < $version_match->{'vmin'} ||
  399. (($c->{'vmatch'} ^ $version_match->{'vmatch'}) & $c->{'vmask'})) {
  400. # Not applicable to this board
  401. next;
  402. }
  403. }
  404. push(@chunks, $c);
  405. last if ($t eq 'end'); # End of stream
  406. }
  407. close($fw);
  408. exit 1 if ($err);
  409. # Sort out the ESP chunks as files for esptool versus the ones
  410. # that should be uploaded once the ESP software is running
  411. my @espfiles;
  412. my $raw_fpgadata;
  413. my $nc = 0;
  414. foreach my $c ( @chunks ) {
  415. my $t = $type[$c->{'type'}];
  416. if ($t eq 'esptool') {
  417. my $s = $c->{'data'};
  418. $s =~ s/[\r\n]+/ /g;
  419. while ($s =~ /^\s*(\S+)\s+(\S+)(.*)/) {
  420. $espopt{$1} = $2;
  421. $s = $3;
  422. }
  423. } elsif ($t =~ /^esp/ && $c->{'addr'}) {
  424. my $addr = sprintf('%x', $c->{'addr'});
  425. my $tff = tmpfilename($t.$nc.'_'.$addr.'.bin');
  426. open(my $tf, '>', $tff) or die "$0: $tff: $!\n";
  427. print $tf $c->{'data'};
  428. close($tf);
  429. push(@espfiles, [$c->{'addr'}, $tff]);
  430. } elsif ($t eq 'note' || ($t eq 'target' && $c != $version_match)) {
  431. # Skip
  432. } else {
  433. $raw_fpgadata .= $c->{'hdr'};
  434. $raw_fpgadata .= $c->{'data'};
  435. }
  436. $nc++;
  437. }
  438. my $fpgadata;
  439. if (defined($raw_fpgadata)) {
  440. open(my $fpgafh, '>:gzip', \$fpgadata) or die;
  441. print $fpgafh $raw_fpgadata;
  442. close($fpgafh);
  443. }
  444. return ([@espfiles], $fpgadata);
  445. }
  446. sub tty_read {
  447. state %old_timeout;
  448. my($tty,$bufref,$timeout) = @_;
  449. my $d = $$bufref;
  450. if ($d eq '') {
  451. my $c;
  452. if (!defined($old_timeout{$tty}) || $timeout != $old_timeout{$tty}) {
  453. $tty->read_const_time($timeout);
  454. $old_timeout{$tty} = $timeout;
  455. }
  456. ($c,$d) = $tty->read(256);
  457. return '' if (!$c);
  458. }
  459. my $r = substr($d,0,1);
  460. $$bufref = substr($d,1);
  461. return $r;
  462. }
  463. sub tty_write($$) {
  464. my($tty,$data) = @_;
  465. my $bytes = length($data);
  466. my $offs = 0;
  467. while ($bytes) {
  468. my $cnt = $tty->write(substr($data,$offs,$bytes));
  469. usleep(10000) unless ($cnt);
  470. $offs += $cnt;
  471. $bytes -= $cnt;
  472. }
  473. return $offs;
  474. }
  475. sub upload_fpgadata($$) {
  476. my($port, $fpgadata) = @_;
  477. my $SerialPort = eval {
  478. require Device::SerialPort;
  479. Device::SerialPort->import(qw(:PARAM));
  480. 'Device::SerialPort';
  481. } || eval {
  482. require Win32::SerialPort;
  483. Win32::SerialPort->import(qw(:STAT));
  484. 'Win32::SerialPort';
  485. } || die "$0: need Device::SerialPort (Unix/MacOS) or Win32::SerialPort (Win32)\n";
  486. print STDERR "Waiting for reinit...\n";
  487. usleep(4000000);
  488. my $tty = $SerialPort->new($port);
  489. die "$0: $port: $!\n" if (!$tty);
  490. $tty->buffers($tty->buffer_max);
  491. $tty->reset_error;
  492. $tty->user_msg(1);
  493. $tty->error_msg(1);
  494. $tty->handshake('none');
  495. $tty->databits(8);
  496. $tty->baudrate(115200);
  497. $tty->stopbits(1);
  498. $tty->parity('none');
  499. $tty->stty_istrip(0);
  500. $tty->stty_inpck(0);
  501. $tty->datatype('raw');
  502. $tty->stty_icanon(0);
  503. $tty->stty_opost(0);
  504. $tty->stty_ignbrk(0);
  505. $tty->stty_inlcr(0);
  506. $tty->stty_igncr(0);
  507. $tty->stty_icrnl(0);
  508. $tty->stty_echo(0);
  509. $tty->stty_echonl(0);
  510. $tty->stty_isig(0);
  511. $tty->read_char_time(0);
  512. $tty->write_settings;
  513. # In case DTR and/or RTS was asserted on the physical serial port.
  514. # Note that DTR needs to be deasserted before RTS!
  515. # However, deasserting DTR on the ACM port prevents it from working,
  516. # so only do this if we don't see CTS (which is always enabled on ACM)...
  517. if ($tty->can_modemlines && !($tty->modemlines & $tty->MS_CTS_ON)) {
  518. usleep(100000);
  519. $tty->dtr_active(0);
  520. usleep(100000);
  521. $tty->rts_active(0);
  522. usleep(100000);
  523. }
  524. my $ttybuf = '';
  525. my $found = 0;
  526. my $tt = time();
  527. my $start_enq = $tt;
  528. tty_write($tty, "\005"); # ENQ
  529. while (($tt = time()) - $start_enq < 30) {
  530. my $d = tty_read($tty, \$ttybuf, 1000);
  531. if ($d eq '') {
  532. tty_write($tty, "\005"); # ENQ
  533. } else {
  534. my $ix = index("\026\004\027", $d);
  535. if ($ix < 0) {
  536. print STDERR $d;
  537. next;
  538. }
  539. $found = $found == $ix ? $found+1 : 0;
  540. last if ($found == 3);
  541. }
  542. }
  543. if ($found < 3) {
  544. die "$0: $port: no MAX80 ESP32 detected\n";
  545. }
  546. $start_enq = $tt;
  547. my $last_req;
  548. my $winspc;
  549. while (!defined($winspc)) {
  550. $tt = time();
  551. if ($tt - $start_enq >= 10) {
  552. die "$0: $port: failed to start FPGA firmware upload\n";
  553. }
  554. if ($tt != $last_req) {
  555. tty_write($tty, "\034\001: /// MAX80 FW UPLOAD \~\@\~ \$\r\n\035");
  556. $last_req = $tt;
  557. }
  558. my $d;
  559. while (1) {
  560. $d = tty_read($tty, \$ttybuf, 100);
  561. last if ($d eq '');
  562. my $dc = unpack('C', $d);
  563. print STDERR $a[$dc];
  564. if ($dc == 036) {
  565. $winspc = 0;
  566. last;
  567. }
  568. }
  569. }
  570. my $bytes = length($fpgadata);
  571. my $offset = 0;
  572. my $maxchunk = 64;
  573. my $maxahead = 256;
  574. my $last_ack = 0;
  575. my @pktends = ();
  576. my $last_enq = 0;
  577. my $last_ack_time = 0;
  578. print STDERR "\nStarting packet transmit...\n";
  579. while ($last_ack < $bytes) {
  580. my $chunk;
  581. my $now;
  582. while (1) {
  583. $chunk = $bytes - $offset;
  584. $chunk = $winspc if ($chunk > $winspc);
  585. if ($offset + $chunk > $last_ack + $maxahead) {
  586. $chunk = $last_ack + $maxahead - $offset;
  587. }
  588. $chunk = 0 if ($chunk <= 0);
  589. $chunk = $maxchunk if ($chunk > $maxchunk);
  590. my $d = tty_read($tty, \$ttybuf, $chunk ? 0 : $maxchunk/10);
  591. $now = time();
  592. last if ($d eq '');
  593. my $dc = unpack('C', $d);
  594. if ($dc == 022) {
  595. $winspc = 0;
  596. } elsif ($dc == 024) {
  597. if (defined($winspc)) {
  598. $winspc += 256;
  599. }
  600. } elsif ($dc == 006) {
  601. $last_ack = shift(@pktends) || $last_ack;
  602. if ($now != $last_ack_time) {
  603. printf STDERR "%s: %s: %d/%d (%d%%) uploaded\n",
  604. $0, $port, $last_ack, $bytes, $last_ack*100/$bytes;
  605. $last_ack_time = $now;
  606. }
  607. } else {
  608. print STDERR $a[$dc];
  609. if ($dc == 025 || $dc == 031 || $dc == 037) {
  610. $offset = $last_ack;
  611. @pktends = ();
  612. undef $winspc; # Wait for WRST before resuming
  613. } elsif ($dc == 030) {
  614. print STDERR "\n";
  615. die "$0: $port: upload aborted by target system\n";
  616. }
  617. }
  618. }
  619. if (!$chunk) {
  620. if ($bytes > $offset) {
  621. if ($now != $last_enq) {
  622. tty_write($tty, "\026"); # SYN: request window resync
  623. $last_enq = $now;
  624. }
  625. }
  626. next;
  627. }
  628. my $data = substr($fpgadata, $offset, $chunk);
  629. my $hdr = pack("CvVV", $chunk-1, 0, $offset, crc32($data));
  630. tty_write($tty, "\002".mybaseencode($hdr, $data));
  631. push(@pktends, $offset + $chunk);
  632. $offset += $chunk;
  633. $winspc -= $chunk;
  634. }
  635. tty_write($tty, "\004"); # EOT
  636. # Final messages out
  637. while (1) {
  638. my $d = tty_read($tty, \$ttybuf, 1000);
  639. last if ($d eq '');
  640. print STDERR $d;
  641. }
  642. $tty->close;
  643. return 0;
  644. }
  645. my @args = @ARGV;
  646. my $esponly = 0;
  647. my $file;
  648. my $target_board = undef;
  649. my $setver = 0;
  650. my $port = undef;
  651. my $which = 0;
  652. while (1) {
  653. $file = shift(@args);
  654. last if ($file !~ /^\-/);
  655. if ($file eq '--esponly') {
  656. $esponly = 1;
  657. } elsif ($file eq '--which') {
  658. $which = 1;
  659. } elsif ($file eq '--setver') {
  660. $target_board = shift(@args);
  661. $setver = defined($target_board);
  662. } elsif ($file eq '--port') {
  663. $port = shift(@args);
  664. } elsif ($file eq '--') {
  665. $file = shift(@args);
  666. last;
  667. } else {
  668. undef $file; # Invalid argument, print usage
  669. last;
  670. }
  671. }
  672. # Legacy command line support: if no --port, specify port after firmware file
  673. if (defined($file) && !defined($port) && $args[0] ne '--esptool') {
  674. $port = shift(@args);
  675. }
  676. $tmpdir = File::Temp->newdir(CLEANUP => 1);
  677. if (!defined($tmpdir)) {
  678. die "$0: failed to create temporary directory: $!\n"
  679. }
  680. my $espver = find_esptool();
  681. if (!$espver) {
  682. die "$0: cannot find esptool, please set ESPTOOL in the environment\n";
  683. }
  684. if ($which) {
  685. print "esptool ${espver}\n";
  686. print $esptool, "\n";
  687. exit 0;
  688. }
  689. print STDERR "esptool v${espver} found\n\n";
  690. if (!defined($port)) {
  691. die "Usage: $0 [--which][--esponly][--setver version][--port port]\n".
  692. " [file.fw] [--esptool esptool_options...]\n";
  693. }
  694. if (!File::Spec->file_name_is_absolute($port)) {
  695. if (-c "/dev/$port") {
  696. $port = "/dev/$port";
  697. } elsif (-c "/dev/tty$port") {
  698. $port = "/dev/tty$port";
  699. } elsif ($^O eq 'MSWin32') {
  700. $port = "\\\\.\\$port";
  701. } else {
  702. die "$0: no such serial port: $port\n";
  703. }
  704. }
  705. print STDERR "Using serial port device $port\n";
  706. %espopt = (%espopt,
  707. 'baud' => 115200, 'port' => undef, 'chip' => undef,
  708. 'flash_mode' => undef, 'flash_freq' => undef,
  709. 'flash_size' => undef);
  710. foreach my $e (keys %espopt) {
  711. my $ev = $ENV{"ESP\U$e"};
  712. if (defined($ev)) {
  713. $espopt{$e} = $ev;
  714. }
  715. }
  716. while (defined(my $eo = shift(@args))) {
  717. if ($eo =~ /^([^=]+)=(.*)$/) {
  718. $espopt{$1} = $2;
  719. } elsif ($args[0] !~ /^-/) {
  720. $espopt{$eo} = shift(@args);
  721. } else {
  722. $espopt{$eo} = '';
  723. }
  724. }
  725. my @espfiles = ();
  726. if (defined($target_board)) {
  727. # Forcibly write target board version
  728. if (!target_string_valid($target_board)) {
  729. die "$0: $port: invalid firmware target string: $target_board\n";
  730. }
  731. my $boardinfo = tmpfilename('boardinfo.bin');
  732. open(my $bi, '>:raw', $boardinfo)
  733. or die "$0: $port: $boardinfo: $!\n";
  734. my $bid = $target_board . "\0";
  735. $bid .= "\xff" x ($boardinfo_len - length($bid));
  736. print $bi $bid;
  737. close($bi);
  738. push(@espfiles, [$boardinfo_addr, $boardinfo]);
  739. } else {
  740. # Get the board version from target flash
  741. $target_board = get_target_board($port);
  742. if (!defined($target_board) || !target_string_valid($target_board)) {
  743. die "$0: $port: board version not programmed, specify with --setver\n";
  744. }
  745. }
  746. my($fwfiles, $fpgadata) = read_fwfile($file, $target_board);
  747. push(@espfiles, @$fwfiles);
  748. if (scalar(@espfiles)) {
  749. run_esptool($port, { hgrep {!/^flash_/} %espopt },
  750. 'write_flash', { hgrep {/^flash_/} %espopt },
  751. '-z', map { (sprintf('0x%x', $_->[0]), $_->[1]) } @espfiles);
  752. }
  753. if (!$esponly && defined($fpgadata)) {
  754. upload_fpgadata($port, $fpgadata);
  755. }
  756. print STDERR "\n$0: $port: update complete\n";
  757. exit 0;