
    ;)di]_                       d dl Z d dlZd dlZd dlZd dlZd dlZd dlZd dlZd dlm	Z	 d dl
mZ d dlmZ ddlmZmZ ddlmZmZmZ ddlmZmZmZmZmZ dd	lmZ dd
lmZmZmZ ddl m!Z! ddl"m#Z#m$Z$m%Z%m&Z& ddl"m'Z'm(Z(m)Z)m*Z*m+Z+m,Z,m-Z-m.Z. dZ/dZ0dddddddZ1i dddddddddddddddd d!d"d#d$d%d&dd"d'd$d(d&d)dd*dd+dddddd d"d,Z2d dd-d.d/Z3ej4        ej5        d0d1efd2e6d3e7d4e6d5e8d6e7d7efd8Z9d9ed:e*d7dfd;Z:d9ed<e7d7dfd=Z;dvd9ed<e7d?e7d@e7d7df
dAZ<	 dwd9ed<e7dBe7dCe6dz  d7e=dz  f
dDZ>dxd9edFe8d7e?e7e7e6dz  f         fdGZ@d9ed7e6dz  fdHZAdI ZB	 	 	 dyd9edKeCe?e7e*f                  dLe6dMe6dNe6d7dfdOZDd9ed7dfdPZEd9ed7dfdQZF	 dwd9edRe?e7e7e7e7e7f         e6z  dz  d7dfdSZGdzdTZHd{d9edUe8d7dfdVZId{d9ed<e7dBe7dUe8d7df
dWZJd9ed7dfdXZKd9ed7dfdYZLd9ed7dfdZZMd|d9ed<e7d[e7d7dfd\ZN	 	 	 d}d9ed<e7dBe7dCe6dz  dNe6d]e8d7e=dz  fd^ZO	 	 	 	 d~d9edKeCe?e7e*f                  dLe6dMe6dNe6d_e8d7dfd`ZPdd9ed[e7d7dfdaZQ	 dd9ed?e7d[e7dbe8d7df
dcZRd9ed7dfddZSdd9edfe6d7dfdgZTd9ed7efdhZUdi ZVdj ZW	 dwd:e*eCe?e7e*f                  z  dke6dz  d7dfdlZXdwdme=dke6dz  d7e6fdnZYdke6dme=d7dfdoZZ	 	 	 	 	 ddKeCe?e7e*f                  dke6dCe6dz  dLe6dMe6dNe6dqe6d7e=dz  fdrZ[	 	 	 	 dd:e*dke6dCe6dz  dLe6dz  dMe6dNe6d7e=e?e=dz  e=f         z  dz  fdtZ\dduZ]dS )    N)IntelHex)SerialException)cast   )ELFFileLoadFirmwareImage)ESP8266ROMFirmwareImageESP8266V2FirmwareImageESP8266V3FirmwareImage)DEFAULT_CONNECT_ATTEMPTSDEFAULT_TIMEOUTERASE_WRITE_TIMEOUT_PER_MB	ESPLoadertimeout_per_mb)log)	CHIP_DEFS	CHIP_LISTROM_LIST)	UF2Writer)
FatalErrorNotImplementedInROMErrorNotSupportedErrorUnsupportedCommandError)div_roundupflash_size_byteshexifyImageSource	get_bytesget_key_from_valuepad_tosanitize_string       512KB1MB2MB4MB8MB16MB)               	      256KB                     32MB   64MB   128MB   256MB!   "   2   3   4   )5   6   7   8   9   :         )qioqoutdiodoutzdefault-resetFportbaudconnect_modetrace_enabledconnect_attemptsreturnc                 8   d}t          | ||          j                            d          rd_                            ||d           dt           dt           ffd}	 	 t          j        d	d
d                                           }t          D ]p}|j	        r
||j
        k    r[ |j        ||          }|                                }	|	d         d         |_         ||          }|                                  nqd| d}
nv# t          t           f$ ra 	                     t           j                  }n# t          $ rj t'          d         j        ||          }|                                }	|	d         d         |_         ||          }|                                 |cY cY S t           $ rf t          j        d                               ||dd           t          j        d	d
d                               t           j                  }Y nw xY wt          D ]I}|j	        s
||j        k    r4 |j        ||          } ||          }|                                  nJd|dd}
Y nw xY w||S t!          |
 d          )a  
    Detect the type of ESP device connected via serial,
    connect to it, and return an active ESPLoader object.

    Args:
        port: The serial port to use for communication.
        baud: The baud rate for serial communication.
        connect_mode: The chip reset method to perform when connecting to the ESP device
            (``"default-reset"``, ``"usb-reset"``,
            ``"no-reset"``, ``"no-reset-no-sync"``)
        trace_enabled: Enables or disables tracing for debugging purposes.
        connect_attempts: Number of connection attempts before failing.

    Returns:
        An initialized instance of the detected chip class ready for use.
    N)rT   zrfc2217:T)	detectinginstancerV   c                     t          j        d| j                    j        r#| j        |                     |           } d| _        | S )N T)r   print	CHIP_NAMEsync_stub_detected
STUB_CLASS)rY   detect_ports    S/var/www/menimich/repos/protonApp/venv/lib/python3.11/site-packages/esptool/cmds.pycheck_if_stubz"detect_chip.<locals>.check_if_stub   sR    	*h(**+++) 	/h.A.M**844H*.H'    zDetecting chip type... endflushparsed_flagsSECURE_DOWNLOAD_ENABLEzUnexpected chip ID value .esp32s2z& Autodetection failed, trying again...F)rX   warningszUnexpected chip magic value #010xzW Failed to autodetect chip type.
Probably it is unsupported by this version of esptool.)r   serial_port
startswithUSES_RFC2217connectr   r\   get_chip_idr   USES_MAGIC_VALUEIMAGE_CHIP_ID_portget_security_infosecure_download_mode_post_connectr   r   read_regCHIP_DETECT_MAGIC_REG_ADDRr   MAGIC_VALUE)rQ   rR   rS   rT   rU   instrb   chip_idclssierr_msgchip_magic_valuer`   s               @ra   detect_chipr   e   s   . DD$mDDDK))*55 (#' &6$GGG	 i      5O	*$????))++ 	= 	=C# #+++s;,d-PPP++--,.~,>?W,X)$}T**""$$$ , ='<<<G#Z0 %O %O %O	*334    ' 
	 
	 
	 Y'!4}  D ''))B(*>(:;S(TD% =&&D   KKKKK 	 	 	I>???.$      I.BdCCCC*334   	  		O 		OC' 3?22s;,d-PPP$}T**""$$$	 3 O5ENNNNGK%ON 
 	C 	C 	C  sF   %B)D J#EJA/H%2J6A,H%"J$H%%AJJespinputc           
         t          |          \  }}t          | j        |          }t          j                     |dnd| d}t          j        d| d           t          |j        d          D ]\  }}t          |j	                  }t          j
        |t          |j                  d| d	|j        d
dd           |                     |t          || j                  | j        |j                   d}t          |j	                  dk    r^|                     |j	        d| j                 |           |j	        | j        d         |_	        |dz  }t          |j	                  dk    ^t          j        d           t          j        dt          |j                   d| d|j        d
d           |                     |j                   dS )a  
    Load a firmware image into RAM and execute it on the ESP device.

    Args:
        esp: Initiated esp object connected to a real device.
        input: Path to the firmware image file, opened file-like object,
            or the image data as bytes.
    Nimage'zLoading z
 to RAM...r   )startzDownloading 
 bytes at rm   r[   ...cur_itertotal_itersprefixsuffixr   TfinishzLoaded z segments from z to RAM, executing at rj   )r   r   r]   r   stager\   	enumeratesegmentslendataprogress_baraddr	mem_beginr   ESP_RAM_BLOCK	mem_block
entrypoint
mem_finish)	r   r   r   sourcer   isegsizeseqs	            ra   load_ramr      s    U##LD&cmT22EIKKKWWMMMMFI++++,,,EN!444  338}}EN++C$CC#(CCCC		
 	
 	
 	
 	+dC$5668I38	
 	
 	
 #(mmaMM#(1s'8#893???x 1 3 34CH1HC #(mma ITI	2#en%% 	2 	2f 	2 	2(1	2 	2 	2   NN5#$$$$$rc   addressc                 b    t          j        |dd|                     |          d           dS )z
    Read and display a 32-bit value from a memory address on the ESP device.

    Args:
        esp: Initiated esp object connected to a real device.
        address: Memory address to read from (32-bit aligned).
    rm   z = N)r   r\   ry   )r   r   s     ra   read_memr      s:     I@@@3<<#8#8@@@AAAAArc       valuemaskc           	      x    |                      |||d           t          j        d|dd|dd|dd           dS )aS  
    Write a 32-bit value to a memory address on the ESP device with optional bitmask.

    Args:
        esp: Initiated esp object connected to a real device.
        address: Memory address to write to (32-bit aligned).
        value: 32-bit value to write.
        mask: Bitmask specifying which bits to modify (default: all bits).
    r   Wrote rm   z with mask z to rj   N)	write_regr   r\   )r   r   r   r   s       ra   	write_memr     sW     MM'5$***IOuOOOtOOOwOOOOPPPPPrc   r   outputc                 <   t          j                    }t          j                     t          j        d| d|d|rd| dndz              t          j                    }t          |dz            D ]}||dz  z   }|                     |          }|                    t          j
        d|                     |                                }	|	d	z  d
k    s|	|k    r6t          j        |                                |d|ddd|	 d| d           t          j                    |z
  }|dk    r0d                    |                                |z  dz  dz            nd}
|rd| dnd}t          j        d           t          j        d|                                 d|dd|dd|
 | d
           |rQt          |d          5 }|                    |                                           ddd           n# 1 swxY w Y   dS |                                S ) a  
    Dump a block of memory from the ESP device.

    Args:
        esp: Initiated esp object connected to a real device.
        address: Starting memory address to dump from.
        size: Number of bytes to dump.
        output: Path to output file for binary data. If None, returns the data.

    Returns:
        Memory dump as bytes if output is None;
        otherwise, returns None after writing to file.
    zDumping  bytes from rm   z
 to file 'z'...r   r*   z<I   r   zDumping from r[   /	 bytes...r            ({:.1f} kbit/s)r.     rd    to 'r   Tr   zDumped  in .1f secondsrj   wbN)ioBytesIOr   r   r\   timerangery   writestructpacktellr   formatopengetvalue)r   r   r   r   r   tr   cur_addrdcur	speed_msgdest_msgfs                ra   dump_memr     s     :<<DIKKKI4444W444(.9$$$$$E	;   		A419  a!e$LL""

6;tQ''(((iikk:??cTkk 8x88880300000	    		aAIJS"))$))++/A*=*DEEEVXI$*2 v    HITI	"$))++ 	" 	"7M 	" 	"aM 	" 	"	"	" 	" 	"    &$ 	%1GGDMMOO$$$	% 	% 	% 	% 	% 	% 	% 	% 	% 	% 	% 	% 	% 	% 	%t}}s   	(G==HHTcachec                    |                      |          }|dz  }|dz	  dz  |dz	  dz  dz  z  }|t          k    r#|dz	  dz  }t                              |          }n|dz	  }t                              |          }|||fS )a5  
    Get the flash memory chip information including vendor ID, device ID, and
    flash size.

    Args:
        esp: Initiated esp object connected to a real device.
        cache: Whether to use cached flash ID (default: True).

    Returns:
        Tuple containing (vendor_id, device_id, flash_size)
    )r         r.   r"   )flash_idADESTO_VENDOR_IDDETECTED_FLASH_SIZES_ADESTOgetDETECTED_FLASH_SIZES)r   r   r   	vendor_id	device_idsize_id
flash_sizes          ra   _get_flash_infor   J  s     ||%|((H4Ib.D(h!mt-C,III$$$q=D(044W==

b.)--g66
i++rc   c                 X    | j         rt          d          t          |           \  }}}|S )z
    Detect the flash size of the connected ESP device.

    Args:
        esp: Initiated esp object connected to a real device.

    Returns:
        Detected flash size in bytes, or None if unrecognized.
    zcDetecting flash size is not supported in secure download mode. Need to manually specify flash size.)rw   r   r   )r   _r   s      ra   detect_flash_sizer   f  sB      
3
 
 	
 's++Aq*rc   c                    t          |          dk     r|S || j        k    r|S |||fdk    r|S t          j        d|dd                   \  }}}}	|| j        k    rt          j        d|dd           |S 	 |                     t          j	        |                    }
|

                                 n3# t          $ r& t          j        d|dd	| j         d
           |cY S w xY w| j        dk    o|d         dk    }|dk    rt          |         }|	dz  }|dk    r|                     |          }|	dz  }|dk    r|                     |          }t          j        d|||z             }||dd         k    rJt          j        dt          j        d|          d         dd           |dd         |z   |dd         z   }|r|                     t          j	        |                    }|d|j                 }||j        |j        z   d         }t)          j        |                                          }t/          t1          j        |||                    }||j        |j        |j        z            }t5          |          t5          |          k    rt          j        d           n4t          j        dt5          |           dt5          |                      |S )a  
    Update the flash mode, size, and freq parameters in a bootloader image,
    if applicable.

    Args:
        esp (ESPLoader): ESPLoader object that provides device-specific attributes
            (e.g., BOOTLOADER_FLASH_OFFSET, ESP_IMAGE_MAGIC, CHIP_NAME) and methods for
            image verification and parameter parsing.
        address (int): The flash memory address where the image is to be written.
        flash_freq (str, optional): Flash frequency setting
            (``"keep"`` to retain current).
        flash_mode (str, optional): Flash mode setting
            (``"keep"`` to retain current).
        flash_size (str, optional): Flash size setting
            (``"keep"`` to retain current).
        image (bytes): The image data that may contain an executable bootloader image.

    Returns:
        bytes: The modified image data with updated flash parameters
            (and recalculated SHA256 digest, if applicable),
            or the original image if no modifications were performed.
    r.   keepr   r   BBBBNr*   zImage file at #xzE doesn't look like an image file, so not changing any flash settings.z is not a valid z+ image, so not changing any flash settings.esp8266r6   r   r         s   BBrK   zFlash parameters set to z>Hr   #06xrj   zSHA digest in image updated.z?SHA recalculation for binary failed!
	Expected calculated SHA: z
	SHA stored in binary:    )r   BOOTLOADER_FLASH_OFFSETr   unpackESP_IMAGE_MAGICr   warningBOOTLOADER_IMAGEr   r   verify	Exceptionr]   FLASH_MODESparse_flash_freq_argparse_flash_size_argr   r\   data_lengthSHA256_DIGEST_LENhashlibsha256digestbytes	itertoolschainr   )r   r   
flash_freq
flash_moder   r   magicr   img_flash_modeimg_flash_size_freq
test_imagesha_appendedimg_flash_freqimg_flash_sizeflash_paramsimage_objectimage_data_before_shaimage_data_after_shasha_digest_calculatedimage_stored_shas                       ra   _update_image_flash_paramsr
  y  s   . 5zzA~~#---J
+}<< 5;M&%PRQRPR)4T4T1E1n1 ###2WK 2 2 2	
 	
 	
 
))"*U*;*;<<
   3WO 3 3 3 3 3	
 	
 	
  =I-D%-12DLV$Z0(4/NV11*==(4/NV11*==;unn~6UVVLuQqSz!!	Sv}T<'H'H'KSSSS	
 	
 	
 ac
\)E!""I5    ++BJu,=,=>> %&@(@&@ A$%(FFII 
 !(/D E E L L N NO%'<>R 
 
 !$|'?,(- -

 '((F3C,D,DDDI45555KI.45J.K.KI I.45E.F.FI I   Ls   7;B3 3-C#"C#r   	addr_datar   r   r   c                 T  7 d |D             }|                     dd          }|                     dd          7|                     dd          }|                     dd          }	|                     dd          }
|                     d	d          }|                     d
d          }|                     dd          }|	s	|
s| j        }	|s| j        dk    r| j        s|                                 r|D ]\  }}|dk     rt          d          |D ]\  }\  }}	 t          | j        |          }n"# t
          t          j        t          f$ r Y >w xY w|j
        | j        k    r$|dnd| d}t          | d| j         d          |j        dk    rd}n(|j        dk    rd}|j        dk    r|j        dk    rd}nd}|r|                                 }||j        k     s||j        k    rsd| d}|d|j        dz   d|j        dz   dz  }|j        dk    r|dz  }n|d|j        dz   d|j        dz   dz  }|d|dz   d|dz   d z  }t          | d!          M| j        d"k    r|                                 }n|                                 }||j        k     rt          d| d#|j         d$| d%          7s|d}| j        s|                                 rt          d&          |                                 }| |d'k    rt)          j        d(|d)           d}|                                 }|st)          j        d*           d}7|nd+ |D             }|D|D ]A\  }\  }}|| j        z  r/|d,nd| d}t)          j        | d-|d)d.| j         d/           d}B|s|st          d0          n|s| j        dk    r| j        d1k    rW| j        rPt3          |                                 d2                                       d3          d4z  dk    rt          d5          | j        s7|                                 r#|                                 rt          d6          t;          | |          }|d7vrt=          |          nd}| j        r|}nCt?          |           }t=          |          }|r#|r!||k    rt)          j        d8| d9| d           |r|rtA          ||          n|}|T|D ]Q\  }\  }}|tC          |          z   |k    r3|d,nd:| d}t          | d;tC          |           d<|d=d>| d?          R|rtE          |            n|D ]\  }\  }}|tC          |          z   }|| j#        z  } | dk    r&t)          j$        d@|d=dA| j#        d)dB| d)dC           t)          j        dD%                    || z
  tM          || j#                  | j#        z  d4z
                       	 7fdE|D             }!	 |!dF |D             }"tO          |!|"z   dG H          }!|!D ]}\  }}}}#|	}	|	rN|#rL|dInd| d}t)          j        dJ           t)          j        dK           t)          j        dL| dM           d}	|}tC          |          dk    rt)          j        |dNnd| dO           tQ          ||#r| j        ndP          }| j        s+t)          j        dQ           || j#        z  } || z  }dR| z  |z   }| j        s)|                                 stS          | |||||          }nt)          j        dS           tU          j+        |          ,                                }$tC          |          }%|	r&|}&t[          j.        |&dT          }tC          |          }'|}(t)          j/                     ta          d4| j1        d4z             D ]})	 |	r+t[          j2                    }*| 3                    |%|'|           n| 4                    |%||#U           d}+d},d}-tk          j5                    }.tl          }/|	r|'n|%}0tC          |          dk    rq|s7t)          j7        |0tC          |          z
  |0dV||-z   d=dWdW|, dX|0 dYZ           tC          |          dk    rn#|d| j8                 }1|	rztC          |*9                    |1                    }2|-|2z  }-tu          tl          tw          tx          |2                    }3| j        s|3}/| =                    |1|+|/[           | j        r|3}/n^|1dR| j8        tC          |1          z
  z  z   }1|#r| >                    |1|+           n| ?                    |1|+           |-tC          |1          z  }-|,tC          |1          z  },|| j8        d         }|+d4z  }+tC          |          dk    q n# t          $ r |)| j1        k    s|#r t)          j        d\           | jA        B                                 t)          j        d]d^_           ta          t                    D ]}	 tk          jD        d4           | jA        E                                 t)          j                     | F                                 | j        rd| _        | G                                } |(} n(# t          $ r t)          j        dd^d`           Y w xY w Y w xY w| j        rA|!da         db         }4|	r|4s| H                    d|/c           n| I                    d|/c           tk          j5                    |.z
  }.d^}5t)          j/        dd           |	r=|.dek    rdf|%|.z  dgz  dhz  didj}5t)          j        dk|% dl|, dm|d=dn|.dido|5 d           n7|.dek    rdp|-|.z  dgz  dhz  z  }5t)          j        dk|- dq|d=dn|.dido|5 d	           |#s| j        s	 | J                    ||%          }6|6|$k    ryt)          j        dr|$            t)          j        ds|6            |6tU          j+        dR|%z            ,                                k    rt          dt          t          du          t)          j        dv           X# t          $ r Y ew xY wt)          j        dw           dS )xa#  
    Write firmware or data to the SPI flash memory of an ESP device.

    Args:
        esp: Initiated esp object connected to a real device.
        addr_data: List of (address, data) tuples specifying where
            to write each file or data in flash memory. The data can be
            a file path (str), bytes, or a file-like object.
        flash_freq: Flash frequency to set in the bootloader image header
            (``"keep"`` to retain current).
        flash_mode: Flash mode to set in the bootloader image header
            (``"keep"`` to retain current).
        flash_size: Flash size to set in the bootloader image header
            (``"keep"`` to retain current).

    Keyword Args:
        erase_all (bool): Erase the entire flash before writing.
        encrypt (bool): Encrypt all files during flashing.
        encrypt_files (list[tuple[int, ImageSource]] | None): List of
            (address, data) tuples for files to encrypt individually.
        compress (bool): Compress data before flashing.
        no_compress (bool): Don't compress data before flashing.
        force (bool): Ignore safety checks (e.g., overwriting bootloader, flash size).
        ignore_flash_enc_efuse (bool): Ignore flash encryption eFuse settings.
        no_progress (bool): Disable progress updates.
    c                 6    g | ]\  }}|t          |          fS  r   .0r   r   s      ra   
<listcomp>zwrite_flash.<locals>.<listcomp>  s'    JJJ*$tYt__-JJJrc   	erase_allFencryptencrypt_filesNcompressno_compressforceignore_flash_enc_efuseno_progressESP8266i   zSecure Boot detected, writing to flash regions < 0x8000 is disabled to protect the bootloader. Use the force argument to override, please use with caution, otherwise it may brick your device!zInput does not containr   z' is not anz an z/ image. Use the force argument to flash anyway.r     Tz"' requires chip revision in range z[vd   rj    - zmax rev not set] vz] z(this chip is revision v)z). Use the force argument to flash anyway.ESP32-C3z' requires chip revision z" or higher (this chip is revision z*). Use the force argument to flash anyway.zThis chip has encrypt functionality in UART download mode disabled. This is the Flash Encryption configuration for Production mode instead of Development mode.r   z%Unexpected FLASH_CRYPT_CONFIG value: r   z'Flash encryption key is not programmed.c                 6    g | ]\  }}|t          |          fS r  r  r  s      ra   r  zwrite_flash.<locals>.<listcomp>  s'    JJJjdD44)JJJrc   zInput imagez
 (address z	) is not z% byte aligned, can't flash encrypted.zaCan't perform encrypted flash write, consult Flash Encryption documentation for more information.ESP32flash_crypt_cnt1r   zWARNING: Detected flash encryption and secure download mode enabled.
Flashing plaintext binary may brick your device! Use the force argument to override the warning.zWARNING: Detected flash encryption enabled and download manual encrypt disabled.
Flashing plaintext binary may brick your device! Use the force argument to override the warning.)detectr   zSet flash_size z, is larger than the available flash size of zFile 'z	 (length z) at offset rm   z will not fit in zD bytes of flash. Change the flash_size argument or flashing address.zFlash address z is not aligned to a z byte flash sector. z* bytes before this address will be erased.z1Flash will be erased from {:#010x} to {:#010x}...c                 (    g | ]\  }\  }}|||fS r  r  )r  r   r   namer  s       ra   r  zwrite_flash.<locals>.<listcomp>  s+    XXX1E$t$dG,XXXrc   c                 >    g | ]\  }}|gt          |          d R S Tr  r  s      ra   r  zwrite_flash.<locals>.<listcomp>  s?      
  
  
/;dT*IdOO*T** 
  
  
rc   c                     | d         S Nr   r  xs    ra   <lambda>zwrite_flash.<locals>.<lambda>  s
    1Q4 rc   keyinput bytes
z4Compress and encrypt options are mutually exclusive.zWill flash z uncompressed.zInput bytes are empty.z' is empty.r*   zErasing flash...   z>Security features enabled, so not changing any flash settings.r/   )begin_rom_encryptedzWriting at r[   r   r   r   )timeoutz
Lost connection, retrying...z!Waiting for the chip to reconnectrd   rf   re   rL   )rebootr6  r   r    (r.   r   r   z kbit/s)r   z bytes (z compressed) at r   r   z (%.1f kbit/s)r   zInput MD5: zFlash MD5: z0Write failed, the written flash region is empty.z)MD5 of file does not match data in flash!zHash of data verified.zCCannot verify written data if encrypted or in secure download mode.)Lr   IS_STUBr]   rw   get_secure_boot_enabledr   r   r   errorRuntimeErrorr}   rt   max_rev_fullmin_rev_fullmin_revget_chip_revisionget_minor_chip_versionget_major_chip_versionget_encrypted_download_disabledget_flash_crypt_configr   r\   is_flash_encryption_key_validFLASH_ENCRYPTED_WRITE_ALIGNr   binrv   countget_flash_encryption_enabled_set_flash_parametersr   r   minr   erase_flashFLASH_SECTOR_SIZEnoter   r   sortedr    r
  r   md5	hexdigestzlibr  r   r   WRITE_FLASH_ATTEMPTSdecompressobjflash_defl_beginflash_beginr   r   r   FLASH_WRITE_SIZE
decompressmaxr   r   flash_defl_blockflash_encrypt_blockflash_blockr   ru   closer   sleepr   rq   run_stubflash_defl_finishflash_finishflash_md5sumr   )8r   r  r   r   r   kwargsnorm_addr_datar  r  r  r  r  r  r  r   r   r   r(  r   msguse_rev_full_fieldsrev	error_strdo_writecrypt_cfg_efuseenc_key_validfiles_to_encryptr   set_flash_size	flash_endflash_end_str	write_end
bytes_over	all_filesencrypted_files_flag	encryptedcalcmd5uncsizeuncimagecompsizeoriginal_imageattemptrZ  r   
bytes_sentbytes_writtenr   r6  
image_sizeblockblock_uncompressedblock_timeoutlast_file_encryptedr   resr  s8                                                          @ra   write_flashr    s   F KJ	JJJN jje44IJJy%00G:@**; ;M ZZ
E22H

=%88K**We,,E#)::.F#N#N

=%88K
  K ; DS]i//8P/&&(( 	,  
V##$W   $  . 8	 8	OA|d)#->>l;   } 11104,,BWdBWBWBW  ! > > > > >   !Q&&&+###u,,&*#&!++0B0B*/'&*#" ++--+++sU5G/G/G LD L L LIVU/36VV9Kc9QVVVI )U22!%88		!X 2c 9XXE<NQT<TXXX	 !UC3J!U!Us!U!U!UUI$$OOO   0H& =J..4466CC4466C&&$BD B B =B BLOB B B   '  H-+' 	!2244  3   "88::O*#/E/E	V/VVVWWW ==??M  !	CDDD 
 " NJJMJJJ 	 ')9 % %%$S<< %.2l]]DFK! 1 1WB 1 1:1 1 1  
  %H 	 6 	O  
  	)33 ((, )--//0ABCCII#NNQRRVWWW F   ,
7799
 4466

 !F   'sJ77J )3:L(L(L$$$RV   	"		)#..$]33	 	i 	NY,F,FKO* O O>KO O O   +9UYUNI&&&I  %3 	 	!G\dDT"Y..*.,<LT<L<L<L  J JD		 J JSJ J7@J J J   /  C"0 	 	GYdA#d))+I 3#88JQQWD Q Q1JQ Q!PQ Q Q   ICJJj(	3+@AA+,     YXXXXXXI   
  
?L 
  
  
 9';;PPP	*3 y y&tY  		 	&*l]]DFIdOOOKNOOOI:F:::;;;Hu::??K,0L((>S$>S>S>S   uQc==PQRR{ 	1I()))
 !3#88Jz!Gj(50E' 	0K0K0M0M 	.Wj*j% EE KP   +e$$..00e** 	"HM(A..E5zzH	Q 81 <== R	 R	GQ U "&!3!5!5J(((GDDDDOOGW)OTTT
 !IKK))1>XXw
%jjAoo& (%/#e**%<(2#Q=1H#Q#Q#Q#Q#Iz#I#IJ#I#I#I	    5zzQ!!c&:":;E 4 .11F1Fu1M1M-N-N*%);;(++* :<N ) )  #{ 4&3G,,UC,III; 4 '4G !&33G#e**3T(U U$ 833E3????OOE3777%U3#e**,J!#"6"8"89E1HCQ %jjAooR "   c666)6 	:;;;	!!!	=2FFFF788  A;
1	(((	; 1*/CK"%,,..C .* ; ; ;	#2T::::::; 	 )4 ; 	@ #,B-"2
  @ 3 @%%UG%DDDD  w ???
 IKK!O		 	3wwE1q4!7EEEE	IE E E* E EDE E)*DE E8AE E E   
 3ww,0AA0E0LM	I' ' ''M ' 'QM ' '#' ' '  
  	!9 	&&w88'>>I5G55666I1C11222gk'G*;<<FFHHHH(N   %%PQQQI67777+    IU   oy ys^   D33EEG0gA2k8A8j20k2!kkkkkB)r
rrc                    d }|                      d          }|rL |d|            |d|                      d                      |d|                      d                     dS  |d|                      d                     dS )z
    Read and display the MAC address of the ESP device.

    Args:
        esp: Initiated esp object connected to a real device.
    c                 x    t          j        | dz   dd                    d |D                                   d S )N:z<20c              3      K   | ]}|d V  	dS )02xNr  )r  r.  s     ra   	<genexpr>z.read_mac.<locals>.print_mac.<locals>.<genexpr>  s&      .G.Ga!zz.G.G.G.G.G.Grc   )r   r\   join)labelmacs     ra   	print_maczread_mac.<locals>.print_mac  sE    	US[IIchh.G.G3.G.G.G&G&GIIJJJJJrc   EUI64MACzBASE MACBASE_MACMAC_EXTN)read_mac)r   r  eui64s      ra   r  r    s    K K K LL!!E 3	%	*cll:66777	)S\\)4455555	%j1122222rc   c                     	 |                                  }t          j        d|d           dS # t          $ r/ t          j        | j         d           t          |            Y dS w xY w)z
    Read and display the Chip ID of the ESP device if available,
    otherwise fall back to displaying the MAC address.

    Args:
        esp: Initiated esp object connected to a real device.
    	Chip ID: rm   z- has no chip ID. Reading MAC address instead.N)r}   r   r\   r   r   r]   r  )r   chipids     ra   r}   r}     s}    	,f,,,-----   s}SSSTTTs   ,0 5A)(A)spi_connectionc                    
 d }|e|}|dk    rd}n,|dk    rd}n#                      |            ||          \  }}t          j        d| d                                |           n j        s j        d	k    s j        r*t          j        d
                                d           nj                                 } ||          \  }}|dk    rt          j        d| d           nt          j        d
                                |            fd
 
fd} j        s<	  |             n0# t          $ r#} 	                    d| d           Y d}~nd}~ww xY w j        sn	  
                                }	|	dv r,t          j        d           |t          j        d           dS dS dS # t          $ r}t          d| d          d}~ww xY wdS )aS  
    Configure and attach a SPI flash memory chip to the ESP device,
    verify the connection.
    All following flash operations will be performed on the attached flash chip.

    Args:
        esp: Initiated esp object connected to a real device.
        spi_connection: Custom SPI connection configuration.
            This can either be a tuple containing five pin numbers
            ``(CLK, Q, D, HD, CS)`` for manual configuration
            or a string (``"SPI"`` or ``"HSPI"``) representing a pre-defined config.
            If not provided, the default flash connection is used.
    c           
      p    | \  }}}}}d| d| d| d| d| 
}|dz  |dz  z  |dz  z  |d	z  z  |z  }||fS )
zAPrepare SPI configuration string and value for flash_spi_attach()zCLK:z, Q:z, D:z, HD:z, CS:r7   r0      r,   r  )r  clkqr   hdcsspi_config_txtr   s           ra   _define_spi_connz&attach_flash.<locals>._define_spi_conn  ss    *Q2rEEEEEEEEEEErbBh'173qAv>Du$$rc   NSPIr   HSPIr   zConfiguring SPI flash mode (z)...r#  z"Enabling default SPI flash mode...)r   r   r   r   r   z5Attaching flash from eFuses' SPI pads configuration (c                      t          d          \  } }}| t          k    rdS |dz	  dz  }|dz  }d}|dk    r|dk    r|dk    rd}n)|dk    r|d	k    r|dk    rd}n|d
k    r|dk    r|dk    rd}|S )NFr.   r   @   r2   r#   TA   r6   P   r4   r5   )r   XMC_VENDOR_ID)r   r   r   mfidcpidmatchedr   s         ra   is_xmc_chip_strictz(attach_flash.<locals>.is_xmc_chip_strict   s    "1#u"="=	9a%%5Q$&44<<t||T\\t||T\\t||rc   c                     d} | r             rd S d}                     |d          }|t          k    rd S t          j        d                               d                               d                               d           t          j        d                               d	           t          j        d
                        st          j        d           t          j        d           d S )NTr   r.   zIXMC flash chip boot-up failure detected! Running XMC25QHxxC startup flow.   y   r   gMb`?   gh㈵>zXMC flash boot-up fix failed.z&XMC flash chip boot-up fix successful!)read_spiflash_sfdpr  r   r   run_spiflash_commandr   r`  r\   )
fast_checksfdp_mfid_addrmf_idr   r  s      ra   flash_xmc_startupz'attach_flash.<locals>.flash_xmc_startup5  s   
 	,,.. 	F&&~q99M!!FW	
 	
 	
 	  &&&  &&&  &&&
5  &&&
7!!## 	9K7888	:;;;;;rc   z3Unable to perform XMC flash chip startup sequence ().)i r   i? zFailed to communicate with the flash chip, read/write operations will fail. Try checking the chip connections or removing any other hardware connected to IOs.zrSome GPIO pins might be used by other peripherals, try using another combination of pins for SPI flash connection.z(Unable to verify flash chip connection ()check_spi_connectionr   r\   flash_spi_attachr;  r]   rw   get_chip_spi_padsr   tracer   r   rP  )r   r  r  
spi_configr   spi_chip_padsr  r  er   r  s   `         @ra   attach_flashr    s   $% % % !#
U""EEv%%EE$$^444 !1 0 @ @J	AAAABBBU####[ (=G##s'?#I:;;;  ####  1133M$4$4]$C$C!NE//	-&- - -   
 	>???  '''    *< < < < < <4 # S	S 	S 	S 	SIIQAQQQRRRRRRRR	S # O	O||~~H999;   "-HP     :9 .-  	O 	O 	OMMMMNNN	O!O Os1   -
D8 8
E%E  E%0AF8 8
GGGc                    t          j        d           |dk    }|dk    r@t          |           }|t          j        d           d}nQt          j        d|            n9|dk    r3| j        rdnt          |           }| j        st          j        d           |Y|                     t          |                     | j        r	| j	        d	v s't          |          d
k    rt          j        d           |rdn|S )a  
    Configure the ESP device's flash memory parameters based on the selected flash size.

    Must be called after attach_flash() and before any flash read/write operations.
    It supports three modes of operation based on the flash_size argument:
      - "detect": Automatically detects the flash size
                  (with a fallback to 4MB if detection fails)
      - "keep": Leaves the flash parameters unchanged in the image header,
                but configures the SPI flash chip with its detected size (if possible)
      - Explicit size (e.g., "4MB", "8MB", etc.): Directly uses the specified flash size

    Args:
        esp (ESPLoader): Initiated esp object connected to a real device.
        flash_size (str, optional): The flash size setting to use. Can be "detect",
                                    "keep", or an explicit flash size value
                                    (default: "keep").

    Returns:
        str | Any: Returns "keep" if flash_size was "keep", or the flash size value
                   used for configuration. In "detect" mode, this is the auto-detected
                   flash size (or "4MB" as a fallback).
    zConfiguring flash size...r   r&  Nz4Could not auto-detect flash size, defaulting to 4MB.r'   zAuto-detected flash size: z5In case of failure, please set a specific flash size.)zESP32-S3zESP32-P4zESP32-C5i   zoFlash sizes larger than than 16MB are not fully supported. Change the flash size argument in case of a failure.)
r   r\   r   r   rw   r;  rP  flash_set_parametersr   r]   )r   r   r   s      ra   rL  rL  j  s4   0 I)***D X&s++
KNOOOJJI?:??@@@@	v		 !5QTT;LS;Q;Q
{ 	NHLMMM   !1*!=!=>>> 	!$2V!V!V ,,/???HG  
 )66z)rc   r  c                    |sI| j         dk    r>| j        s7|                                 s|                                 rt	          d          t          j                     t          j        d           | j         dk    r| j        st          j	        d           t          j
                    }|                                  t          j        d           t          j        dt          j
                    |z
  dd	           d
S )z
    Erase the SPI flash memory of the ESP device.

    Args:
        esp: Initiated esp object connected to a real device.
        force: Bypass the security checks for flash encryption and secure boot.
    r  Active security features detected, erasing flash is disabled as a safety measure. Use the force argument to override, please use with caution, otherwise it may brick your device!z/Erasing flash memory (this may take a while)...zWYou can use the erase-region command in ROM bootloader mode to erase a specific region.Tr   z$Flash memory erased successfully in r   	 seconds.N)r]   rw   rK  r<  r   r   r   r\   r;  rP  r   rN  )r   r  r   s      ra   rN  rN    s	     S]i//8P/++-- 	1L1L1N1N 	O   IKKKI?@@@
}	!!#+!/	
 	
 	
 		AOOITISTY[[1_SSSSTTTTTrc   c                    |t           j        z  dk    rt          dt           j         d          |t           j        z  dk    rt          dt           j         d          |sI| j        dk    r>| j        s7|                                 s|                                 rt          d          t          j                     t          j	        d           t          j
                    }| j        dk    r | j        s|                     ||d	           n|                     ||           t          j        d
           t          j	        dt          j
                    |z
  dd           dS )aZ  
    Erase a specific region of the SPI flash memory of the ESP device.

    Args:
        esp: Initiated esp object connected to a real device.
        address: The starting address from which to begin erasing.
        size: The total number of bytes to erase.
        force: Bypass the security checks for flash encryption and secure boot.
    r   z+Offset to erase from must be a multiple of rj   z,Size of data to erase must be a multiple of r  r  zHErasing flash memory region (this may take a while depending on size)...F)loggingTr   z+Flash memory region erased successfully in r   r  N)r   rO  r   r]   rw   rK  r<  r   r   r\   r   r;  rX  erase_region)r   r   r   r  r   s        ra   r  r    s    ,,11X):UXXX
 
 	
 i))Q...*. . .
 
 	
  S]i//8P/++-- 	1L1L1N1N 	O   IKKKIR   		A
}	!!#+!gu5555$'''ITITdikkAoTTTT    rc   c                 .    |                                   dS )z
    Execute the firmware loaded on the ESP device.

    Args:
        esp: Initiated esp object connected to a real device.
    N)runr   s    ra   r  r    s     GGIIIIIrc   c                     t          |           \  }}}t          j        d|d           t          j        d|d           t          j        d|pd            dS )z
    Read and display the SPI flash memory chip ID and related information.

    Args:
        esp: Initiated esp object connected to a real device.
    zManufacturer: r  zDevice: 04xzDetected flash size: UnknownN)r   r   r\   )r   manufacturer_idr   r   s       ra   print_flash_idr    st     .=S-A-A*OY
I4444555I(((()))I?j&=I??@@@@@rc   c                 r   d}t          j        |           t          j        dt          |          z             t          |            |                                 }ddd}|                    |          }|rt          j        d|            	 |                                  dS # t          $ r Y dS w xY w)z
    Read and display the SPI flash memory chip identification and configuration details,
    such as the manufacturer ID, device ID, detected flash size, type, and voltage.

    Args:
        esp: Initiated esp object connected to a real device.
    zFlash Memory Information:=zquad (4 data lines)zoctal (8 data lines)r   r   zFlash type set in eFuse: N)r   r\   r   r  
flash_typer   get_flash_voltager   )r   titler  flash_type_dictflash_type_strs        ra   r   r     s     (EIeIcCJJ3!!J/4JKKO$((44N @	>n>>???   s   B( (
B65B6r   c                 f   d|cxk    rdk    sn t          d          t          |            |                     ||dz            }t          j        d| d||z   dz
   dd	           t          |          D ]$}t          j        |d
z  ddd	           |dz	  }%t          j                     dS )a  
    Read and display the Serial Flash Discoverable Parameters (SFDP)
    from the flash memory.

    Args:
        esp: Initiated esp object connected to a real device.
        address: Starting address in the SFDP region to read from.
        bytes: Number of bytes to read (1-4).
    r   r*   z0Invalid number of bytes to read from SFDP (1-4).r.   zFlash memory SFDP[z..z]: rd   r7  r   #04xr[   N)r   r  r  r   r\   r   )r   r   r   sfdpr   s        ra   read_flash_sfdpr    s     OOOO!OOOOKLLL3!!'51955DIF7FFgo.AFFFBOOOO5\\  	TD[((((b1111qyIKKKKKrc   r  c                 f   t          | |           |rd}nd }t          j                     t          j                    }|                     |||          }t          j                    |z
  }|dk    r+d                    t          |          |z  dz  dz            nd}	|rd| d	nd}
t          j        d
           t          j        dt          |           d|dd|dd|	 |
 d
           |r?t          |d          5 }|	                    |           ddd           n# 1 swxY w Y   dS |S )a~  
    Read a specified region of SPI flash memory of an ESP device
    and optionally save it to a file.

    Args:
        esp: Initiated esp object connected to a real device.
        address: The starting address in flash memory to read from.
        size: The number of bytes to read.
        output: The name of the file to save the read data.
            If None, the function returns the data.
        flash_size: Flash size setting, needs to be set only when
            the stub flasher is disabled.
            Options: ``"detect"``: auto-detect flash size with fallback to 4MB,
            ``"keep"``: auto-detect but skip setting parameters in SDM,
            Explicit size: use the specified flash size.
        no_progress: Disable printing progress.

    Returns:
        The read flash data as bytes if output is None; otherwise,
        returns None after writing to file.
    Nc           
      T    t          j        | |d|| z   ddd|  d| d           d S )NzReading from rm   r[   r   r   r   )r   r   )progresslengthoffsets      ra   flash_progressz"read_flash.<locals>.flash_progressQ  sX    !"Av'8AAAA7877f777	     rc   r   r   r.   r   rd   r   r   Tr   zRead r   rm   r   r   r   rj   r   )
rL  r   r   r   
read_flashr   r   r\   r   r   )r   r   r   r   r   r  r  r   r   r   r   r   s               ra   r  r  /  s   : #z*** 
	 	 	 IKKK	A>>'488D	aAGH3ww"))#d))a-!*;d*BCCCTVI$*2 v    HITI	"D		 	" 	"wI 	" 	"!I 	" 	"	"	" 	" 	"    &$ 	1GGDMMM	 	 	 	 	 	 	 	 	 	 	 	 	 	 	ts   D$$D(+D(diffc                 p   t          | |          }d}|D ]\  }}t          |          \  }}	t          |d          t          | ||||          t	                    }
|	dnd|	 d}	t          j        d|
dd|
 d	|d
d|	 d	           |                     ||
          }t          j	                  
                                }||k    rt          j        d           d}|st          j        d           |                     ||
          k    sJ fdt          |
          D             }t          j        dt	          |           d||d         z   d
d           |D ]5}|         }|         }t          j        d||z   d
d|dd|d           6|rt          d          dS )a  
    Verify the contents of the SPI flash memory against the provided binary files
    or byte data.

    Args:
        esp: Initiated esp object connected to a real device.
        addr_data: List of (address, data) tuples specifying what
            parts of flash memory to verify. The data can be
            a file path (str), bytes, or a file-like object.
        flash_freq: Flash frequency setting (``"keep"`` to retain current).
        flash_mode: Flash mode setting (``"keep"`` to retain current).
        flash_size: Flash size setting (``"keep"`` to retain current).
        diff: If True, perform a byte-by-byte comparison on failure.
    Fr*   Nr2  r   z
Verifying r   r:  z) bytes at rm   z in flash against r   z)Verification successful (digest matched).Tz&Verification failed (digest mismatch).c                 8    g | ]}|         |         k    |S r  r  )r  r   flashr   s     ra   r  z verify_flash.<locals>.<listcomp>  s+    LLLQuQx587K7Kq7K7K7Krc   zVerification failed: z differences, first at r   r  z   r[   r  zVerification failed.)rL  r   r    r
  r   r   r\   rd  r   rR  rS  r  r   r   )r   r  r   r   r   r  mismatchr   r   r   r  r   expected_digestdifferencesr   
flash_byte
image_byter  r   s                    @@ra   verify_flashr  l  sg   , 'sJ77JH" $S $S ftQ**j*e
 
 ZZ
"(.m&mmm	?> ? ?* ? ?>? ?39? ? ?	
 	
 	

 !!':66!+e,,6688_$$IABBBH 	BCCCw
33~~~~LLLLL%
"3"3LLL	:C$4$4 : :+a.09: : :	
 	
 	
  	S 	SAqJqJIQGaKQQQ
QQQQQQRRRR	S  1/0001 1rc   c                 \    t          j        d|                     |          d           dS )z
    Read and print the status register value of the SPI flash memory.

    Args:
        esp: Initiated esp object connected to a real device.
        bytes: Number of bytes to read.
    zFlash memory status: r   N)r   r\   read_status)r   r   s     ra   read_flash_statusr    s2     ICcooe&<&<CCCDDDDDrc   non_volatilec                 J   d|dz   d}|d|dz  z  dz
  z  }t          j        d||                     |          z              t          j        d||z              |                     |||           t          j        d||                     |          z              d	S )
af  
    Write a new value to the SPI flash memory status register and verify the update.

    Args:
        esp: Initiated esp object connected to a real device.
        value: The new status register value to write.
        bytes: Number of bytes to write.
        non_volatile: If True, allows non-volatile status register bits
            to be written.
    z0x%0rK   r.  r   r.   zInitial flash memory status: zSetting flash memory status: zAfter flash memory status:   N)r   r\   r  write_status)r   r   r   r  fmts        ra   write_flash_statusr    s     


CaEAI&!+,EILcCOOE4J4J.JLLMMMI;cEk;;<<<UE<000ILcCOOE4J4J.JLLMMMMMrc   c           	                                            }|d         }d}t          j        |           t          j        dt          |          z             t          j        d                    |d         t          |d                                         j        rht          j        d|d                     d                     fd	t          |d                   D                       }t          j        d
|            |d         b|d         Zt          j        d                    |d                              t          j        d                    |d                              |d         rt          j        d           |d         rt          j        d           g }t          g d          D ]"\  }}||         r|	                    |           #t          |          dk    r1t          j        d           |D ]}t          j        d| d           nt          j        d           t          |d                   }|
                    d          dz  dk    rt          j        d           nt          j        d           d}	 j        d k    rd!}	t          j        |	 d"|d         d#           |d$         rt          j        d%           |d&         rt          j        d'           |d(         }
|d)         }|
rt          j        d*           n|rt          j        d+           |d,         rt          j        d-           dS dS ).z
    Read and display security-related information about the ESP device.

    Args:
        esp: Initiated esp object connected to a real device.
    rh   zSecurity Information:r  zFlags: {:#010x} ({})flagszKey Purposes: key_purposesz
  c           	      n    g | ]1\  }}|j         k    d | dj                            |d           2S )	BLOCK_KEYr  UNKNOWN)EFUSE_MAX_KEYKEY_PURPOSESr   )r  key_numpurposer   s      ra   r  z%get_security_info.<locals>.<listcomp>  sY       $GWc/// SGRR(8(<(<Wi(P(PRR///rc     r}   Napi_versionzChip ID: {}zAPI Version: {}SECURE_BOOT_ENzSecure Boot: EnabledSECURE_BOOT_AGGRESSIVE_REVOKEz.Secure Boot Aggressive key revocation: Enabled)SECURE_BOOT_KEY_REVOKE0SECURE_BOOT_KEY_REVOKE1SECURE_BOOT_KEY_REVOKE2r   z#Secure Boot Key Revocation Status:
z	Secure Boot Keyz is Revoked
zSecure Boot: Disabledr$  r%  rK   zFlash Encryption: EnabledzFlash Encryption: Disabledz)SPI Boot Crypt Count (SPI_BOOT_CRYPT_CNT)esp32z#Flash Crypt Count (FLASH_CRYPT_CNT): r   DIS_DOWNLOAD_DCACHEz&Dcache in UART download mode: DisabledDIS_DOWNLOAD_ICACHEz&Icache in UART download mode: DisabledHARD_DIS_JTAGSOFT_DIS_JTAGzJTAG: Permanently DisabledzJTAG: Software Access DisabledDIS_USBzUSB Access: Disabled)rv   r   r\   r   r   rI  r  r  r   appendrJ  r]   )r   r   rh   r  descrevoked_keysr   r1  r$  CRYPT_CNT_STRINGhard_dis_jtagsoft_dis_jtags   `           ra   rv   rv     s    
			 	 Bn%L#EIeIcCJJI$++BwKR[9I9IJJKKK
 		72n#577888{{   (1"^2D(E(E  
 
 		+t++	)} R%6%B	-&&r)}55666	#**2m+<==>>>$% +	()))78 	HIFGGG  
 
 	' 	'FAs C  '##A&&&|q  I<===! @ @	>a>>>???? 		)***"./00Oc""Q&1,,	-....	.///B
}@I!??R(9%:???@@@)* <	:;;;)* <	:;;; 1M 1M 4	.////	 4	2333I *	()))))* *rc   
hard-reset
reset_modec                    |dk    r|                                   dS |dk    r+t          j        d           |                     d           dS |dk    rt          j        d           dS |dk    rG| j        r*t          j        d           |                                   dS |                                  dS |d	k    r4t          j        d
           | j        r|                     d           dS dS t          d|           )a  
    Reset the ESP device.

    Args:
        esp: Initiated esp object connected to a real device.
        reset_mode: Reset mode to use (
            ``"hard-reset"``: perform a hard reset using the RTS control line,
            ``"soft-reset"``: perform a soft reset,
            ``"no-reset"``: stay in bootloader,
            ``"no-reset-stub"``: stay in flasher stub,
            ``"watchdog-reset"``: perform a hard reset utilizing a software watchdog.
            )

    r  z
soft-resetzSoft resetting...Fzno-reset-stubzStaying in flasher stub.zwatchdog-resetzdWatchdog hard reset is not supported in Secure Download Mode, attempting classic hard reset instead.zno-resetzStaying in bootloader.TzInvalid reset mode: N)	
hard_resetr   r\   
soft_resetrw   r   watchdog_resetr;  r   )r   r  s     ra   
reset_chipr    s<    \!!	|	#	#	%&&&u		&	&	,-----	'	'	'# 	!K9   NN     	z	!	!	*+++; 	!NN4     	! 	! <
<<===rc   c                     | j         rt          j        d           n| j        dk    r)|                                 rt          j        d           n| j        s| j        rt          j        d           n| j        dv rt          j        d| j         d           ns	 |                                 S # t          $ rQ t          j
        dk    r?|                                 d	k    r't          j                     t          j        d
            w xY w| S )a  
    Load and execute the stub loader on the ESP device. If stub loading
    is not supported or is explicitly disabled, warnings are logged.

    Args:
        esp: Initiated esp object connected to a real device.

    Returns:
        The esp instance, either as a stub child class in a state
        where the stub has been executed, or in its original state
        if the stub loader is disabled or unsupported.
    ztStub flasher is not supported in Secure Download Mode, it has been disabled. Set --no-stub to suppress this warning.r!  zyStub flasher is not supported on ESP32-C3 with Secure Boot, it has been disabled. Set --no-stub to suppress this warning.zYStub flasher has been disabled for compatibility, set --no-stub to suppress this warning.)z	ESP32-H21zESP32-H4z%Stub flasher is not yet supported on z?, it has been disabled. Set --no-stub to suppress this warning.darwiniU  zEIf issues persist, try installing the WCH USB-to-Serial MacOS driver.)rw   r   r   r]   r<  r;  stub_is_disabledra  r   sysplatform_get_pidr\   rP  r  s    ra   ra  ra  F  sl     "L	
 	
 	
 	
 
*	$	$)D)D)F)F	$L	
 	
 	
 	
 [ S1 6	
 	
 	
 	
 
  
 
 	LCM L L L	
 	
 	
 	


	<<>>! 	 	 	|x''CLLNNf,D,D	I   	 Js   B0 0ADc                    | dd         }d}t          j        ||          \  }}}}}}}	}
}}}}}}|dk    rdS |||t          |          t          |          t          |          t          |	          t          |
          t          |d          |dz   d|dz   |dz   d|dz   |d	k    rd
|z  dz   dnd||dS )z^
    Check if correct magic word is present in the app_info and parse the app_info struct
    N   z<II8s32s32s16s16s32s32sHHB3s72sl   2TW F	uppercaser  rj   r   rK   r    KB)
magic_wordsecure_versionreserv1versionproject_namer   dateidf_verapp_elf_sha256min_efuse_blk_rev_fullmax_efuse_blk_rev_fullmmu_page_sizereserv3reserv2)r   r   r!   r   )app_info_segmentapp_infoAPP_DESC_STRUCT_FMTr&  r'  r(  r)  r*  r   r+  r,  r-  r.  r/  r0  r1  r2  s                    ra   _parse_app_infor6  }  s6     %H P  	)844 Zt !("7++'55%%%%"7++ 5AAA%,MM/E/KMM &,MM/E/KMM 1>0B0Bq-4',,,,)  rc   c                     | dd         }d}t          j        ||          \  }}}}}}|dk    rdS |||t          |          t          |          |dS )zp
    Check if correct magic byte is present in the bootloader_info and parse
    the bootloader_info struct
    Nr  z<B3sI32s24s16s)
magic_byter(  r)  r,  	date_timer2  )r   r   r!   )	bootloader_info_segmentbootloader_infoBOOTLOADER_DESC_STRUCT_FMTr8  r(  r)  r,  r9  r2  s	            ra   _parse_bootloader_infor=    s    
 .crc2O "A 	0/BB Tt !"7++$Y//  rc   chipc                    t          | t                    rt          j        d           t	          |           D ]\  }}t          |d                   \  }}|d         t          |d                   nd}d|dz    dt          |            d| d	t          |           d
	}t          j                     t          j        dt          |          z             t          j        |           t          j        dt          |          z             	 t          ||          }nY# t          $ rL}	t          j
        d|dz    dt          |            d|	            t          j
        d           Y d}	~	;d}	~	ww xY w|dk    r-|+t          j        d|                                            |}t          ||           dS t          |           \  }}t          ||          }t          j        dt          |           d
           |)t          j        d|                                            t          ||           dS )a  
    Display detailed information about an ESP firmware image.

    Args:
        input: Path to the firmware image file, opened file-like object,
            or the image data as bytes. If a list of tuples is provided,
            each tuple contains an offset and an image data as bytes. Used for
            merged binary images.
        chip: Target ESP device type (e.g., ``"esp32"``). If None, the chip
            type will be automatically detected from the image header.
    z@Merged binary image detected. Processing each file individually.r   r   NunknownzProcessing file r   z
, offset: z, size: z bytesr  zError processing file r  z;Probably not a valid firmware image (e.g. partition table).zDetected image type: zImage size: )
isinstancelistr   r\   r   r   hexr   _parse_image_info_headerr   r=  upper_print_image_info)
r   r>  r   filer   r   
offset_strlinedetected_chipr  s
             ra   
image_inforK    sz    % %/	TUUU '' 	3 	3GAtQ((GD!)-a)<T!W)JA1q5 A A3u:: A A%A A/24yyA A A  IKKKIcCIIo&&&IdOOOIcCIIo&&& 8t D D   	L1q5LL3u::LLLLMMM	WXXX Q4<	I-2E2E2G2GIIJJJ$mT22223	3 	38 E""a0t<<	2T222333<IEm.A.A.C.CEEFFF-.....s   D$$
E:.AE55E:r   c                 `   t          j        |           }|                    d          }||                    d          }|                    d           	 |d         }n# t          $ r t          d          w xY w|t          j        t          j	        fvrt          d|dd          |	 |d	         d
vrt          d          t                              |dd         d          }t          D ]}||j        k    r	|j        } nt          d| d          n# t
          $ r d}Y nw xY w|S )z5Parse the image info header and return the chip type.r.   Nr   r   zImage is empty.z1This is not a valid image (invalid magic number: r   r  r8  r  zAppend digest field not 0 or 1.r*   r+   littlezUnknown image chip ID (r   )r   r   readseek
IndexErrorr   r   r   r
   IMAGE_V2_MAGICint
from_bytesr   rt   r]   )r   r>  streamcommon_headerextended_headerr   r}   roms           ra   rD  rD    s   ZFKKNNM| ++b//
KKNNN,a  , , ,*+++,!-   LLLLL
 
 	
 |	r"&00 !BCCCnn_QqS%98DDG H Hc///=DE 0 !!F7!F!F!FGGG   	 	 	DDD	 Ks   A   A:.A-D D+*D+c                    t          | |          t          j                     |                                  d}t          j        |           t          j        dt	          |          z             t          j        dj                    t          j        j        dk    rdj        dnd           t          j        dt	          j                              j        d	z  }t          j
        j        |          }|t          j        d
|            nt          j        d|dd           j        dz  }t          j
        j        |          }|t          j        d|            nt          j        d|dd           t          t          j                  }|*t          j        d|                                            nt          j        dj         d           | dk    rt          j                     |                                  d}t          j        |           t          j        dt	          |          z             t          j        dj        dgj        j        k    rdgng R   t          j        d                    j        j        j        j        j        j                             	 t3          fdt5          j                    D                       }t          j        dj         d|j         d           n-# t<          $ r  t          j        dj         d           Y nw xY wt          j        dj        dz   dj        dz   dj          d           t          j        d j!        dz   dj!        dz              t          j                     d!}t          j        |           t          j        dt	          |          z             d"}	t          j        |	                    d#d$d%d&d'                     t          j        d( d)d( d)d* d)d* d)d+ 	           d,}
d }d }tE          j                  D ]\  }}|#                              }d-$                    |          }d.|v r
||j%        }n#d/|v rt	          |j%                  d0k    r|j%        }t          j        |
                    |t	          |j%                  |j&        |j'        |                     t          j                     |                                  d1}t          j        |           t          j        dt	          |          z             (                                }t          j        d2                    j)        j)        |k    rd3nd4|d5                     	 d6}j*        rUj+        j,        k    }d7                    t[          j,        d89          |rd3nd:          }t          j        d;|            n# t\          $ r Y nw xY w|ryt_          |          }|ret          j                     d<}t          j        |           t          j        dt	          |          z             t          j        d=|d>                     t          j        d?|d@                     t          j        dA|dB          dC|dD                     t          j        dE|dF                     t          j        dG|dH                     t          j        dI|dJ                     t          j        dK|dL                     |dM         rt          j        dN|dM                     t          j        dO|dP                     d S d S |rta          |          }|rt          j                     dQ}t          j        |           t          j        dt	          |          z             t          j        dR|d@                     t          j        dG|dH                     t          j        dA|dS                     d S d S d S )TNz Image Headerr  zImage version: r   zEntry point: z#8xzEntry point not setz
Segments: r   zFlash size: zInvalid flash size (z#02xr   r   zFlash freq: zInvalid flash frequency (zFlash mode: zInvalid flash mode (r   z Extended Image HeaderzWP pin: z
(disabled)zFlash pins drive settings: clk_drv: {:#02x}, q_drv: {:#02x}, d_drv: {:#02x}, cs0_drv: {:#02x}, hd_drv: {:#02x}, wp_drv: {:#02x}c              3   P   K   | ] }t          |d d          j        k    |V  !dS )rt   N)getattrr}   )r  r>  r   s     ra   r  z$_print_image_info.<locals>.<genexpr>l  sH        4$775=HH HHHH rc   r  r:  z (Unknown ID)zMinimal chip revision: vr  rj   z, (legacy min_rev = zMaximal chip revision: vzSegments Informationz#{:>7}  {:>7}  {:>10}  {:>10}  {:10}SegmentLengthz	Load addrz	File offszMemory typesz-------r   z
----------z------------z%{:7}  {:#07x}  {:#010x}  {:#010x}  {}, DROMDRAMr  z Image FooterzChecksum: {:#04x} ({})validzinvalid - calculated r  zNot appendedz{} ({})Fr#  invalidzValidation hash: zApplication InformationzProject name: r*  zApp version: r)  zCompile time: r+  r[   r   zELF file SHA256: r-  z	ESP-IDF: r,  zMinimal eFuse block revision: r.  zMaximal eFuse block revision: r/  r0  zMMU page size: zSecure version: r'  zBootloader InformationzBootloader version: r9  )1r   r   r\   rE  r   r)  r   r   flash_size_freqr   
ROM_LOADERFLASH_SIZESr   FLASH_FREQUENCYr   r   wp_pinWP_PIN_DISABLEDr   clk_drvq_drvd_drvcs_drvhd_drvwp_drvnextr   valuesr}   r]   StopIterationr@  rA  r?  r   get_memory_typer  r   r   	file_offscalculate_checksumchecksumappend_digeststored_digestcalc_digestr   AttributeErrorr6  r=  )r>  r   r  flash_s_bitsflash_sflash_fr_bitsflash_frr   
chip_classheaders_str
format_strapp_desc_segbootloader_desc_segidxr   segsseg_namecalc_checksum
digest_msgis_validapp_descbootloader_descr   s                         @ra   rF  rF  .  s	   dD))EIKKKzz||***EIeIcCJJI///000Iq   	/(...."   I03u~..00111 (4/L !1!=|LLG	***++++?<????@@@ )D0M!%"2"BMRRH	+++,,,,EEEEEFFF $K1ABBJ	5!1!1!3!3556666>5+;>>>??? y	::<<777	%	#E

"###	*u|***	
$|u/DDDl^^"	
 	
 	
 	
 		AAGB B	
 	
 	
	@    %,..    J
 IJ%-JJ:3GJJJKKKK 	@ 	@ 	@I>%->>>?????	@	2"c)2 2,1,>,D2 2!&2 2 2	
 	
 	

 		G"c)G G,1,>,DG G	
 	
 	
 IKKK #EIeIcCJJ7KIxk>	
 	
  
 IIIGIIxII8IIxIIJJJ8JLen-- 
 
S""5))99T??T>>l28LLt^^38}}""&)h#	c3sx==#(CM8TT	
 	
 	
 	
 IKKK zz||***EIeIcCJJ,,..MI ''N >]22 A]AAA	
 	
	 	 	
#
 	8*e.??H"))u(E:::#2 J I6*66777     G"<00 	GIKKK-EIeIcCJJ&'''IAx'?AABBBI;hy&9;;<<<ILx'7LL(6:JLLMMMIF(3C*DFFGGGI7(9"577888IU:R1SUU   IU:R1SUU   ( I	GH_,EGGHHHIE2B)CEEFFFFF%	G 	G( 
 	G01DEE 	GIKKK,EIeIcCJJ&'''II_Y-GIIJJJI>/)"<>>???IE{'CEEFFFFF	G 	G	G 	Gs&   AL( ('MMAX$ $
X10X1rawr   c           
         |                     dd          |                     dd          }|                     dd          }	|                     dd          }
|dvrt          d	| d
          |)|dv r%t          d|                                 d          	 t          |         }n<# t          $ r/ t          d| dd                    t                     d          w xY wt          | d           } | st          d          | d         d         }|k     rt          ddd|dd          ||dk    rt          |j	        ||	|
           5 }| D ]g\  }}t          |          \  }}|dnd| d}t          j        d| d|dd           t          ||||||          }|                    ||           h	 ddd           n# 1 swxY w Y   t          j        d t          j                            |          dd!| d"           nG|d#k    rJ|t%          j                    nt)          |d$          	 fd%}| D ]K\  }} ||           t          |          \  }}t          ||||||          }                    |           L|r |t-          |                                                     }|                                 n# |                                 w w xY w|Kt3          t$          j                  r1t          j        d&|dd'dd(                                           S t          j        d |dd!| d)dd(           dS ||d*k    rt7                      }t9          |           d+k    rt          j        d,           | D ]d\  }}t7                      }t          |          \  }}t          ||||||          }|                    ||           |                    |           e|                     |           t          j        d t          j                            |          dd!| d)dd(           dS )-a  
    Merge multiple binary files into a single output file for flashing to an ESP device.

    Take multiple binary files along with their flash addresses and merge them
    into a unified binary in either raw, UF2, or Intel HEX format.
    Also apply necessary flash parameters and ensure correct alignment for flashing.

    Args:
        addr_data: List of (address, data) tuples specifying where
            to write each file or data in flash memory. The data can be
            a file path (str), bytes, or a file-like object.
        chip: Target ESP device type (e.g., ``"esp32"``).
        output: Path to the output file where the merged binary will be written.
            If None, the merged binary will be returned as bytes.
        flash_freq: Flash frequency to set in the image header
            (``"keep"`` to retain current).
        flash_mode: Flash mode to set in the image header
            (``"keep"`` to retain current).
        flash_size: Flash size to set in the image header
            (``"keep"`` to retain current).
        format: Output format (``"raw"``, ``"uf2"``, or ``"hex"``).

    Keyword Args:
        target_offset (int): Starting offset for the merged output.
        pad_to_size (str | None): If specified, pad the output to a specific flash size.
        chunk_size (int | None): Chunk size for UF2 format.
        md5_disable (bool): If True, disable MD5 checks in UF2 format.

    Returns:
        The merged binary data as bytes if output is None; otherwise,
        returns None after writing to file.
    target_offsetr   pad_to_sizeN
chunk_sizemd5_disableF)r  uf2rC  zInvalid format: 'z#', choose from 'raw', 'uf2', 'hex'.)r  rC  z#Output file must be specified with z format.Invalid chip choice: '' (choose from r]  r  c                     | d         S r,  r  r-  s    ra   r/  zmerge_bin.<locals>.<lambda>  s
    ! rc   r0  zNo input data.zOutput data target offset is r   z. Input data offset z is before this.r  )md5_enabledr   r   zAdding z at r   r   z bytes to file 'z/', ready to be flashed with any ESP USB Bridge.r  r   c                 h                         d| z
                                  z
  z             d S )Nr4  )r   r   )
flash_offsofr  s    ra   r    zmerge_bin.<locals>.pad_to=  s2    J$>$JKLLLLLrc   Merged z! bytes, ready to flash to offset rj   z', ready to flash to offset rC  r   a  Only one input file specified, output may include additional padding if input file was previously merged. Please refer to the documentation for more information: https://docs.espressif.com/projects/esptool/en/latest/esptool/basic-commands.html#hex-output-format)!r   r   rE  r   KeyErrorr  r   rQ  r   UF2_FAMILY_IDr   r   r\   r
  add_fileospathgetsizer   r   r   r   r   r   r_  rA  r   r   r   r   	frombytesmergewrite_hex_file)r  r>  r   r   r   r   r   re  r  r  r  r}  
first_addrwriterr   r   r   r   r    r   r   outihexr  r  s                          @@ra   	merge_binr    s   X  OQ77M$jj==K#ZZd;;J

=%88K***KKKK
 
 	
 ~&N22Wv||~~WWWXXX
t_

 
 
 
RTRR$))I:N:NRRR
 
 	

 ynn555I +)***1aJM!!AM@ A A!+@A A A
 
 	

 foo$'	
 
 
 	-
 ' - -
d )$v$*NF	<F<<<<<<===2j*j%  e,,,,-	- 	- 	- 	- 	- 	- 	- 	- 	- 	- 	- 	- 	- 	- 	- 		<RW__V,,L < < < < <	
 	
 	
 	

 
5#^RZ\\\fd1C1C	M M M M M M (    
dt$T??q2j*j%   6'445557799D!


 !



 " >jRZ88>IW$WWWMWWWW   ;;== I@= @ @& @ @,9?@ @ @   4		%jjy>>QKv   $ 	 	JD$::D HE1.D*j*e E NN5$'''IIdOOOO6"""	<RW__V,,L < < < <(5;< < <	
 	
 	
 4s,   B, ,9C%A+GGGBK K5rM   c                 n   |                     dd          }|                     dd          }|                     dd          }	|                     dd          }
|                     dd	          }|                     d
d	          }|                     dd          }|                     dd          }|                     dd	          }|                     dd          }|                     dd          }|                     dd	          }|t          vr.t          d| dd                    t                     d          t	          |           \  }}t          |          }t          j        d|                                 d           |dk    r|t          |         j
        }|t          d| d           |            }|dk    r	|rd|_        |rd|_        ||_        |	|_        |
|_        ||_        |j        rd	|_        n@||_        n8|dk    rt#                      }n#|dk    rt%                      }nt'                      }|j        |_        t*          |         |_        |r#|                    t1          |                     nd}|j        D ]}d|j        v r|} n|r|                    |j                  r|j        rt=          |j                  }|r|d          r)|                    t1          |d                               nvtA          |j                  D ]M}|j        d!z
  d"z
  |z  dk    r7|                    |           t          j        d#|j!        d$z   d%            nNt          j"        d&           |r|j#        n|j        |_#        |rt1          |          |_$        |j%        &                    |          |_'        |xj'        |j%        (                    |          z  c_'        |r!|)                                |_*        ||_+        nSd' |j#        D             }|r@|                    |d         j                  r |)                                |_*        d(|_+        |r(t          j        d)           |,                                 t[          |j#                  }|.                                 t[          |j#                  |k    r:|t[          |j#                  z
  }t          j        d*| d+|dk    rd,nd- d           |/                                 t          j        d.|                                 d/           |d0k    r|| d1n|}|0                    |          }tc          td          tf          td          dz  td          f         z  dz  |4                    |                    S )2a  
    Convert ELF data into a firmware image suitable for flashing onto an ESP device.

    Args:
        input: Path to the ELF file to convert, opened file-like object,
            or the ELF data as bytes.
        chip: Target ESP device type.
        output: Path to save the generated firmware image. If "auto", a default
            pre-defined path is used. If None, the image is not written to a file,
            but returned as bytes.
        flash_freq: Flash frequency to set in the image header.
        flash_mode: Flash mode to set in the image header.
        flash_size: Flash size to set in the image header.

    Keyword Args:
        version (int): ESP8266-only, firmware image version.
        min_rev (int): Minimum chip revision required in legacy format.
        min_rev_full (int): Minimum chip revision required in extended format.
        max_rev_full (int): Maximum chip revision allowed in extended format.
        secure_pad (bool): ESP32-only, enable secure padding.
        secure_pad_v2 (bool): Enable version 2 secure padding.
        elf_sha256_offset (int): Offset for storing the ELF file's SHA-256 hash.
        append_digest (bool): Whether to append a digest to the firmware image.
        use_segments (bool): Use ELF segments instead of sections.
        flash_mmu_page_size (str): MMU page size for flash mapping.
        pad_to_size (str): Pad the final image to a specific flash size.
        ram_only_header (bool): Include only RAM segments and no SHA-256 hash.

    Returns:
        The firmware image as bytes if output is None; otherwise,
        returns None after writing to file.
        When ESP8266 V1 image is generated, returns a tuple of bytes
        of IROM data and the rest if output is None; otherwise,
        returns None after writing to two files.
    r)  r   rA  r   r@  r?  r  
secure_padFsecure_pad_v2elf_sha256_offsetNru  Tuse_segmentsflash_mmu_page_sizer  ram_only_headerr  r  r]  r  z	Creating z	 image...r   z(Missing bootloader image definition for rj   r  r%  2.flash.appdescr0  r7   r.   z$MMU page size not specified, set to r   r%  zApp description segment is not aligned to MMU page size, probably linker script issue or wrong MMU page size. Try to set MMU page size parameter manually.c                 $    g | ]}d |j         v |S )r  )r(  )r  r   s     ra   r  zelf2image.<locals>.<listcomp>	  s%    VVV9ISX9U9U9U9U9Urc      z_Image has only RAM segments visible. ROM segments are hidden and SHA256 digest is not appended.r  z ELF sectionsrd   zSuccessfully created z image.auto_image)5r   r   r   r  r   r   r   r\   rE  r   r   r  rA  r@  r?  r  ru  r	   r
   r   r   r   r   set_mmu_page_sizer   sectionsr(  is_flash_addrr   MMU_PAGE_SIZE_CONFr6  r   reversed
IROM_ALIGNr   r   r  rc  r   rb  r   r   
elf_sha256r  sort_segmentsr   merge_adjacent_segmentsr   default_output_namer   r   tuplesave)r   r>  r   r   r   r   re  r)  rA  r@  r?  r  r  r  ru  r  r  r  r  r   r   r  bootloader_imager   appdesc_segr   r  r0  appdesc_segsbeforedeltas                                  ra   	elf2imager  t  s   \ ::i++G::i++G

>155L

>599Lzz,66J **_e<<M$*JJ/BD$I$I **_d;;MNE::L&,jj1F&M&M$jj==K"JJ'8%@@O9RTRR$))I:N:NRRR
 
 	
 U##LD&AI1$**,,111222y$T?;#OOOOPPP$$&&E7??z?"E 	#"E)) /  	0"'E"/E	C'))	C&((&((|E":.E & 01D E EFFFF: 	 	C38++! , 	##K$455	 (	
 '{'788H O, ++,<Xo=V,W,WXXXX
 *2%2J)K)K  ',r1A5F!KK!33MBBBI!A#(#3t#;!A !A !A   "E L K   $0?QZZQZEN :,[99!,AA*MME	U-BB:NNN 
+88::"3
 WVu~VVV 	+E//Q0DEE 	+ xxzzE&*E# 	I	
 	
 	
 	  F	!!###
5>f$$U^,,,	JEJJeaiissRJJJKKK	LLNNNI;djjll;;;<<<$*ND**622edlE122T95::f;M;MNNNrc   c                  :    ddl m}  t          j        |            dS )z,
    Print the current esptool version.
    r   __version__N)rd   r  r   r\   r  s    ra   r)  r)  #	  s,     Ikrc   )r   )Nr*  r   )r   )F)r   )Nr   F)r   r   r   F)rK   )rK   F)r  )Nr   r   r   r  )NNrM   r%   )rV   N)^r   r   r  r   r  r   rT  r   intelhexr   serialr   typingr   	bin_imager   r   r	   r
   r   loaderr   r   r   r   r   loggerr   targetsr   r   r   
uf2_writerr   utilr   r   r   r   r   r   r   r   r   r   r    r!   r   r  r   r   r   DEFAULT_PORTESP_ROM_BAUDstrrR  boolr   r   r   r   r   r   r  r   r   r
  rB  r  r  r}   r  rL  rN  r  r  r  r   r  r  r  r  r  rv   r  ra  r6  r=  rK  rD  rF  r  r  r)  r  rc   ra   <module>r     s    				 				  



             " " " " " "       1 1 1 1 1 1 1 1         
                    3 3 3 3 3 3 3 3 3 3 ! ! ! ! ! !           	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	   




  '' 	% 	%	
 	% 	% 	& 	& 	& 	' 	' 	& 	' 	' 	'  	'!" 	%#$ 




/   6 	  &&'4h h
h
h h 	h
 h h h h h^%%) %%K %%D %% %% %% %%PB) Bc Bd B B B BQ Q9 Qs Q3 Qc QSW Q Q Q Q CG2 2	2 2(+2584Z2
T\2 2 2 2j, , ,4 ,5c3QU:AU;V , , , ,89 t    &p p pl T T	TE#{*+,T T 	T
 T 
T T T Tn3) 3 3 3 3 3( t    $ EI@O @O	@O3S#s23c9TA@O 
@O @O @O @OF7* 7* 7* 7*tU UY Ut U U U U U:( (i (# (S ( (RV ( ( ( (VY 4    
A	 
Ad 
A 
A 
A 
A)     .  S  T    2 : :	:: : $J	:
 : : T\: : : :@ ?1 ?1	?1E#{*+,?1 ?1 	?1
 ?1 ?1 
?1 ?1 ?1 ?1DE E9 ES E E E E E FKN N	NN'*N>BN	N N N N*M*9 M* M* M* M* M*`%> %>I %>3 %>$ %> %> %> %>P0) 0	 0 0 0 0n1 1 1h  @ LP3/ 3/eC$45663/>ADj3/	3/ 3/ 3/ 3/l% %5 %d
 %c % % % %PhGC hGu hG hG hG hG hG\ X XE#{*+,X
X $JX 	X
 X X X T\X X X X| !lO lOlO
lO $JlO d
	lO
 lO lO U54<&''$.lO lO lO lO^     rc   