flashmax.pl 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541
  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 = ($^O eq 'MSWin32') ? 'esptool.exe' : 'esptool.py';
  11. $esptool = $ENV{'ESPTOOL'} || $esptool;
  12. my $esp_retries = 5;
  13. my $FW_MAGIC = 0x7a07fbd6;
  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 $STRING_MAX_LEN = 4095;
  32. # For debug; DC1-4 replaced with functional names
  33. my @ascii = qw(NUL SOH STX ETX EOT ENQ ACK BEL BS HT LF VT FF CR SO SI
  34. DLE XON WRST XOFF WGO NAK SYN ETB CAN EM SUB ESC FS GS RS US);
  35. foreach my $i (9, 10, 13, 32..126) {
  36. $ascii[$i] = chr($i);
  37. }
  38. $ascii[127] = 'DEL';
  39. for (my $i = 128; $i < 256; $i++) {
  40. $ascii[$i] = sprintf("%02X", $i);
  41. }
  42. my @a = map { length($_) == 1 ? $_ : '<'.$_.'>' } @ascii;
  43. # Simple base64 encode using 3F-7E, bytewise bigendian
  44. sub mybaseencode {
  45. my $nbits = 0;
  46. my $bitbuf = 0;
  47. my $out = '';
  48. foreach my $s (@_) {
  49. foreach my $c (unpack('C*', $s)) {
  50. $nbits += 8;
  51. $bitbuf = ($bitbuf << 8) + $c;
  52. while ($nbits >= 6) {
  53. $nbits -= 6;
  54. $out .= pack('C', 63 + (($bitbuf >> $nbits) & 63));
  55. }
  56. }
  57. }
  58. if ($nbits) {
  59. $out .= pack('C', 63 + ($bitbuf & ((1 << $nbits) - 1)));
  60. }
  61. return $out;
  62. }
  63. sub getint($) {
  64. my($s) = @_;
  65. return undef
  66. unless ($s =~ /^(([1-9][0-9]+)|(0(x[0-9a-f]+|[0-7]*)))([kmgtpe]?)$/i);
  67. my $o = oct($3) + $2;
  68. my $p = lc($5);
  69. if ($p eq 'k') {
  70. $o <<= 10;
  71. } elsif ($p eq 'm') {
  72. $o <<= 20;
  73. } elsif ($p eq 'g') {
  74. $o <<= 30;
  75. } elsif ($p eq 't') {
  76. $o <<= 40;
  77. } elsif ($p eq 'p') {
  78. $o <<= 50;
  79. } elsif ($p eq 'e') {
  80. $o <<= 60;
  81. }
  82. return $o;
  83. }
  84. sub filelen($) {
  85. my($f) = @_;
  86. my @s = stat($f);
  87. return $s[7];
  88. }
  89. sub unquote_cmd($) {
  90. my($s) = @_;
  91. my @a;
  92. $s =~ s/[\r\n]+/ /g;
  93. while ($s =~ /^\s*(?:\"((?:[^\"]+|\"\")*)\"|(\S+))(\s.*)?$/) {
  94. push(@a, $1.$2);
  95. $s = $3;
  96. }
  97. return @a;
  98. }
  99. # Similar to grep, but for a hash; also filters out
  100. sub hgrep(&%) {
  101. my($mfunc, %hash) = @_;
  102. return map { $_ => $hash{$_} } grep(&$mfunc, keys %hash);
  103. }
  104. # Wrapper for running esptool, returns a hash with info output
  105. # or dies on failure
  106. sub hash2opt($)
  107. {
  108. my($h) = @_;
  109. return () unless (defined($h));
  110. return map { $h->{$_} ne '' ? ('--'.$_, $h->{$_}) : () } sort keys %{$h};
  111. }
  112. sub run_esptool($$$$@)
  113. {
  114. my($port,$common_options,$cmd,$cmd_options,@args) = @_;
  115. my @espcmd = unquote_cmd($esptool);
  116. push(@espcmd, '--port', $port);
  117. push(@espcmd, hash2opt($common_options));
  118. push(@espcmd, unquote_cmd($cmd));
  119. push(@espcmd, hash2opt($cmd_options));
  120. push(@espcmd, @args);
  121. my $retries = $esp_retries;
  122. my $ok = 0;
  123. my %outinfo;
  124. my @output;
  125. while (!$ok && $retries--) {
  126. %outinfo = ();
  127. @output = ();
  128. print STDERR 'Command: ', join(' ', @espcmd), "\n";
  129. print STDERR "Running $espcmd[0] $cmd... ";
  130. my $esp;
  131. if (!open($esp, '-|', @espcmd)) {
  132. print STDERR $!, "\n";
  133. exit 1;
  134. }
  135. while (defined(my $l = <$esp>)) {
  136. if ($l =~ /^Chip is (\S+)/) {
  137. $outinfo{'chip'} = $1;
  138. } elsif ($l =~ /^MAC: ([0-9a-f:]+)/) {
  139. $outinfo{'mac'} = $1;
  140. }
  141. push(@output, $l);
  142. }
  143. $ok = close($esp);
  144. if ($ok) {
  145. print STDERR "ok\n";
  146. last;
  147. } elsif ($retries) {
  148. print STDERR "failed, retrying\n";
  149. usleep(1000000);
  150. } else {
  151. print STDERR "failed, giving up\n";
  152. }
  153. }
  154. print STDERR @output;
  155. die "$0: $espcmd[0] $cmd failed\n" unless ($ok);
  156. return %outinfo;
  157. }
  158. my @args = @ARGV;
  159. my $esponly = 0;
  160. my $file;
  161. while (1) {
  162. $file = shift(@args);
  163. last if ($file !~ /^\-/);
  164. if ($file eq '--esponly') {
  165. $esponly = 1;
  166. } elsif ($file eq '--') {
  167. $file = shift(@args);
  168. last;
  169. } else {
  170. undef $file; # Invalid argument, print usage
  171. last;
  172. }
  173. }
  174. my $port = shift(@args);
  175. if (!defined($port)) {
  176. die "Usage: $0 file.fw port [esptool options...]\n";
  177. }
  178. if (!File::Spec->file_name_is_absolute($port)) {
  179. if (-c "/dev/$port") {
  180. $port = "/dev/$port";
  181. } elsif (-c "/dev/tty$port") {
  182. $port = "/dev/tty$port";
  183. } elsif ($^O eq 'MSWin32') {
  184. $port = "\\\\.\\$port";
  185. } else {
  186. die "$0: no such serial port: $port\n";
  187. }
  188. }
  189. print STDERR "Using serial port device $port\n";
  190. open(my $fw, '<:gzip', $file)
  191. or die "$0: $file: $!\n";
  192. my @chunks = ();
  193. my $err = 0;
  194. my $hdr;
  195. while (read($fw, $hdr, 16) == 16) {
  196. # magic type flags data_len addr
  197. my @h = unpack('VvvVV', $hdr);
  198. my $c = { 'hdr' => $hdr, 'magic' => $h[0], 'type' => $h[1],
  199. 'flags' => $h[2], 'len' => $h[3], 'addr' => $h[4] };
  200. if ($c->{'magic'} != $FW_MAGIC) {
  201. print STDERR "$0: $file: bad chunk magic\n";
  202. $err = 1;
  203. last;
  204. }
  205. my $t = $type[$c->{'type'}];
  206. my $d;
  207. if (read($fw, $d, $c->{'len'}) != $c->{'len'}) {
  208. print STDERR "$0: $file: short chunk read\n";
  209. $err = 1;
  210. last;
  211. }
  212. $c->{'data'} = $d;
  213. push(@chunks, $c);
  214. last if ($t eq 'end'); # End of stream
  215. }
  216. close($fw);
  217. exit $err if ($err);
  218. my $td = File::Temp->newdir(CLEANUP => 1);
  219. my @espfiles = ();
  220. my %espopt = ('before' => 'default_reset', 'after' => 'hard_reset',
  221. 'baud' => 115200, 'port' => undef, 'chip' => undef,
  222. 'flash_mode' => undef, 'flash_freq' => undef,
  223. 'flash_size' => undef);
  224. # Create a compressed data buffer without the ESP32 chunks
  225. my $fpgadata;
  226. open(my $fpgafh, '>:gzip', \$fpgadata) or die;
  227. my $nc = 0;
  228. foreach my $c ( @chunks ) {
  229. my $t = $type[$c->{'type'}];
  230. if ($t eq 'esptool') {
  231. my $s = $c->{'data'};
  232. $s =~ s/[\r\n]+/ /g;
  233. while ($s =~ /^\s*(\S+)\s+(\S+)(.*)/) {
  234. $espopt{$1} = $2;
  235. $s = $3;
  236. }
  237. } elsif ($t =~ /^esp/ && $c->{'addr'}) {
  238. my $addr = sprintf('%x', $c->{'addr'});
  239. my $tff = File::Spec->catfile($td, $t.$nc.'_'.$addr.'.bin');
  240. open(my $tf, '>', $tff) or die "$0: $tff: $!\n";
  241. print $tf $c->{'data'};
  242. close($tf);
  243. push(@espfiles, '0x'.$addr, $tff);
  244. } else {
  245. print $fpgafh $c->{'hdr'};
  246. print $fpgafh $c->{'data'};
  247. }
  248. $nc++;
  249. }
  250. close($fpgafh);
  251. foreach my $e (keys %espopt) {
  252. my $ev = $ENV{"ESP\U$e"};
  253. if (defined($ev)) {
  254. $espopt{$e} = $ev;
  255. }
  256. }
  257. run_esptool($port, { hgrep sub {!/^flash_/}, %espopt },
  258. 'write_flash', { hgrep sub {/^flash_/}, %espopt },
  259. '-z', @espfiles);
  260. my $SerialPort = eval {
  261. require Device::SerialPort;
  262. Device::SerialPort->import(qw(:PARAM));
  263. 'Device::SerialPort';
  264. } || eval {
  265. require Win32::SerialPort;
  266. Win32::SerialPort->import(qw(:STAT));
  267. 'Win32::SerialPort';
  268. } || die "$0: need Device::SerialPort or Win32::SerialPort\n";
  269. print STDERR "Waiting for reinit...\n";
  270. usleep(4000000);
  271. my $tty = $SerialPort->new($port);
  272. die "$0: $port: $!\n" if (!$tty);
  273. $tty->buffers($tty->buffer_max);
  274. $tty->reset_error;
  275. $tty->user_msg(1);
  276. $tty->error_msg(1);
  277. $tty->handshake('none');
  278. $tty->databits(8);
  279. $tty->baudrate(115200);
  280. $tty->stopbits(1);
  281. $tty->parity('none');
  282. $tty->stty_istrip(0);
  283. $tty->stty_inpck(0);
  284. $tty->datatype('raw');
  285. $tty->stty_icanon(0);
  286. $tty->stty_opost(0);
  287. $tty->stty_ignbrk(0);
  288. $tty->stty_inlcr(0);
  289. $tty->stty_igncr(0);
  290. $tty->stty_icrnl(0);
  291. $tty->stty_echo(0);
  292. $tty->stty_echonl(0);
  293. $tty->stty_isig(0);
  294. $tty->read_char_time(0);
  295. $tty->write_settings;
  296. # In case DTR and/or RTS was asserted on the physical serial port.
  297. # Note that DTR needs to be deasserted before RTS!
  298. # However, deasserting DTR on the ACM port prevents it from working,
  299. # so only do this if we don't see CTS (which is always enabled on ACM)...
  300. if ($tty->can_modemlines && !($tty->modemlines & $tty->MS_CTS_ON)) {
  301. usleep(100000);
  302. $tty->dtr_active(0);
  303. usleep(100000);
  304. $tty->rts_active(0);
  305. usleep(100000);
  306. }
  307. sub tty_read {
  308. state %old_timeout;
  309. my($tty,$bufref,$timeout) = @_;
  310. my $d = $$bufref;
  311. if ($d eq '') {
  312. my $c;
  313. if (!defined($old_timeout{$tty}) || $timeout != $old_timeout{$tty}) {
  314. $tty->read_const_time($timeout);
  315. $old_timeout{$tty} = $timeout;
  316. }
  317. ($c,$d) = $tty->read(256);
  318. return '' if (!$c);
  319. }
  320. my $r = substr($d,0,1);
  321. $$bufref = substr($d,1);
  322. return $r;
  323. }
  324. my $ttybuf = '';
  325. sub tty_write($$) {
  326. my($tty,$data) = @_;
  327. my $bytes = length($data);
  328. my $offs = 0;
  329. while ($bytes) {
  330. my $cnt = $tty->write(substr($data,$offs,$bytes));
  331. usleep(10000) unless ($cnt);
  332. $offs += $cnt;
  333. $bytes -= $cnt;
  334. }
  335. return $offs;
  336. }
  337. my $found = 0;
  338. my $tt = time();
  339. my $start_enq = $tt;
  340. tty_write($tty, "\005"); # ENQ
  341. while (($tt = time()) - $start_enq < 30) {
  342. my $d = tty_read($tty, \$ttybuf, 1000);
  343. if ($d eq '') {
  344. tty_write($tty, "\005"); # ENQ
  345. } else {
  346. my $ix = index("\026\004\027", $d);
  347. if ($ix < 0) {
  348. print STDERR $d;
  349. next;
  350. }
  351. $found = $found == $ix ? $found+1 : 0;
  352. last if ($found == 3);
  353. }
  354. }
  355. if ($found < 3) {
  356. die "$0: $port: no MAX80 ESP32 detected\n";
  357. }
  358. $start_enq = $tt;
  359. my $last_req;
  360. my $winspc;
  361. while (!defined($winspc)) {
  362. $tt = time();
  363. if ($tt - $start_enq >= 10) {
  364. die "$0: $port: failed to start FPGA firmware upload\n";
  365. }
  366. if ($tt != $last_req) {
  367. tty_write($tty, "\034\001: /// MAX80 FW UPLOAD \~\@\~ \$\r\n\035");
  368. $last_req = $tt;
  369. }
  370. my $d;
  371. while (1) {
  372. $d = tty_read($tty, \$ttybuf, 100);
  373. last if ($d eq '');
  374. my $dc = unpack('C', $d);
  375. print STDERR $a[$dc];
  376. if ($dc == 036) {
  377. $winspc = 0;
  378. last;
  379. }
  380. }
  381. }
  382. my $bytes = length($fpgadata);
  383. my $offset = 0;
  384. my $maxchunk = 64;
  385. my $maxahead = 256;
  386. my $last_ack = 0;
  387. my @pktends = ();
  388. my $last_enq = 0;
  389. my $last_ack_time = 0;
  390. print STDERR "\nStarting packet transmit...\n";
  391. while ($last_ack < $bytes) {
  392. my $chunk;
  393. my $now;
  394. while (1) {
  395. $chunk = $bytes - $offset;
  396. $chunk = $winspc if ($chunk > $winspc);
  397. if ($offset + $chunk > $last_ack + $maxahead) {
  398. $chunk = $last_ack + $maxahead - $offset;
  399. }
  400. $chunk = 0 if ($chunk <= 0);
  401. $chunk = $maxchunk if ($chunk > $maxchunk);
  402. my $d = tty_read($tty, \$ttybuf, $chunk ? 0 : $maxchunk/10);
  403. $now = time();
  404. last if ($d eq '');
  405. my $dc = unpack('C', $d);
  406. if ($dc == 022) {
  407. $winspc = 0;
  408. } elsif ($dc == 024) {
  409. if (defined($winspc)) {
  410. $winspc += 256;
  411. }
  412. } elsif ($dc == 006) {
  413. $last_ack = shift(@pktends) || $last_ack;
  414. if ($now != $last_ack_time) {
  415. printf STDERR "%s: %s: %d/%d (%d%%) uploaded\n",
  416. $0, $port, $last_ack, $bytes, $last_ack*100/$bytes;
  417. $last_ack_time = $now;
  418. }
  419. } else {
  420. print STDERR $a[$dc];
  421. if ($dc == 025 || $dc == 031 || $dc == 037) {
  422. $offset = $last_ack;
  423. @pktends = ();
  424. undef $winspc; # Wait for WRST before resuming
  425. } elsif ($dc == 030) {
  426. print STDERR "\n";
  427. die "$0: $port: upload aborted by target system\n";
  428. }
  429. }
  430. }
  431. if (!$chunk) {
  432. if ($bytes > $offset) {
  433. if ($now != $last_enq) {
  434. tty_write($tty, "\026"); # SYN: request window resync
  435. $last_enq = $now;
  436. }
  437. }
  438. next;
  439. }
  440. my $data = substr($fpgadata, $offset, $chunk);
  441. my $hdr = pack("CvVV", $chunk-1, 0, $offset, crc32($data));
  442. tty_write($tty, "\002".mybaseencode($hdr, $data));
  443. push(@pktends, $offset + $chunk);
  444. $offset += $chunk;
  445. $winspc -= $chunk;
  446. }
  447. tty_write($tty, "\004"); # EOT
  448. # Final messages out
  449. while (1) {
  450. my $d = tty_read($tty, \$ttybuf, 1000);
  451. last if ($d eq '');
  452. print STDERR $d;
  453. }
  454. $tty->close;
  455. print STDERR "\n$0: $port: firmware upload complete\n";
  456. exit 0;