1+ import { SerialPort } from 'serialport/dist/index.d' ;
2+ import { ProgramConfig } from '../index.d' ;
3+ import ESPLoader , { ESPOptions , UploadFileDef } from './loader' ;
4+ import asyncTimeout from '../util/async-timeout' ;
5+
6+ const isSupported = ( cpu : string ) => [ 'esp8266' , 'esp32' ] . includes ( cpu ) ;
7+
8+ export const upload = async ( serial : SerialPort , config : ProgramConfig ) => {
9+ if ( ! config . files ?. length ) throw new Error ( 'No files to upload' ) ;
10+ // const log = (...args) => config.debug(`${args.join(' ')}\r\n`);
11+ const log = ( ...args : any [ ] ) => console . log ( ...args ) ;
12+ // const term = { log, debug: log, write: config.debug };
13+
14+ // serial.on('data', (data: Buffer) => {
15+ // console.log('read (utf8)', data.toString('utf-8'));
16+ // console.log('read (hex)', data.toString('hex'));
17+ // });
18+
19+ let espLoader ;
20+ try {
21+ espLoader = new ESPLoader ( serial , {
22+ quiet : ! config . verbose ,
23+ } as ESPOptions ) ;
24+ await espLoader . mainFn ( ) ;
25+ // await espLoader.flash_id();
26+ log ( '> Connected' ) ;
27+
28+ if ( config . uploadSpeed ) {
29+ await espLoader . changeBaudrate ( config . uploadSpeed ) ;
30+ }
31+ } catch ( err ) {
32+ // eslint-disable-next-line no-console
33+ console . error ( err ) ;
34+ try {
35+ await serial . close ( ) ;
36+ } catch ( err2 ) {
37+ // eslint-disable-next-line no-console
38+ console . error ( err2 ) ;
39+ }
40+ return ;
41+ }
42+
43+ try {
44+ log ( '> Writing main data partition, this may take a while...' ) ;
45+ await espLoader . writeFlash ( {
46+ fileArray : config . files . map ( ( file ) => ( { ...file , data : Buffer . from ( file . data , 'base64' ) } ) ) ,
47+ flashSize : '4MB' ,
48+ flashFreq : config . flashFreq || 'keep' ,
49+ flashMode : config . flashMode || 'keep' ,
50+ // compress: board.props?.build?.mcu !== 'esp8266',
51+ } ) ;
52+ await espLoader . reboot ( ) ;
53+ await asyncTimeout ( 100 ) ;
54+ if ( config . uploadSpeed ) {
55+ await serial . update ( { baudRate : config . speed || 115200 } ) ;
56+ }
57+ log ( '> Successfully written data partition' ) ;
58+ log ( '> Flashing succeeded! Have a nice day! :)' ) ;
59+ } catch ( err ) {
60+ // eslint-disable-next-line no-console
61+ console . error ( err ) ;
62+ log ( 'Failed to upload:' , err instanceof Error ? err . message : err ) ;
63+ }
64+
65+ } ;
66+
67+ export default { upload, isSupported } ;
0 commit comments