From ae422f12b3aafcb922e00ae6a603df55e623c78c Mon Sep 17 00:00:00 2001
From: cnlohr <lohr85@gmail.com>
Date: Fri, 9 Jun 2023 00:33:42 -0400
Subject: [PATCH] Change order of operations for write64 on the ESP programmer.

---
 minichlink/pgm-esp32s2-ch32xx.c | 28 +++++++++++++++++++++++++---
 1 file changed, 25 insertions(+), 3 deletions(-)

diff --git a/minichlink/pgm-esp32s2-ch32xx.c b/minichlink/pgm-esp32s2-ch32xx.c
index 11d0048..7b02bbb 100644
--- a/minichlink/pgm-esp32s2-ch32xx.c
+++ b/minichlink/pgm-esp32s2-ch32xx.c
@@ -100,6 +100,17 @@ int ESPFlushLLCommands( void * dev )
 
 	eps->commandbuffer[0] = 0xad; // Key report ID
 	eps->commandbuffer[eps->commandplace] = 0xff;
+
+#if 0
+	int i;
+	for( i = 0; i < eps->commandplace; i++ )
+	{
+		if( ( i & 0xff ) == 0 ) printf( "\n" );
+		printf( "%02x ", eps->commandbuffer[i] );
+	}
+	printf("\n" );
+#endif
+
 	r = hid_send_feature_report( eps->hd, eps->commandbuffer, 255 );
 	eps->commandplace = 1;
 	if( r < 0 )
@@ -228,17 +239,28 @@ int ESPBlockWrite64( void * dev, uint32_t address_to_write, uint8_t * data )
 {
 	struct ESP32ProgrammerStruct * eps = (struct ESP32ProgrammerStruct *)dev;
 	ESPFlushLLCommands( dev );
+
 	Write2LE( eps, 0x0bfe );
 	Write4LE( eps, address_to_write );
 	int i;
+	int timeout = 0;
 	for( i = 0; i < 64; i++ ) Write1( eps, data[i] );
+
+	// Not sure why this is needed.
+	ESPWaitForDoneOp( dev, 0 );
+
 	do
 	{
 		ESPFlushLLCommands( dev );
+		timeout++;
+		if( timeout > 1000 )
+		{
+			fprintf( stderr, "Error: Timed out block-writing 64\n" );
+		}
 	} while( eps->replylen < 2 );
-	
-	// Not sure why this is needed.
-	ESPWaitForDoneOp( dev, 0 );
+
+	//printf( "Reply %d: %02x %02x %02x %02x %08x\n", timeout, eps->reply[0], eps->reply[1], eps->reply[2], eps->reply[3], address_to_write );
+
 
 	return eps->reply[1];
 }
-- 
GitLab