This commit is contained in:
Jelmer
2023-09-14 12:38:03 +02:00
64 changed files with 4209 additions and 313 deletions

View File

@@ -0,0 +1,281 @@
TRACE +0.008 command op=0x0a data len=4 wait_response=1 timeout=3.000 data=00100040
TRACE +0.000 Write 14 bytes: c0000a04000000000000100040c0
TRACE +0.002 Read 1 bytes: c0
TRACE +0.000 Read 13 bytes: 010a04006f80e02c00000000c0
TRACE +0.000 Received full packet: 010a04006f80e02c00000000
Detecting chip type...
TRACE +0.000 command op=0x14 data len=0 wait_response=1 timeout=3.000 data=
TRACE +0.000 Write 10 bytes: c00014000000000000c0
TRACE +0.008 Read 1 bytes: c0
TRACE +0.000 Read 33 bytes:
011418006f80e02c 0000000000000000 | ....o..,........
0000000c0d000000 0000000000000000 | ................
c0 | .
TRACE +0.000 Received full packet:
011418006f80e02c 0000000000000000 | ....o..,........
0000000c0d000000 0000000000000000 | ................
TRACE +0.000 command op=0x0a data len=4 wait_response=1 timeout=3.000 data=80f58740
TRACE +0.000 Write 14 bytes: c0000a04000000000080f58740c0
TRACE +0.002 Read 1 bytes: c0
TRACE +0.000 Read 13 bytes: 010a04000000000000000000c0
TRACE +0.000 Received full packet: 010a04000000000000000000
TRACE +0.000 command op=0x0a data len=4 wait_response=1 timeout=3.000 data=50080b60
TRACE +0.000 Write 14 bytes: c0000a04000000000050080b60c0
TRACE +0.000 Read 1 bytes: c0
TRACE +0.000 Read 13 bytes: 010a04000000000800000000c0
TRACE +0.000 Received full packet: 010a04000000000800000000
TRACE +0.008 command op=0x0a data len=4 wait_response=1 timeout=3.000 data=50080b60
TRACE +0.000 Write 14 bytes: c0000a04000000000050080b60c0
TRACE +0.002 Read 1 bytes: c0
TRACE +0.000 Read 13 bytes: 010a04000000000800000000c0
TRACE +0.000 Received full packet: 010a04000000000800000000
TRACE +0.000 command op=0x0a data len=4 wait_response=1 timeout=3.000 data=50080b60
TRACE +0.000 Write 14 bytes: c0000a04000000000050080b60c0
TRACE +0.000 Read 1 bytes: c0
TRACE +0.000 Read 13 bytes: 010a04000000000800000000c0
TRACE +0.000 Received full packet: 010a04000000000800000000
Chip is ESP32-C6 (QFN40) (revision v0.0)
Features: WiFi 6, BT 5, IEEE802.15.4
Crystal is 40MHz
TRACE +0.000 command op=0x0a data len=4 wait_response=1 timeout=3.000 data=44080b60
TRACE +0.000 Write 14 bytes: c0000a04000000000044080b60c0
TRACE +0.010 Read 1 bytes: c0
TRACE +0.000 Read 13 bytes: 010a0400e85342ca00000000c0
TRACE +0.000 Received full packet: 010a0400e85342ca00000000
TRACE +0.000 command op=0x0a data len=4 wait_response=1 timeout=3.000 data=48080b60
TRACE +0.000 Write 14 bytes: c0000a04000000000048080b60c0
TRACE +0.000 Read 1 bytes: c0
TRACE +0.000 Read 13 bytes: 010a04004c40feff00000000c0
TRACE +0.000 Received full packet: 010a04004c40feff00000000
MAC: 40:4c:ca:ff:fe:42:53:e8
TRACE +0.000 command op=0x0a data len=4 wait_response=1 timeout=3.000 data=44080b60
TRACE +0.000 Write 14 bytes: c0000a04000000000044080b60c0
TRACE +0.008 Read 1 bytes: c0
TRACE +0.000 Read 13 bytes: 010a0400e85342ca00000000c0
TRACE +0.000 Received full packet: 010a0400e85342ca00000000
TRACE +0.002 command op=0x0a data len=4 wait_response=1 timeout=3.000 data=48080b60
TRACE +0.000 Write 14 bytes: c0000a04000000000048080b60c0
TRACE +0.000 Read 1 bytes: c0
TRACE +0.000 Read 13 bytes: 010a04004c40feff00000000c0
TRACE +0.000 Received full packet: 010a04004c40feff00000000
BASE MAC: 40:4c:ca:42:53:e8
TRACE +0.000 command op=0x0a data len=4 wait_response=1 timeout=3.000 data=44080b60
TRACE +0.000 Write 14 bytes: c0000a04000000000044080b60c0
TRACE +0.008 Read 1 bytes: c0
TRACE +0.000 Read 13 bytes: 010a0400e85342ca00000000c0
TRACE +0.000 Received full packet: 010a0400e85342ca00000000
!!! TRACE +0.000 command op=0x0a data len=4 wait_response=1 timeout=3.000 data=48080b60
TRACE +0.000 Write 14 bytes: c0000a04000000000048080b60c0
TRACE +0.002 Read 1 bytes: c0
TRACE +0.000 Read 13 bytes: 010a04004c40feff00000000c0
TRACE +0.000 Received full packet: 010a04004c40feff00000000
MAC_EXT: ff:fe
Enabling default SPI flash mode...
!!!! TRACE +0.000 command op=0x0d data len=8 wait_response=1 timeout=3.000 data=0000000000000000
TRACE +0.000 Write 18 bytes:
c0000d0800000000 0000000000000000 | ................
00c0 | ..
TRACE +0.000 Read 1 bytes: c0
TRACE +0.000 Read 13 bytes: 010d04004c40feff00000000c0
TRACE +0.000 Received full packet: 010d04004c40feff00000000
v TRACE +0.008 command op=0x0a data len=4 wait_response=1 timeout=3.000 data=18300060
TRACE +0.000 Write 14 bytes: c0000a04000000000018300060c0
TRACE +0.002 Read 1 bytes: c0
TRACE +0.000 Read 13 bytes: 010a04000000008000000000c0
TRACE +0.000 Received full packet: 010a04000000008000000000
v TRACE +0.000 command op=0x0a data len=4 wait_response=1 timeout=3.000 data=20300060
TRACE +0.000 Write 14 bytes: c0000a04000000000020300060c0
TRACE +0.000 Read 1 bytes: c0
TRACE +0.000 Read 13 bytes: 010a04000000007000000000c0
TRACE +0.000 Received full packet: 010a04000000007000000000
v TRACE +0.000 command op=0x09 data len=16 wait_response=1 timeout=3.000 data=2830006017000000ffffffff00000000
TRACE +0.000 Write 26 bytes:
c000091000000000 0028300060170000 | .........(0.`...
00ffffffff000000 00c0 | ..........
TRACE +0.010 Read 1 bytes: c0
TRACE +0.000 Read 13 bytes: 010904000000007000000000c0
TRACE +0.000 Received full packet: 010904000000007000000000
TRACE +0.000 command op=0x09 data len=16 wait_response=1 timeout=3.000 data=1830006000000090ffffffff00000000
TRACE +0.000 Write 26 bytes:
c000091000000000 0018300060000000 | ..........0.`...
90ffffffff000000 00c0 | ..........
TRACE +0.000 Read 1 bytes: c0
TRACE +0.000 Read 13 bytes: 010904000000007000000000c0
TRACE +0.000 Received full packet: 010904000000007000000000
TRACE +0.008 command op=0x09 data len=16 wait_response=1 timeout=3.000 data=203000609f000070ffffffff00000000
TRACE +0.000 Write 26 bytes:
c000091000000000 00203000609f0000 | ......... 0.`...
70ffffffff000000 00c0 | p.........
TRACE +0.002 Read 1 bytes: c0
TRACE +0.000 Read 13 bytes: 010904000000007000000000c0
TRACE +0.000 Received full packet: 010904000000007000000000
TRACE +0.000 command op=0x09 data len=16 wait_response=1 timeout=3.000 data=5830006000000000ffffffff00000000
TRACE +0.000 Write 26 bytes:
c000091000000000 0058300060000000 | .........X0.`...
00ffffffff000000 00c0 | ..........
TRACE +0.008 Read 1 bytes: c0
TRACE +0.000 Read 13 bytes: 010904000000007000000000c0
TRACE +0.000 Received full packet: 010904000000007000000000
TRACE +0.000 command op=0x09 data len=16 wait_response=1 timeout=3.000 data=0030006000000400ffffffff00000000
TRACE +0.000 Write 26 bytes:
c000091000000000 0000300060000004 | ..........0.`...
00ffffffff000000 00c0 | ..........
TRACE +0.002 Read 1 bytes: c0
TRACE +0.000 Read 13 bytes: 010904000000007000000000c0
TRACE +0.000 Received full packet: 010904000000007000000000
TRACE +0.000 command op=0x0a data len=4 wait_response=1 timeout=3.000 data=00300060
TRACE +0.000 Write 14 bytes: c0000a04000000000000300060c0
TRACE +0.008 Read 1 bytes: c0
TRACE +0.000 Read 13 bytes: 010a04000000000000000000c0
TRACE +0.000 Received full packet: 010a04000000000000000000
!!! TRACE +0.000 command op=0x0a data len=4 wait_response=1 timeout=3.000 data=58300060
TRACE +0.000 Write 14 bytes: c0000a04000000000058300060c0
TRACE +0.002 Read 1 bytes: c0
TRACE +0.000 Read 13 bytes: 010a0400c840170000000000c0
TRACE +0.000 Received full packet: 010a0400c840170000000000
!!! TRACE +0.000 command op=0x09 data len=16 wait_response=1 timeout=3.000 data=1830006000000080ffffffff00000000
TRACE +0.000 Write 26 bytes:
c000091000000000 0018300060000000 | ..........0.`...
80ffffffff000000 00c0 | ..........
TRACE +0.000 Read 1 bytes: c0
TRACE +0.008 Read 13 bytes: 01090400c840170000000000c0
TRACE +0.000 Received full packet: 01090400c840170000000000
TRACE +0.000 command op=0x09 data len=16 wait_response=1 timeout=3.000 data=2030006000000070ffffffff00000000
TRACE +0.000 Write 26 bytes:
c000091000000000 0020300060000000 | ......... 0.`...
70ffffffff000000 00c0 | p.........
TRACE +0.002 Read 1 bytes: c0
TRACE +0.000 Read 13 bytes: 01090400c840170000000000c0
TRACE +0.000 Received full packet: 01090400c840170000000000
TRACE +0.000 command op=0x0a data len=4 wait_response=1 timeout=3.000 data=18300060
TRACE +0.000 Write 14 bytes: c0000a04000000000018300060c0
TRACE +0.008 Read 1 bytes: c0
TRACE +0.000 Read 13 bytes: 010a04000000008000000000c0
TRACE +0.000 Received full packet: 010a04000000008000000000
TRACE +0.000 command op=0x0a data len=4 wait_response=1 timeout=3.000 data=20300060
TRACE +0.000 Write 14 bytes: c0000a04000000000020300060c0
TRACE +0.002 Read 1 bytes: c0
TRACE +0.000 Read 13 bytes: 010a04000000007000000000c0
TRACE +0.000 Received full packet: 010a04000000007000000000
TRACE +0.000 command op=0x09 data len=16 wait_response=1 timeout=3.000 data=2830006007000000ffffffff00000000
TRACE +0.000 Write 26 bytes:
c000091000000000 0028300060070000 | .........(0.`...
00ffffffff000000 00c0 | ..........
TRACE +0.008 Read 1 bytes: c0
TRACE +0.000 Read 13 bytes: 010904000000007000000000c0
TRACE +0.000 Received full packet: 010904000000007000000000
TRACE +0.000 command op=0x09 data len=16 wait_response=1 timeout=3.000 data=1c3000600700005cffffffff00000000
TRACE +0.000 Write 26 bytes:
c000091000000000 001c300060070000 | ..........0.`...
5cffffffff000000 00c0 | \.........
TRACE +0.002 Read 1 bytes: c0
TRACE +0.000 Read 13 bytes: 010904000000007000000000c0
TRACE +0.000 Received full packet: 010904000000007000000000
TRACE +0.000 command op=0x09 data len=16 wait_response=1 timeout=3.000 data=18300060000000f0ffffffff00000000
TRACE +0.000 Write 26 bytes:
c000091000000000 0018300060000000 | ..........0.`...
f0ffffffff000000 00c0 | ..........
TRACE +0.008 Read 1 bytes: c0
TRACE +0.000 Read 13 bytes: 010904000000007000000000c0
TRACE +0.000 Received full packet: 010904000000007000000000
TRACE +0.000 command op=0x09 data len=16 wait_response=1 timeout=3.000 data=203000605a000070ffffffff00000000
TRACE +0.000 Write 26 bytes:
c000091000000000 00203000605a0000 | ......... 0.`Z..
70ffffffff000000 00c0 | p.........
TRACE +0.000 Read 1 bytes: c0
TRACE +0.000 Read 13 bytes: 010904000000007000000000c0
TRACE +0.000 Received full packet: 010904000000007000000000
TRACE +0.000 command op=0x09 data len=16 wait_response=1 timeout=3.000 data=0430006010000000ffffffff00000000
TRACE +0.000 Write 26 bytes:
c000091000000000 0004300060100000 | ..........0.`...
00ffffffff000000 00c0 | ..........
TRACE +0.012 Read 1 bytes: c0
TRACE +0.000 Read 13 bytes: 010904000000007000000000c0
TRACE +0.000 Received full packet: 010904000000007000000000
TRACE +0.000 command op=0x09 data len=16 wait_response=1 timeout=3.000 data=5830006000000000ffffffff00000000
TRACE +0.000 Write 26 bytes:
c000091000000000 0058300060000000 | .........X0.`...
00ffffffff000000 00c0 | ..........
TRACE +0.000 Read 1 bytes: c0
TRACE +0.000 Read 13 bytes: 010904000000007000000000c0
TRACE +0.000 Received full packet: 010904000000007000000000
TRACE +0.000 command op=0x09 data len=16 wait_response=1 timeout=3.000 data=0030006000000400ffffffff00000000
TRACE +0.000 Write 26 bytes:
c000091000000000 0000300060000004 | ..........0.`...
00ffffffff000000 00c0 | ..........
TRACE +0.010 Read 1 bytes: c0
TRACE +0.000 Read 13 bytes: 010904000000007000000000c0
TRACE +0.000 Received full packet: 010904000000007000000000
TRACE +0.000 command op=0x0a data len=4 wait_response=1 timeout=3.000 data=00300060
TRACE +0.000 Write 14 bytes: c0000a04000000000000300060c0
TRACE +0.000 Read 1 bytes: c0
TRACE +0.000 Read 13 bytes: 010a04000000000000000000c0
TRACE +0.000 Received full packet: 010a04000000000000000000
TRACE +0.000 command op=0x0a data len=4 wait_response=1 timeout=3.000 data=58300060
TRACE +0.000 Write 14 bytes: c0000a04000000000058300060c0
TRACE +0.010 Read 1 bytes: c0
TRACE +0.000 Read 13 bytes: 010a0400c800000000000000c0
TRACE +0.000 Received full packet: 010a0400c800000000000000
TRACE +0.000 command op=0x09 data len=16 wait_response=1 timeout=3.000 data=1830006000000080ffffffff00000000
TRACE +0.000 Write 26 bytes:
c000091000000000 0018300060000000 | ..........0.`...
80ffffffff000000 00c0 | ..........
TRACE +0.000 Read 1 bytes: c0
TRACE +0.000 Read 13 bytes: 01090400c800000000000000c0
TRACE +0.000 Received full packet: 01090400c800000000000000
TRACE +0.000 command op=0x09 data len=16 wait_response=1 timeout=3.000 data=2030006000000070ffffffff00000000
TRACE +0.000 Write 26 bytes:
c000091000000000 0020300060000000 | ......... 0.`...
70ffffffff000000 00c0 | p.........
TRACE +0.010 Read 1 bytes: c0
TRACE +0.000 Read 13 bytes: 01090400c800000000000000c0
TRACE +0.000 Received full packet: 01090400c800000000000000
Manufacturer: c8
Device: 4017
Detected flash size: 8MB

View File

@@ -0,0 +1,96 @@
C6 flash starting
Write 1 bytes: c000082400000000000707122055555555
55555555555555555555555555555555
555555555555555555555555c0
Read 1 bytes: 004553502d524f4d3a657370333263362d32303232303931390d0a4275696c643a53657020313920323032320d0a7273743a3078312028504f5745524f4e292c626f6f743a307836362028444f574e4c4f4144285553422f55415254302f5344494f5f5245495f46454f29290d0a77616974696e6720666f7220646f776e6c6f61640d0a
Write 1 bytes: c000082400000000000707122055555555
55555555555555555555555555555555
555555555555555555555555c0
Read 1 bytes: c0010804000707122000000000c0
Write 1 bytes: c0000a04000000000000100040c0
Read 1 bytes: c0010804000707122000000000c0
c0010804000707122000000000c0
c0010804000707122000000000c0
c0010804000707122000000000c0
c0010804000707122000000000c0
c0010804000707122000000000c0
c0010804000707122000000000c0
c0010a04006f80e02c00000000c0
Write 1 bytes: c0000a04000000000048080b60c0 600b0848!!! read 0x12
c0000a04000000000044080b60c0 600b0844 read 0x11
Read 1 bytes: c0010a04004c40feff00000000c0
c0010a0400e85342ca00000000c0
esptool: c0010a04004c40feff00000000c0
>>>>> Write 1 bytes: c0000a0400000000004c080b60c0 600b084C!!! read 0x13
esptool: c0000a04000000000048080b60c0 600b0848 read 0x12
Read 1 bytes: c0010a04000000000000000000c0
esptool: c0010a04004c40feff00000000c0
command op=0x0d data len=8
>>>>> Write 1 bytes: c0000d080000000000feff000000000000c0
esptool:c0000d0800000000000000000000000000c0
>>>>> Read 1 bytes: c0010d04000000000000000000c0
esptool: c0010d04004c40feff00000000c0
Connected to target
Connected to ESP32-C6
bootloader
size: 21248
Erasing flash (this may take a while)...
esp_loader_flash_start
block_size 1024
detect_flash_size
spi_flash_command 159 0 24
v Write 1 bytes: c0000a04000000000018300060c0
Read 1 bytes: c0010a04000000008000000000c0
v Write 1 bytes: c0000a04000000000020300060c0
Read 1 bytes: c0010a04000000007000000000c0
v Write 1 bytes: c000091000000000002830006017000000
ffffffff00000000c0
Read 1 bytes: c0010904000000007000000000c0
v Write 1 bytes: c000091000000000001830006000000090
ffffffff00000000c0
Read 1 bytes: c0010904000000007000000000c0
v Write 1 bytes: c00009100000000000203000609f000070
ffffffff00000000c0
Read 1 bytes: c0010904000000007000000000c0
v Write 1 bytes: c000091000000000005830006000000000
ffffffff00000000c0
Read 1 bytes: c0010904000000007000000000c0
v Write 1 bytes: c000091000000000000030006000000400
ffffffff00000000c0
Read 1 bytes: c0010904000000007000000000c0try 9
v Write 1 bytes: c0000a04000000000000300060c0
Read 1 bytes: c0010a04000000000000000000c0
Write 1 bytes: c0000a04000000000058300060c0
!!! Read 1 bytes: c0010a0400ffffff0000000000c0
Write 1 bytes: c000091000000000001830006000000080
ffffffff00000000c0
!!! Read 1 bytes: c001090400ffffff0000000000c0
Write 1 bytes: c000091000000000002030006000000070
ffffffff00000000c0
Read 1 bytes: c001090400ffffff0000000000c0
size_id 255
DEBUG: Flash size detection failed, falling back to default
Write 1 bytes: c000021400000000000053000015000000
000400000000000000000000c0
Read 0 bytes:
Erasing flash failed with error 2.

View File

@@ -40,7 +40,7 @@ const uint8_t channelList[6] = {11, 15, 20, 25, 26, 27};
struct pendingData pendingDataArr[MAX_PENDING_MACS];
// VERSION GOES HERE!
uint16_t version = 0x0018;
uint16_t version = 0x0019;
#define RAW_PKT_PADDING 2
@@ -64,8 +64,9 @@ uint8_t lastAckMac[8] = {0};
#define CONCURRENT_REQUEST_DELAY 1200UL
uint32_t lastBlockRequest = 0;
uint8_t lastBlockMac[8];
uint8_t lastTagReturn[8];
uint8_t curChannel = 11;
uint8_t curChannel = 25;
uint8_t curPower = 10;
uint8_t curPendingData = 0;
@@ -325,13 +326,15 @@ void processSerial(uint8_t lastchar) {
}
goto SCPfailed;
SCPchannelFound:
curChannel = scp->channel;
curPower = scp->power;
radioSetChannel(scp->channel);
pr("ACK>");
if (curChannel != scp->channel) {
radioSetChannel(scp->channel);
curChannel = scp->channel;
}
curPower = scp->power;
radioSetTxPower(scp->power);
ESP_LOGI(TAG, "Set channel: %d power: %d", curChannel, curPower);
pr("ACK>");
} else {
} else {
SCPfailed:
pr("NOK>");
}
@@ -408,6 +411,30 @@ void espNotifyAPInfo() {
pr("NOP>%02X", curNoUpdate);
}
void espNotifyTagReturnData(uint8_t *src, uint8_t len) {
struct tagReturnData *trd = (struct tagReturnData *)(radiorxbuffer + sizeof(struct MacFrameBcast) + 1); // oh how I'd love to pass this as an argument, but sdcc won't let me
struct espTagReturnData *etrd = (struct espTagReturnData *)radiotxbuffer;
if (memcmp((void *) & trd->dataVer, lastTagReturn, 8) == 0) {
return;
} else {
memcpy(lastTagReturn, &trd->dataVer, 8);
}
memcpy(etrd->src, src, 8);
etrd->len = len;
memcpy(&etrd->returnData, trd, len);
addCRC(etrd, len + 10);
uartTx('T');
uartTx('R');
uartTx('D');
uartTx('>');
for (uint8_t c = 0; c < len + 10; c++) {
uartTx(((uint8_t *)etrd)[c]);
}
}
// process data from tag
void processBlockRequest(const uint8_t *buffer, uint8_t forceBlockDownload) {
struct MacFrameNormal *rxHeader = (struct MacFrameNormal *) buffer;
@@ -555,6 +582,26 @@ void processXferComplete(uint8_t *buffer) {
}
}
void processTagReturnData(uint8_t *buffer, uint8_t len) {
struct MacFrameBcast *rxframe = (struct MacFrameBcast *)buffer;
struct MacFrameNormal *frameHeader = (struct MacFrameNormal *)(radiotxbuffer + 1);
if (!checkCRC((buffer + sizeof(struct MacFrameBcast) + 1), len - (sizeof(struct MacFrameBcast) + 1))) {
return;
}
radiotxbuffer[sizeof(struct MacFrameNormal) + 1] = PKT_TAG_RETURN_DATA_ACK;
radiotxbuffer[0] = sizeof(struct MacFrameNormal) + 1 + RAW_PKT_PADDING;
memcpy(frameHeader->src, mSelfMac, 8);
memcpy(frameHeader->dst, rxframe->src, 8);
radiotxbuffer[1] = 0x41; // fast way to set the appropriate bits
radiotxbuffer[2] = 0xCC; // normal frame
frameHeader->seq = seq++;
frameHeader->pan = rxframe->srcPan;
radioTx(radiotxbuffer);
espNotifyTagReturnData(rxframe->src, len - (sizeof(struct MacFrameBcast) + 1));
}
// send block data to the tag
void sendPart(uint8_t partNo) {
struct MacFrameNormal *frameHeader = (struct MacFrameNormal *) (radiotxbuffer + 1);
@@ -637,25 +684,24 @@ void sendPong(void *buf) {
}
void app_main(void) {
esp_event_loop_create_default();
init_nvs();
init_led();
init_led();
init_second_uart();
esp_event_loop_create_default();
radio_init();
requestedData.blockId = 0xFF;
// clear the array with pending information
memset(pendingDataArr, 0, sizeof(pendingDataArr));
radioSetChannel(curChannel);
radio_init(curChannel);
radioSetTxPower(10);
pr("RES>");
pr("RDY>");
ESP_LOGI(TAG, "C6 ready!");
housekeepingTimer = getMillis();
housekeepingTimer = getMillis();
while (1) {
while ((getMillis() - housekeepingTimer) < ((1000 * HOUSEKEEPING_INTERVAL) - 100)) {
int8_t ret = commsRxUnencrypted(radiorxbuffer);
@@ -695,8 +741,11 @@ void app_main(void) {
processAvailDataReq(radiorxbuffer);
}
break;
default:
ESP_LOGI(TAG, "t=%02X" , getPacketType(radiorxbuffer));
case PKT_TAG_RETURN_DATA:
processTagReturnData(radiorxbuffer, ret);
break;
default:
ESP_LOGI(TAG, "t=%02X" , getPacketType(radiorxbuffer));
break;
}
} else if (blockStartTimer == 0) {
@@ -714,7 +763,8 @@ void app_main(void) {
}
}
for (uint8_t cCount = 0; cCount < MAX_PENDING_MACS; cCount++) {
memset(&lastTagReturn, 0, 8);
for (uint8_t cCount = 0; cCount < MAX_PENDING_MACS; cCount++) {
if (pendingDataArr[cCount].attemptsLeft == 1) {
if (pendingDataArr[cCount].availdatainfo.dataType != DATATYPE_NOUPDATE) {
espNotifyTimeOut(pendingDataArr[cCount].targetMac);

View File

@@ -58,6 +58,8 @@ struct MacFrameBcast {
uint8_t src[8];
} __attribute__((packed, aligned(1)));
#define PKT_TAG_RETURN_DATA 0xE1
#define PKT_TAG_RETURN_DATA_ACK 0xE2
#define PKT_AVAIL_DATA_SHORTREQ 0xE3
#define PKT_AVAIL_DATA_REQ 0xE5
#define PKT_AVAIL_DATA_INFO 0xE6
@@ -125,9 +127,14 @@ struct blockData {
uint8_t data[];
} __attribute__((packed, aligned(1)));
struct burstMacData {
uint16_t offset;
uint8_t targetMac[8];
#define TAG_RETURN_DATA_SIZE 90
struct tagReturnData {
uint8_t checksum;
uint8_t partId;
uint64_t dataVer;
uint8_t dataType;
uint8_t data[TAG_RETURN_DATA_SIZE];
} __attribute__((packed, aligned(1)));
#define BLOCK_PART_DATA_SIZE 99
@@ -173,4 +180,11 @@ struct espSetChannelPower {
uint8_t power;
} __attribute__((packed, aligned(1)));
struct espTagReturnData {
uint8_t checksum;
uint8_t src[8];
uint8_t len;
struct tagReturnData returnData;
} __attribute__((packed, aligned(1)));
#endif

View File

@@ -47,19 +47,44 @@ void esp_ieee802154_transmit_done(const uint8_t *frame, const uint8_t *ack, esp_
ESP_EARLY_LOGI(TAG, "TX %d", frame[0]);
}
void radio_init() {
packet_buffer = xQueueCreate(32, 130);
esp_ieee802154_enable();
radioSetChannel(11);
esp_ieee802154_set_panid(PROTO_PAN_ID);
esp_ieee802154_set_promiscuous(false); // Filter for our mac and PAN
void radio_init(uint8_t ch) {
if (packet_buffer == NULL) packet_buffer = xQueueCreate(32, 130);
// this will trigger a "IEEE802154 MAC sleep init failed" when called a second time, but it works
esp_ieee802154_enable();
esp_ieee802154_set_channel(ch);
// esp_ieee802154_set_txpower(int8_t power);
esp_ieee802154_set_panid(PROTO_PAN_ID);
esp_ieee802154_set_promiscuous(false);
esp_ieee802154_set_coordinator(false);
esp_ieee802154_set_pending_mode(ESP_IEEE802154_AUTO_PENDING_ZIGBEE);
esp_read_mac(mSelfMac, ESP_MAC_IEEE802154);
esp_ieee802154_set_extended_address(mSelfMac);
esp_ieee802154_set_short_address(0xFFFE);
// esp_ieee802154_set_extended_address needs the MAC in reversed byte order
esp_read_mac(mSelfMac, ESP_MAC_IEEE802154);
uint8_t eui64_rev[8] = {0};
for (int i = 0; i < 8; i++) {
eui64_rev[7 - i] = mSelfMac[i];
}
esp_ieee802154_set_extended_address(eui64_rev);
esp_ieee802154_get_extended_address(mSelfMac);
esp_ieee802154_set_short_address(0xFFFE);
esp_ieee802154_set_rx_when_idle(true);
esp_ieee802154_receive();
led_flash(1);
vTaskDelay(100 / portTICK_PERIOD_MS);
led_flash(0);
vTaskDelay(100 / portTICK_PERIOD_MS);
led_flash(1);
vTaskDelay(100 / portTICK_PERIOD_MS);
led_flash(0);
ESP_LOGI(TAG, "Receiver ready, panId=0x%04x, channel=%d, long=%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x, short=%04x",
esp_ieee802154_get_panid(), esp_ieee802154_get_channel(),
mSelfMac[0], mSelfMac[1], mSelfMac[2], mSelfMac[3],
mSelfMac[4], mSelfMac[5], mSelfMac[6], mSelfMac[7],
esp_ieee802154_get_short_address());
}
uint32_t lastZbTx = 0;
@@ -77,7 +102,9 @@ bool radioTx(uint8_t *packet) {
return true;
}
void radioSetChannel(uint8_t ch) { esp_ieee802154_set_channel(ch); }
void radioSetChannel(uint8_t ch) {
radio_init(ch);
}
void radioSetTxPower(uint8_t power) {}

View File

@@ -4,7 +4,7 @@
extern uint8_t mSelfMac[8];
void radio_init();
void radio_init(uint8_t ch);
bool radioTx(uint8_t *packet);
void radioSetChannel(uint8_t ch);
void radioSetTxPower(uint8_t power);

View File

@@ -32,7 +32,8 @@ volatile int curr_buff_pos = 0;
volatile int worked_buff_pos = 0;
volatile uint8_t buff_pos[MAX_BUFF_POS + 5];
#define S3_TX_PIN 3
#define S3_RX_PIN 2
static void uart_event_task(void *pvParameters);
void init_second_uart() {
@@ -46,9 +47,9 @@ void init_second_uart() {
};
ESP_ERROR_CHECK(uart_driver_install(1, BUF_SIZE * 2, BUF_SIZE * 2, 20, &uart0_queue, 0));
ESP_ERROR_CHECK(uart_param_config(1, &uart_config));
ESP_ERROR_CHECK(uart_set_pin(1, 3, 2, UART_PIN_NO_CHANGE, UART_PIN_NO_CHANGE));
ESP_ERROR_CHECK(uart_set_pin(1, S3_TX_PIN, S3_RX_PIN, UART_PIN_NO_CHANGE, UART_PIN_NO_CHANGE));
xTaskCreate(uart_event_task, "uart_event_task", 16384, NULL, 12, NULL);
xTaskCreate(uart_event_task, "uart_event_task", 16384, NULL, 12, NULL);
}
void uart_switch_speed(int baudrate) {
@@ -92,7 +93,7 @@ static void uart_event_task(void *pvParameters) {
}
break;
default:
ESP_LOGI(TAG, "uart event type: %d", event.type);
// ESP_LOGI(TAG, "uart event type: %d", event.type);
break;
}
}

View File

@@ -0,0 +1,5 @@
# ESP-IDF Partition Table
# Name, Type, SubType, Offset, Size, Flags
nvs,data,nvs,0x9000,0x6000,,
factory,app,factory,0x10000,1M,,
littlefs,data,spiffs,,3008K,,
1 # ESP-IDF Partition Table
2 # Name, Type, SubType, Offset, Size, Flags
3 nvs,data,nvs,0x9000,0x6000,,
4 factory,app,factory,0x10000,1M,,
5 littlefs,data,spiffs,,3008K,,

View File

@@ -1,6 +1,6 @@
#
# Automatically generated file. DO NOT EDIT.
# Espressif IoT Development Framework (ESP-IDF) 5.1.0 Project Configuration
# Espressif IoT Development Framework (ESP-IDF) 5.1.1 Project Configuration
#
CONFIG_SOC_ADC_SUPPORTED=y
CONFIG_SOC_DEDICATED_GPIO_SUPPORTED=y
@@ -72,6 +72,9 @@ CONFIG_SOC_ADC_SAMPLE_FREQ_THRES_HIGH=83333
CONFIG_SOC_ADC_SAMPLE_FREQ_THRES_LOW=611
CONFIG_SOC_ADC_RTC_MIN_BITWIDTH=12
CONFIG_SOC_ADC_RTC_MAX_BITWIDTH=12
CONFIG_SOC_ADC_CALIBRATION_V1_SUPPORTED=y
CONFIG_SOC_ADC_SELF_HW_CALI_SUPPORTED=y
CONFIG_SOC_ADC_CALIB_CHAN_COMPENS_SUPPORTED=y
CONFIG_SOC_ADC_TEMPERATURE_SHARE_INTR=y
CONFIG_SOC_BROWNOUT_RESET_SUPPORTED=y
CONFIG_SOC_SHARED_IDCACHE_SUPPORTED=y
@@ -115,6 +118,7 @@ CONFIG_SOC_DEDIC_GPIO_IN_CHANNELS_NUM=8
CONFIG_SOC_DEDIC_PERIPH_ALWAYS_ENABLE=y
CONFIG_SOC_I2C_NUM=1
CONFIG_SOC_I2C_FIFO_LEN=32
CONFIG_SOC_I2C_CMD_REG_NUM=8
CONFIG_SOC_I2C_SUPPORT_SLAVE=y
CONFIG_SOC_I2C_SUPPORT_HW_CLR_BUS=y
CONFIG_SOC_I2C_SUPPORT_XTAL=y
@@ -255,6 +259,7 @@ CONFIG_SOC_SUPPORT_SECURE_BOOT_REVOKE_KEY=y
CONFIG_SOC_FLASH_ENCRYPTED_XTS_AES_BLOCK_MAX=32
CONFIG_SOC_FLASH_ENCRYPTION_XTS_AES=y
CONFIG_SOC_FLASH_ENCRYPTION_XTS_AES_128=y
CONFIG_SOC_CRYPTO_DPA_PROTECTION_SUPPORTED=y
CONFIG_SOC_UART_NUM=2
CONFIG_SOC_UART_FIFO_LEN=128
CONFIG_SOC_UART_BITRATE_MAX=5000000
@@ -264,6 +269,7 @@ CONFIG_SOC_UART_SUPPORT_XTAL_CLK=y
CONFIG_SOC_UART_SUPPORT_WAKEUP_INT=y
CONFIG_SOC_UART_SUPPORT_FSM_TX_WAIT_SEND=y
CONFIG_SOC_COEX_HW_PTI=y
CONFIG_SOC_EXTERNAL_COEX_ADVANCE=y
CONFIG_SOC_PHY_DIG_REGS_MEM_SIZE=21
CONFIG_SOC_WIFI_LIGHT_SLEEP_CLK_WIDTH=12
CONFIG_SOC_PM_SUPPORT_WIFI_WAKEUP=y
@@ -277,12 +283,14 @@ CONFIG_SOC_PM_SUPPORT_RC32K_PD=y
CONFIG_SOC_PM_SUPPORT_RC_FAST_PD=y
CONFIG_SOC_PM_SUPPORT_VDDSDIO_PD=y
CONFIG_SOC_PM_SUPPORT_TOP_PD=y
CONFIG_SOC_PM_SUPPORT_HP_AON_PD=y
CONFIG_SOC_PM_SUPPORT_MAC_BB_PD=y
CONFIG_SOC_PM_SUPPORT_RTC_PERIPH_PD=y
CONFIG_SOC_PM_SUPPORT_PMU_MODEM_STATE=y
CONFIG_SOC_PM_SUPPORT_DEEPSLEEP_CHECK_STUB_ONLY=y
CONFIG_SOC_PM_CPU_RETENTION_BY_SW=y
CONFIG_SOC_PM_MODEM_RETENTION_BY_REGDMA=y
CONFIG_SOC_PM_RETENTION_HAS_CLOCK_BUG=y
CONFIG_SOC_PM_PAU_LINK_NUM=4
CONFIG_SOC_CLK_RC_FAST_SUPPORT_CALIBRATION=y
CONFIG_SOC_MODEM_CLOCK_IS_INDEPENDENT=y
@@ -293,7 +301,6 @@ CONFIG_SOC_TEMPERATURE_SENSOR_SUPPORT_FAST_RC=y
CONFIG_SOC_TEMPERATURE_SENSOR_SUPPORT_XTAL=y
CONFIG_SOC_TEMPERATURE_SENSOR_INTR_SUPPORT=y
CONFIG_SOC_WIFI_HW_TSF=y
CONFIG_SOC_WIFI_FTM_SUPPORT=y
CONFIG_SOC_WIFI_GCMP_SUPPORT=y
CONFIG_SOC_WIFI_WAPI_SUPPORT=y
CONFIG_SOC_WIFI_CSI_SUPPORT=y
@@ -306,6 +313,8 @@ CONFIG_SOC_BLE_50_SUPPORTED=y
CONFIG_SOC_BLE_DEVICE_PRIVACY_SUPPORTED=y
CONFIG_SOC_BLE_POWER_CONTROL_SUPPORTED=y
CONFIG_SOC_BLUFI_SUPPORTED=y
CONFIG_SOC_BLE_MULTI_CONN_OPTIMIZATION=y
CONFIG_SOC_BLE_USE_WIFI_PWR_CLK_WORKAROUND=y
CONFIG_IDF_CMAKE=y
CONFIG_IDF_TARGET_ARCH_RISCV=y
CONFIG_IDF_TARGET_ARCH="riscv"
@@ -422,14 +431,14 @@ CONFIG_ESPTOOLPY_FLASHFREQ_80M=y
CONFIG_ESPTOOLPY_FLASHFREQ_80M_DEFAULT=y
CONFIG_ESPTOOLPY_FLASHFREQ="80m"
# CONFIG_ESPTOOLPY_FLASHSIZE_1MB is not set
CONFIG_ESPTOOLPY_FLASHSIZE_2MB=y
# CONFIG_ESPTOOLPY_FLASHSIZE_4MB is not set
# CONFIG_ESPTOOLPY_FLASHSIZE_2MB is not set
CONFIG_ESPTOOLPY_FLASHSIZE_4MB=y
# CONFIG_ESPTOOLPY_FLASHSIZE_8MB is not set
# CONFIG_ESPTOOLPY_FLASHSIZE_16MB is not set
# CONFIG_ESPTOOLPY_FLASHSIZE_32MB is not set
# CONFIG_ESPTOOLPY_FLASHSIZE_64MB is not set
# CONFIG_ESPTOOLPY_FLASHSIZE_128MB is not set
CONFIG_ESPTOOLPY_FLASHSIZE="2MB"
CONFIG_ESPTOOLPY_FLASHSIZE="4MB"
# CONFIG_ESPTOOLPY_HEADER_FLASHSIZE_UPDATE is not set
CONFIG_ESPTOOLPY_BEFORE_RESET=y
# CONFIG_ESPTOOLPY_BEFORE_NORESET is not set
@@ -443,12 +452,12 @@ CONFIG_ESPTOOLPY_MONITOR_BAUD=115200
#
# Partition Table
#
CONFIG_PARTITION_TABLE_SINGLE_APP=y
# CONFIG_PARTITION_TABLE_SINGLE_APP is not set
# CONFIG_PARTITION_TABLE_SINGLE_APP_LARGE is not set
# CONFIG_PARTITION_TABLE_TWO_OTA is not set
# CONFIG_PARTITION_TABLE_CUSTOM is not set
CONFIG_PARTITION_TABLE_CUSTOM=y
CONFIG_PARTITION_TABLE_CUSTOM_FILENAME="partitions.csv"
CONFIG_PARTITION_TABLE_FILENAME="partitions_singleapp.csv"
CONFIG_PARTITION_TABLE_FILENAME="partitions.csv"
CONFIG_PARTITION_TABLE_OFFSET=0x8000
CONFIG_PARTITION_TABLE_MD5=y
# end of Partition Table
@@ -750,9 +759,9 @@ CONFIG_ESP32C6_UNIVERSAL_MAC_ADDRESSES=4
# Sleep Config
#
# CONFIG_ESP_SLEEP_POWER_DOWN_FLASH is not set
CONFIG_ESP_SLEEP_GPIO_RESET_WORKAROUND=y
CONFIG_ESP_SLEEP_FLASH_LEAKAGE_WORKAROUND=y
# CONFIG_ESP_SLEEP_MSPI_NEED_ALL_IO_PU is not set
CONFIG_ESP_SLEEP_GPIO_RESET_WORKAROUND=y
# end of Sleep Config
#
@@ -790,6 +799,16 @@ CONFIG_PERIPH_CTRL_FUNC_IN_IRAM=y
CONFIG_XTAL_FREQ_40=y
CONFIG_XTAL_FREQ=40
# end of Main XTAL Config
#
# Crypto DPA Protection
#
CONFIG_ESP_CRYPTO_DPA_PROTECTION_AT_STARTUP=y
CONFIG_ESP_CRYPTO_DPA_PROTECTION_LEVEL_LOW=y
# CONFIG_ESP_CRYPTO_DPA_PROTECTION_LEVEL_MEDIUM is not set
# CONFIG_ESP_CRYPTO_DPA_PROTECTION_LEVEL_HIGH is not set
CONFIG_ESP_CRYPTO_DPA_PROTECTION_LEVEL=1
# end of Crypto DPA Protection
# end of Hardware Settings
#
@@ -815,6 +834,7 @@ CONFIG_ESP_NETIF_IP_LOST_TIMER_INTERVAL=120
CONFIG_ESP_NETIF_TCPIP_LWIP=y
# CONFIG_ESP_NETIF_LOOPBACK is not set
CONFIG_ESP_NETIF_USES_TCPIP_WITH_BSD_API=y
# CONFIG_ESP_NETIF_RECEIVE_REPORT_ERRORS is not set
# CONFIG_ESP_NETIF_L2_TAP is not set
# CONFIG_ESP_NETIF_BRIDGE_EN is not set
# end of ESP NETIF Adapter
@@ -974,7 +994,6 @@ CONFIG_ESP_WIFI_ENABLE_SAE_PK=y
CONFIG_ESP_WIFI_SOFTAP_SAE_SUPPORT=y
CONFIG_ESP_WIFI_ENABLE_WPA3_OWE_STA=y
# CONFIG_ESP_WIFI_SLP_IRAM_OPT is not set
# CONFIG_ESP_WIFI_FTM_ENABLE is not set
CONFIG_ESP_WIFI_STA_DISCONNECTED_PM_ENABLE=y
# CONFIG_ESP_WIFI_GCMP_SUPPORT is not set
# CONFIG_ESP_WIFI_GMAC_SUPPORT is not set
@@ -1148,6 +1167,7 @@ CONFIG_IEEE802154_CCA_THRESHOLD=-60
CONFIG_IEEE802154_PENDING_TABLE_SIZE=20
# CONFIG_IEEE802154_MULTI_PAN_ENABLE is not set
# CONFIG_IEEE802154_TIMING_OPTIMIZATION is not set
# CONFIG_IEEE802154_DEBUG is not set
# end of IEEE 802.15.4
#
@@ -1309,6 +1329,9 @@ CONFIG_LWIP_HOOK_IP6_ROUTE_NONE=y
CONFIG_LWIP_HOOK_ND6_GET_GW_NONE=y
# CONFIG_LWIP_HOOK_ND6_GET_GW_DEFAULT is not set
# CONFIG_LWIP_HOOK_ND6_GET_GW_CUSTOM is not set
CONFIG_LWIP_HOOK_IP6_SELECT_SRC_ADDR_NONE=y
# CONFIG_LWIP_HOOK_IP6_SELECT_SRC_ADDR_DEFAULT is not set
# CONFIG_LWIP_HOOK_IP6_SELECT_SRC_ADDR_CUSTOM is not set
CONFIG_LWIP_HOOK_NETCONN_EXT_RESOLVE_NONE=y
# CONFIG_LWIP_HOOK_NETCONN_EXT_RESOLVE_DEFAULT is not set
# CONFIG_LWIP_HOOK_NETCONN_EXT_RESOLVE_CUSTOM is not set
@@ -1491,6 +1514,17 @@ CONFIG_NEWLIB_TIME_SYSCALL_USE_RTC_HRT=y
# OpenThread
#
# CONFIG_OPENTHREAD_ENABLED is not set
#
# Thread Operational Dataset
#
CONFIG_OPENTHREAD_NETWORK_NAME="OpenThread-ESP"
CONFIG_OPENTHREAD_NETWORK_CHANNEL=15
CONFIG_OPENTHREAD_NETWORK_PANID=0x1234
CONFIG_OPENTHREAD_NETWORK_EXTPANID="dead00beef00cafe"
CONFIG_OPENTHREAD_NETWORK_MASTERKEY="00112233445566778899aabbccddeeff"
CONFIG_OPENTHREAD_NETWORK_PSKC="104810e2315100afd6bc9215a6bfac53"
# end of Thread Operational Dataset
# end of OpenThread
#
@@ -1514,9 +1548,9 @@ CONFIG_PTHREAD_TASK_NAME_DEFAULT="pthread"
#
# MMU Config
#
CONFIG_MMU_PAGE_SIZE_32KB=y
CONFIG_MMU_PAGE_MODE="32KB"
CONFIG_MMU_PAGE_SIZE=0x8000
CONFIG_MMU_PAGE_SIZE_64KB=y
CONFIG_MMU_PAGE_MODE="64KB"
CONFIG_MMU_PAGE_SIZE=0x10000
# end of MMU Config
#
@@ -1640,6 +1674,7 @@ CONFIG_VFS_SUPPORT_DIR=y
CONFIG_VFS_SUPPORT_SELECT=y
CONFIG_VFS_SUPPRESS_SELECT_DEBUG_OUTPUT=y
CONFIG_VFS_SUPPORT_TERMIOS=y
CONFIG_VFS_MAX_COUNT=8
#
# Host File System I/O (Semihosting)

View File

@@ -11,7 +11,8 @@
"red": [255, 0, 0],
"gray": [150, 150, 150]
},
"capabilities": ["button", "customlut"],
"shortlut": 2,
"options": ["button", "customlut"],
"template": {
"1": {
"weekday": [ 76, 10, "fonts/calibrib30" ],

View File

@@ -11,7 +11,8 @@
"red": [255, 0, 0],
"gray": [150, 150, 150]
},
"capabilities": ["button", "customlut"],
"shortlut": 2,
"options": ["button", "customlut"],
"template": {
"1": {
"weekday": [148, 10, "fonts/calibrib60"],

View File

@@ -11,7 +11,8 @@
"red": [255, 0, 0],
"gray": [150, 150, 150]
},
"capabilities": ["button", "customlut"],
"shortlut": 1,
"options": ["button"],
"template": {
"1": {
"weekday": [ 200, 25, "fonts/calibrib60" ],

View File

@@ -11,7 +11,8 @@
"red": [255, 0, 0],
"gray": [150, 150, 150]
},
"capabilities": ["button", "customlut"],
"shortlut": 1,
"options": [],
"template": {
"1": {
"weekday": [ 200, 25, "fonts/calibrib60" ],

View File

@@ -11,6 +11,7 @@
"red": [255, 0, 0],
"gray": [150, 150, 150]
},
"capabilities": ["button", "customlut"],
"shortlut": 0,
"options": ["button"],
"usetemplate": 1
}

View File

@@ -11,7 +11,8 @@
"red": [255, 0, 0],
"gray": [150, 150, 150]
},
"capabilities": ["button", "customlut"],
"shortlut": 0,
"options": ["button", "led"],
"template": {
"1": {
"weekday": [148, 10, "fonts/calibrib60"],

View File

@@ -11,7 +11,8 @@
"red": [255, 0, 0],
"gray": [150, 150, 150]
},
"capabilities": ["button", "customlut"],
"shortlut": 0,
"options": ["button", "led"],
"template": {
"1": {
"weekday": [148, 10, "fonts/calibrib60"],

View File

@@ -11,7 +11,8 @@
"red": [ 255, 0, 0 ],
"gray": [ 150, 150, 150 ]
},
"capabilities": [ ],
"shortlut": 0,
"options": [],
"contentids": [ 0, 1, 2, 3, 4, 8, 16, 9, 7, 19, 10, 11, 21 ],
"usetemplate": 1,
"template": {

View File

@@ -6,7 +6,8 @@
"bpp": 1,
"colors": 0,
"colortable": {},
"capabilities": [],
"shortlut": 0,
"options": [],
"template": {
}
}

Binary file not shown.

Binary file not shown.

View File

@@ -0,0 +1,59 @@
/* Copyright 2020-2023 Espressif Systems (Shanghai) CO LTD
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include "esp_loader_io.h"
#include "freertos/FreeRTOS.h"
#include "freertos/queue.h"
#ifdef __cplusplus
extern "C" {
#endif
typedef struct
{
uint32_t baud_rate; /*!< Initial baud rate, can be changed later */
uint32_t uart_port; /*!< UART port */
uint32_t uart_rx_pin; /*!< This pin will be configured as UART Rx pin */
uint32_t uart_tx_pin; /*!< This pin will be configured as UART Tx pin */
uint32_t reset_trigger_pin; /*!< This pin will be used to reset target chip */
uint32_t gpio0_trigger_pin; /*!< This pin will be used to toggle set IO0 of target chip */
uint32_t rx_buffer_size; /*!< Set to zero for default RX buffer size */
uint32_t tx_buffer_size; /*!< Set to zero for default TX buffer size */
uint32_t queue_size; /*!< Set to zero for default UART queue size */
QueueHandle_t *uart_queue; /*!< Set to NULL, if UART queue handle is not
necessary. Otherwise, it will be assigned here */
} loader_esp32_config_t;
/**
* @brief Initializes serial interface.
*
* @param baud_rate[in] Communication speed.
*
* @return
* - ESP_LOADER_SUCCESS Success
* - ESP_LOADER_ERROR_FAIL Initialization failure
*/
esp_loader_error_t loader_port_esp32_init(const loader_esp32_config_t *config);
/**
* @brief Deinitialize serial interface.
*/
void loader_port_esp32_deinit(void);
#ifdef __cplusplus
}
#endif

View File

@@ -0,0 +1,4 @@
#include <Arduino.h>
#include <LittleFS.h>
bool doC6flash();

View File

@@ -5,6 +5,10 @@
extern TFT_eSPI tft;
#define SHORTLUT_DISABLED 0
#define SHORTLUT_ONLY_BLACK 1
#define SHORTLUT_ALLOWED 2
struct imgParam {
bool hasRed;
uint8_t dataType;
@@ -21,6 +25,9 @@ struct imgParam {
char segments[12];
uint16_t symbols;
bool invert;
uint8_t lut;
uint8_t shortlut;
};
void spr2buffer(TFT_eSprite &spr, String &fileout, imgParam &imageParams);

View File

@@ -7,7 +7,7 @@ extern void processBlockRequest(struct espBlockRequest* br);
extern void prepareCancelPending(const uint8_t dst[8]);
extern void prepareIdleReq(const uint8_t* dst, uint16_t nextCheckin);
extern void prepareDataAvail(uint8_t* data, uint16_t len, uint8_t dataType, const uint8_t* dst);
extern bool prepareDataAvail(String& filename, uint8_t dataType, const uint8_t* dst, uint16_t nextCheckin, bool resend = false);
extern bool prepareDataAvail(String& filename, uint8_t dataType, uint8_t dataTypeArgument, const uint8_t* dst, uint16_t nextCheckin, bool resend = false);
extern void prepareExternalDataAvail(struct pendingData* pending, IPAddress remoteIP);
extern void processXferComplete(struct espXferComplete* xfc, bool local);
extern void processXferTimeout(struct espXferComplete* xfc, bool local);

View File

@@ -9,4 +9,5 @@ void handleUpdateOTA(AsyncWebServerRequest* request);
void firmwareUpdateTask(void* parameter);
void updateFirmware(const char* url, const char* expectedMd5, const size_t size);
void handleRollback(AsyncWebServerRequest* request);
void handleUpdateC6(AsyncWebServerRequest* request);
void handleUpdateActions(AsyncWebServerRequest* request);

View File

@@ -29,7 +29,8 @@ void APTask(void* parameter);
bool sendCancelPending(struct pendingData* pending);
bool sendDataAvail(struct pendingData* pending);
bool sendPing();
void APEnterEarlyReset();
bool sendChannelPower(struct espSetChannelPower* scp);
bool sendChannelPower(struct espSetChannelPower* scp);
void rxSerialTask2(void* parameter);
void APTagReset();
bool bringAPOnline();

View File

@@ -77,6 +77,7 @@ struct HwType {
uint16_t height;
uint8_t rotatebuffer;
uint8_t bpp;
uint8_t shortlut;
};
struct varStruct {
@@ -105,5 +106,6 @@ extern void initAPconfig();
extern void saveAPconfig();
extern HwType getHwType(const uint8_t id);
extern bool setVarDB(const std::string& key, const String& value);
extern void cleanupCurrent();
#pragma pack(pop)

View File

@@ -0,0 +1,202 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

View File

@@ -0,0 +1,155 @@
# esp-serial-flasher
`esp-serial-flasher` is a portable C library for flashing or loading apps to RAM of Espressif SoCs from other host microcontrollers.
## Using the library
Espressif SoCs are normally programmed via serial interface (UART). The port layer for the given host microcontroller has to be implemented if not available. Details can be found in section below.
Supported **host** microcontrollers:
- STM32
- Raspberry Pi SBC
- ESP32
- Any MCU running Zephyr OS
Supported **target** microcontrollers:
- ESP32
- ESP8266
- ESP32-S2
- ESP32-S3
- ESP32-C3
- ESP32-C2
- ESP32-H2
- ESP32-C6
Supported hardware interfaces:
- UART
- SPI (only for RAM download, experimental)
For example usage check the `examples` directory.
## Supporting a new host target
In order to support a new target, following functions have to be implemented by user:
- `loader_port_read()`
- `loader_port_write()`
- `loader_port_enter_bootloader()`
- `loader_port_delay_ms()`
- `loader_port_start_timer()`
- `loader_port_remaining_time()`
For the SPI interface ports
- `loader_port_spi_set_cs()`
needs to be implemented as well.
The following functions are part of the [io.h](include/io.h) header for convenience, however, the user does not have to strictly follow function signatures, as there are not called directly from library.
- `loader_port_change_transmission_rate()`
- `loader_port_reset_target()`
- `loader_port_debug_print()`
Prototypes of all functions mentioned above can be found in [io.h](include/io.h).
## Configuration
These are the configuration toggles available to the user:
* `SERIAL_FLASHER_INTERFACE_UART/SERIAL_FLASHER_INTERFACE_SPI`
This defines the hardware interface to use. SPI interface only supports RAM download mode and is in experimental stage and can undergo changes.
Default: SERIAL_FLASHER_INTERFACE_UART
* `MD5_ENABLED`
If enabled, `esp-serial-flasher` is capable of verifying flash integrity after writing to flash.
Default: Enabled
> Warning: As ROM bootloader of the ESP8266 does not support MD5_CHECK, this option has to be disabled!
* `SERIAL_FLASHER_RESET_HOLD_TIME_MS`
This is the time for which the reset pin is asserted when doing a hard reset in milliseconds.
Default: 100
* `SERIAL_FLASHER_BOOT_HOLD_TIME_MS`
This is the time for which the boot pin is asserted when doing a hard reset in milliseconds.
Default: 50
Configuration can be passed to `cmake` via command line:
```
cmake -DMD5_ENABLED=1 .. && cmake --build .
```
### STM32 support
The STM32 port makes use of STM32 HAL libraries, and these do not come with CMake support. In order to compile the project, `stm32-cmake` (a `CMake` support package) has to be pulled as submodule.
```
git clone --recursive https://github.com/espressif/esp-serial-flasher.git
```
If you have cloned this repository without the `--recursive` flag, you can initialize the submodule using the following command:
```
git submodule update --init
```
In addition to configuration parameters mentioned above, following definitions has to be set:
- TOOLCHAIN_PREFIX: path to arm toolchain (i.e /home/user/gcc-arm-none-eabi-9-2019-q4-major)
- STM32Cube_DIR: path to STM32 Cube libraries (i.e /home/user/STM32Cube/Repository/STM32Cube_FW_F4_V1.25.0)
- STM32_CHIP: name of STM32 for which project should be compiled (i.e STM32F407VG)
- PORT: STM32
This can be achieved by passing definitions to the command line, such as:
```
cmake -DTOOLCHAIN_PREFIX="/path_to_toolchain" -DSTM32Cube_DIR="path_to_stm32Cube" -DSTM32_CHIP="STM32F407VG" -DPORT="STM32" .. && cmake --build .
```
Alternatively, those variables can be set in the top level `cmake` directory:
```
set(TOOLCHAIN_PREFIX path_to_toolchain)
set(STM32Cube_DIR path_to_stm32_HAL)
set(STM32_CHIP STM32F407VG)
set(PORT STM32)
```
### Zephyr support
The Zephyr port is ready to be integrated into Zephyr apps as a Zephyr module. In the manifest file (west.yml), add:
```
- name: esp-flasher
url: https://github.com/espressif/esp-serial-flasher
revision: master
path: modules/lib/esp_flasher
```
And add
```
CONFIG_ESP_SERIAL_FLASHER=y
CONFIG_CONSOLE_GETCHAR=y
CONFIG_SERIAL_FLASHER_MD5_ENABLED=y
```
to the project configuration `prj.conf`.
For the C/C++ source code, the example code provided in `examples/zephyr_example` can be used as a starting point.
## Licence
Code is distributed under Apache 2.0 license.
## Known limitations
Size of new binary image has to be known before flashing.

View File

@@ -0,0 +1,61 @@
#include <Arduino.h>
/* Copyright 2020-2023 Espressif Systems (Shanghai) CO LTD
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include "esp_loader_io.h"
#include "freertos/FreeRTOS.h"
#include "freertos/queue.h"
#ifdef __cplusplus
extern "C" {
#endif
typedef struct
{
uint32_t baud_rate; /*!< Initial baud rate, can be changed later */
uint32_t uart_port; /*!< UART port */
uint32_t uart_rx_pin; /*!< This pin will be configured as UART Rx pin */
uint32_t uart_tx_pin; /*!< This pin will be configured as UART Tx pin */
uint32_t reset_trigger_pin; /*!< This pin will be used to reset target chip */
uint32_t gpio0_trigger_pin; /*!< This pin will be used to toggle set IO0 of target chip */
uint32_t rx_buffer_size; /*!< Set to zero for default RX buffer size */
uint32_t tx_buffer_size; /*!< Set to zero for default TX buffer size */
uint32_t queue_size; /*!< Set to zero for default UART queue size */
QueueHandle_t *uart_queue; /*!< Set to NULL, if UART queue handle is not
necessary. Otherwise, it will be assigned here */
} loader_esp32_config_t;
/**
* @brief Initializes serial interface.
*
* @param baud_rate[in] Communication speed.
*
* @return
* - ESP_LOADER_SUCCESS Success
* - ESP_LOADER_ERROR_FAIL Initialization failure
*/
esp_loader_error_t loader_port_esp32_init(const loader_esp32_config_t *config);
/**
* @brief Deinitialize serial interface.
*/
void loader_port_esp32_deinit(void);
#ifdef __cplusplus
}
#endif

View File

@@ -0,0 +1,300 @@
#include <Arduino.h>
/* Copyright 2020-2023 Espressif Systems (Shanghai) CO LTD
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <stdint.h>
#include <stdbool.h>
#ifdef __cplusplus
extern "C" {
#endif
/* Used for backwards compatibility with the previous API */
#define esp_loader_change_baudrate esp_loader_change_transmission_rate
/**
* Macro which can be used to check the error code,
* and return in case the code is not ESP_LOADER_SUCCESS.
*/
#define RETURN_ON_ERROR(x) do { \
esp_loader_error_t _err_ = (x); \
if (_err_ != ESP_LOADER_SUCCESS) { \
return _err_; \
} \
} while(0)
/**
* @brief Error codes
*/
typedef enum {
ESP_LOADER_SUCCESS, /*!< Success */
ESP_LOADER_ERROR_FAIL, /*!< Unspecified error */
ESP_LOADER_ERROR_TIMEOUT, /*!< Timeout elapsed */
ESP_LOADER_ERROR_IMAGE_SIZE, /*!< Image size to flash is larger than flash size */
ESP_LOADER_ERROR_INVALID_MD5, /*!< Computed and received MD5 does not match */
ESP_LOADER_ERROR_INVALID_PARAM, /*!< Invalid parameter passed to function */
ESP_LOADER_ERROR_INVALID_TARGET, /*!< Connected target is invalid */
ESP_LOADER_ERROR_UNSUPPORTED_CHIP, /*!< Attached chip is not supported */
ESP_LOADER_ERROR_UNSUPPORTED_FUNC, /*!< Function is not supported on attached target */
ESP_LOADER_ERROR_INVALID_RESPONSE /*!< Internal error */
} esp_loader_error_t;
/**
* @brief Supported targets
*/
typedef enum {
ESP8266_CHIP = 0,
ESP32_CHIP = 1,
ESP32S2_CHIP = 2,
ESP32C3_CHIP = 3,
ESP32S3_CHIP = 4,
ESP32C2_CHIP = 5,
ESP32H4_CHIP = 6,
ESP32H2_CHIP = 7,
ESP32C6_CHIP = 8,
ESP_MAX_CHIP = 9,
ESP_UNKNOWN_CHIP = 9
} target_chip_t;
/**
* @brief Application binary header
*/
typedef struct {
uint8_t magic;
uint8_t segments;
uint8_t flash_mode;
uint8_t flash_size_freq;
uint32_t entrypoint;
} esp_loader_bin_header_t;
/**
* @brief Segment binary header
*/
typedef struct {
uint32_t addr;
uint32_t size;
uint8_t *data;
} esp_loader_bin_segment_t;
/**
* @brief Connection arguments
*/
typedef struct {
uint32_t sync_timeout; /*!< Maximum time to wait for response from serial interface. */
int32_t trials; /*!< Number of trials to connect to target. If greater than 1,
100 millisecond delay is inserted after each try. */
} esp_loader_connect_args_t;
#define ESP_LOADER_CONNECT_DEFAULT() { \
.sync_timeout = 100, \
.trials = 10, \
}
/**
* @brief Connects to the target
*
* @param connect_args[in] Timing parameters to be used for connecting to target.
*
* @return
* - ESP_LOADER_SUCCESS Success
* - ESP_LOADER_ERROR_TIMEOUT Timeout
* - ESP_LOADER_ERROR_INVALID_RESPONSE Internal error
*/
esp_loader_error_t esp_loader_connect(esp_loader_connect_args_t *connect_args);
/**
* @brief Returns attached target chip.
*
* @warning This function can only be called after connection with target
* has been successfully established by calling esp_loader_connect().
*
* @return One of target_chip_t
*/
target_chip_t esp_loader_get_target(void);
#ifdef SERIAL_FLASHER_INTERFACE_UART
/**
* @brief Initiates flash operation
*
* @param offset[in] Address from which flash operation will be performed.
* @param image_size[in] Size of the whole binary to be loaded into flash.
* @param block_size[in] Size of buffer used in subsequent calls to esp_loader_flash_write.
*
* @note image_size is size of the whole image, whereas, block_size is chunk of data sent
* to the target, each time esp_loader_flash_write function is called.
*
* @return
* - ESP_LOADER_SUCCESS Success
* - ESP_LOADER_ERROR_TIMEOUT Timeout
* - ESP_LOADER_ERROR_INVALID_RESPONSE Internal error
*/
esp_loader_error_t esp_loader_flash_start(uint32_t offset, uint32_t image_size, uint32_t block_size);
/**
* @brief Writes supplied data to target's flash memory.
*
* @param payload[in] Data to be flashed into target's memory.
* @param size[in] Size of payload in bytes.
*
* @note size must not be greater that block_size supplied to previously called
* esp_loader_flash_start function. If size is less than block_size,
* remaining bytes of payload buffer will be padded with 0xff.
* Therefore, size of payload buffer has to be equal or greater than block_size.
*
* @return
* - ESP_LOADER_SUCCESS Success
* - ESP_LOADER_ERROR_TIMEOUT Timeout
* - ESP_LOADER_ERROR_INVALID_RESPONSE Internal error
*/
esp_loader_error_t esp_loader_flash_write(void *payload, uint32_t size);
/**
* @brief Ends flash operation.
*
* @param reboot[in] reboot the target if true.
*
* @return
* - ESP_LOADER_SUCCESS Success
* - ESP_LOADER_ERROR_TIMEOUT Timeout
* - ESP_LOADER_ERROR_INVALID_RESPONSE Internal error
*/
esp_loader_error_t esp_loader_flash_finish(bool reboot);
#endif /* SERIAL_FLASHER_INTERFACE_UART */
/**
* @brief Initiates mem operation, initiates loading for program into target RAM
*
* @param offset[in] Address from which mem operation will be performed.
* @param size[in] Size of the whole binary to be loaded into mem.
* @param block_size[in] Size of buffer used in subsequent calls to esp_loader_mem_write.
*
* @note image_size is size of the whole image, whereas, block_size is chunk of data sent
* to the target, each time esp_mem_flash_write function is called.
*
* @return
* - ESP_LOADER_SUCCESS Success
* - ESP_LOADER_ERROR_TIMEOUT Timeout
* - ESP_LOADER_ERROR_INVALID_RESPONSE Internal error
*/
esp_loader_error_t esp_loader_mem_start(uint32_t offset, uint32_t size, uint32_t block_size);
/**
* @brief Writes supplied data to target's mem memory.
*
* @param payload[in] Data to be loaded into target's memory.
* @param size[in] Size of data in bytes.
*
* @note size must not be greater that block_size supplied to previously called
* esp_loader_mem_start function.
* Therefore, size of data buffer has to be equal or greater than block_size.
*
* @return
* - ESP_LOADER_SUCCESS Success
* - ESP_LOADER_ERROR_TIMEOUT Timeout
* - ESP_LOADER_ERROR_INVALID_RESPONSE Internal error
*/
esp_loader_error_t esp_loader_mem_write(const void *payload, uint32_t size);
/**
* @brief Ends mem operation, finish loading for program into target RAM
* and send the entrypoint of ram_loadable app
*
* @param entrypoint[in] entrypoint of ram program.
*
* @return
* - ESP_LOADER_SUCCESS Success
* - ESP_LOADER_ERROR_TIMEOUT Timeout
* - ESP_LOADER_ERROR_INVALID_RESPONSE Internal error
*/
esp_loader_error_t esp_loader_mem_finish(uint32_t entrypoint);
/**
* @brief Writes register.
*
* @param address[in] Address of register.
* @param reg_value[in] New register value.
*
* @return
* - ESP_LOADER_SUCCESS Success
* - ESP_LOADER_ERROR_TIMEOUT Timeout
* - ESP_LOADER_ERROR_INVALID_RESPONSE Internal error
*/
esp_loader_error_t esp_loader_write_register(uint32_t address, uint32_t reg_value);
/**
* @brief Reads register.
*
* @param address[in] Address of register.
* @param reg_value[out] Register value.
*
* @return
* - ESP_LOADER_SUCCESS Success
* - ESP_LOADER_ERROR_TIMEOUT Timeout
* - ESP_LOADER_ERROR_INVALID_RESPONSE Internal error
*/
esp_loader_error_t esp_loader_read_register(uint32_t address, uint32_t *reg_value);
/**
* @brief Change baud rate.
*
* @note Baud rate has to be also adjusted accordingly on host MCU, as
* target's baud rate is changed upon return from this function.
*
* @param transmission_rate[in] new baud rate to be set.
*
* @return
* - ESP_LOADER_SUCCESS Success
* - ESP_LOADER_ERROR_TIMEOUT Timeout
* - ESP_LOADER_ERROR_INVALID_RESPONSE Internal error
* - ESP_LOADER_ERROR_UNSUPPORTED_FUNC Unsupported on the target
*/
esp_loader_error_t esp_loader_change_transmission_rate(uint32_t transmission_rate);
/**
* @brief Verify target's flash integrity by checking MD5.
* MD5 checksum is computed from data pushed to target's memory by calling
* esp_loader_flash_write() function and compared against target's MD5.
* Target computes checksum based on offset and image_size passed to
* esp_loader_flash_start() function.
*
* @note This function is only available if MD5_ENABLED is set.
*
* @return
* - ESP_LOADER_SUCCESS Success
* - ESP_LOADER_ERROR_INVALID_MD5 MD5 does not match
* - ESP_LOADER_ERROR_TIMEOUT Timeout
* - ESP_LOADER_ERROR_INVALID_RESPONSE Internal error
* - ESP_LOADER_ERROR_UNSUPPORTED_FUNC Unsupported on the target
*/
#if MD5_ENABLED
esp_loader_error_t esp_loader_flash_verify(void);
#endif
/**
* @brief Toggles reset pin.
*/
void esp_loader_reset_target(void);
#ifdef __cplusplus
}
#endif

View File

@@ -0,0 +1,112 @@
/* Copyright 2020-2023 Espressif Systems (Shanghai) CO LTD
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <stdint.h>
#include "esp_loader.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
* @brief Changes the transmission rate of the used peripheral.
*/
esp_loader_error_t loader_port_change_transmission_rate(uint32_t transmission_rate);
/**
* @brief Writes data over the io interface.
*
* @param data[in] Buffer with data to be written.
* @param size[in] Size of data in bytes.
* @param timeout[in] Timeout in milliseconds.
*
* @return
* - ESP_LOADER_SUCCESS Success
* - ESP_LOADER_ERROR_TIMEOUT Timeout elapsed
*/
esp_loader_error_t loader_port_write(const uint8_t *data, uint16_t size, uint32_t timeout);
/**
* @brief Reads data from the io interface.
*
* @param data[out] Buffer into which received data will be written.
* @param size[in] Number of bytes to read.
* @param timeout[in] Timeout in milliseconds.
*
* @return
* - ESP_LOADER_SUCCESS Success
* - ESP_LOADER_ERROR_TIMEOUT Timeout elapsed
*/
esp_loader_error_t loader_port_read(uint8_t *data, uint16_t size, uint32_t timeout);
/**
* @brief Delay in milliseconds.
*
* @param ms[in] Number of milliseconds.
*
*/
void loader_port_delay_ms(uint32_t ms);
/**
* @brief Starts timeout timer.
*
* @param ms[in] Number of milliseconds.
*
*/
void loader_port_start_timer(uint32_t ms);
/**
* @brief Returns remaining time since timer was started by calling esp_loader_start_timer.
* 0 if timer has elapsed.
*
* @return Number of milliseconds.
*
*/
uint32_t loader_port_remaining_time(void);
/**
* @brief Asserts bootstrap pins to enter boot mode and toggles reset pin.
*
* @note Reset pin should stay asserted for at least 20 milliseconds.
*/
void loader_port_enter_bootloader(void);
/**
* @brief Toggles reset pin.
*
* @note Reset pin should stay asserted for at least 20 milliseconds.
*/
void loader_port_reset_target(void);
/**
* @brief Function can be defined by user to print debug message.
*
* @note Empty weak function is used, otherwise.
*
*/
void loader_port_debug_print(const char *str);
#ifdef SERIAL_FLASHER_INTERFACE_SPI
/**
* @brief Sets the chip select to a defined level
*/
void loader_port_spi_set_cs(uint32_t level);
#endif /* SERIAL_FLASHER_INTERFACE_SPI */
#ifdef __cplusplus
}
#endif

View File

@@ -0,0 +1,33 @@
/* Copyright 2020 Espressif Systems (Shanghai) PTE LTD
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <stdint.h>
#include "esp_loader.h"
typedef struct {
uint32_t cmd;
uint32_t usr;
uint32_t usr1;
uint32_t usr2;
uint32_t w0;
uint32_t mosi_dlen;
uint32_t miso_dlen;
} target_registers_t;
esp_loader_error_t loader_detect_chip(target_chip_t *target, const target_registers_t **regs);
esp_loader_error_t loader_read_spi_config(target_chip_t target_chip, uint32_t *spi_config);
bool encryption_in_begin_flash_cmd(target_chip_t target);

View File

@@ -0,0 +1,28 @@
/*
* MD5 hash implementation and interface functions
* Copyright (c) 2003-2005, Jouni Malinen <j@w1.fi>
*
* This software may be distributed under the terms of the BSD license.
* See README for more details.
*/
#pragma once
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
struct MD5Context {
uint32_t buf[4];
uint32_t bits[2];
uint8_t in[64];
};
void MD5Init(struct MD5Context *context);
void MD5Update(struct MD5Context *context, unsigned char const *buf, unsigned len);
void MD5Final(unsigned char digest[16], struct MD5Context *context);
#ifdef __cplusplus
}
#endif

View File

@@ -0,0 +1,236 @@
/* Copyright 2020-2023 Espressif Systems (Shanghai) CO LTD
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <stdint.h>
#include <stdbool.h>
#include "esp_loader.h"
#ifdef __cplusplus
extern "C" {
#endif
#define STATUS_FAILURE 1
#define STATUS_SUCCESS 0
#define READ_DIRECTION 1
#define WRITE_DIRECTION 0
#define MD5_SIZE 32
typedef enum __attribute__((packed))
{
FLASH_BEGIN = 0x02,
FLASH_DATA = 0x03,
FLASH_END = 0x04,
MEM_BEGIN = 0x05,
MEM_END = 0x06,
MEM_DATA = 0x07,
SYNC = 0x08,
WRITE_REG = 0x09,
READ_REG = 0x0a,
SPI_SET_PARAMS = 0x0b,
SPI_ATTACH = 0x0d,
CHANGE_BAUDRATE = 0x0f,
FLASH_DEFL_BEGIN = 0x10,
FLASH_DEFL_DATA = 0x11,
FLASH_DEFL_END = 0x12,
SPI_FLASH_MD5 = 0x13,
} command_t;
typedef enum __attribute__((packed))
{
RESPONSE_OK = 0x00,
INVALID_COMMAND = 0x05, // parameters or length field is invalid
COMMAND_FAILED = 0x06, // Failed to act on received message
INVALID_CRC = 0x07, // Invalid CRC in message
FLASH_WRITE_ERR = 0x08, // After writing a block of data to flash, the ROM loader reads the value back and the 8-bit CRC is compared to the data read from flash. If they don't match, this error is returned.
FLASH_READ_ERR = 0x09, // SPI read failed
READ_LENGTH_ERR = 0x0a, // SPI read request length is too long
DEFLATE_ERROR = 0x0b, // ESP32 compressed uploads only
} error_code_t;
typedef struct __attribute__((packed))
{
uint8_t direction;
uint8_t command; // One of command_t
uint16_t size;
uint32_t checksum;
} command_common_t;
typedef struct __attribute__((packed))
{
command_common_t common;
uint32_t erase_size;
uint32_t packet_count;
uint32_t packet_size;
uint32_t offset;
uint32_t encrypted;
} flash_begin_command_t;
typedef struct __attribute__((packed))
{
command_common_t common;
uint32_t data_size;
uint32_t sequence_number;
uint32_t zero_0;
uint32_t zero_1;
} data_command_t;
typedef struct __attribute__((packed))
{
command_common_t common;
uint32_t stay_in_loader;
} flash_end_command_t;
typedef struct __attribute__((packed))
{
command_common_t common;
uint32_t total_size;
uint32_t blocks;
uint32_t block_size;
uint32_t offset;
} mem_begin_command_t;
typedef struct __attribute__((packed))
{
command_common_t common;
uint32_t stay_in_loader;
uint32_t entry_point_address;
} mem_end_command_t;
typedef struct __attribute__((packed))
{
command_common_t common;
uint8_t sync_sequence[36];
} sync_command_t;
typedef struct __attribute__((packed))
{
command_common_t common;
uint32_t address;
uint32_t value;
uint32_t mask;
uint32_t delay_us;
} write_reg_command_t;
typedef struct __attribute__((packed))
{
command_common_t common;
uint32_t address;
} read_reg_command_t;
typedef struct __attribute__((packed))
{
command_common_t common;
uint32_t configuration;
uint32_t zero; // ESP32 ROM only
} spi_attach_command_t;
typedef struct __attribute__((packed))
{
command_common_t common;
uint32_t new_baudrate;
uint32_t old_baudrate;
} change_baudrate_command_t;
typedef struct __attribute__((packed))
{
command_common_t common;
uint32_t address;
uint32_t size;
uint32_t reserved_0;
uint32_t reserved_1;
} spi_flash_md5_command_t;
typedef struct __attribute__((packed))
{
uint8_t direction;
uint8_t command; // One of command_t
uint16_t size;
uint32_t value;
} common_response_t;
typedef struct __attribute__((packed))
{
uint8_t failed;
uint8_t error;
} response_status_t;
typedef struct __attribute__((packed))
{
common_response_t common;
response_status_t status;
} response_t;
typedef struct __attribute__((packed))
{
common_response_t common;
uint8_t md5[MD5_SIZE]; // ROM only
response_status_t status;
} rom_md5_response_t;
typedef struct __attribute__((packed))
{
command_common_t common;
uint32_t id;
uint32_t total_size;
uint32_t block_size;
uint32_t sector_size;
uint32_t page_size;
uint32_t status_mask;
} write_spi_command_t;
esp_loader_error_t loader_initialize_conn(esp_loader_connect_args_t *connect_args);
#ifdef SERIAL_FLASHER_INTERFACE_UART
esp_loader_error_t loader_flash_begin_cmd(uint32_t offset, uint32_t erase_size, uint32_t block_size, uint32_t blocks_to_write, bool encryption);
esp_loader_error_t loader_flash_data_cmd(const uint8_t *data, uint32_t size);
esp_loader_error_t loader_flash_end_cmd(bool stay_in_loader);
esp_loader_error_t loader_sync_cmd(void);
esp_loader_error_t loader_spi_attach_cmd(uint32_t config);
esp_loader_error_t loader_md5_cmd(uint32_t address, uint32_t size, uint8_t *md5_out);
esp_loader_error_t loader_spi_parameters(uint32_t total_size);
#endif /* SERIAL_FLASHER_INTERFACE_UART */
esp_loader_error_t loader_mem_begin_cmd(uint32_t offset, uint32_t size, uint32_t blocks_to_write, uint32_t block_size);
esp_loader_error_t loader_mem_data_cmd(const uint8_t *data, uint32_t size);
esp_loader_error_t loader_mem_end_cmd(uint32_t entrypoint);
esp_loader_error_t loader_mem_begin_cmd(uint32_t offset, uint32_t size, uint32_t blocks_to_write, uint32_t block_size);
esp_loader_error_t loader_mem_data_cmd(const uint8_t *data, uint32_t size);
esp_loader_error_t loader_mem_end_cmd(uint32_t entrypoint);
esp_loader_error_t loader_write_reg_cmd(uint32_t address, uint32_t value, uint32_t mask, uint32_t delay_us);
esp_loader_error_t loader_read_reg_cmd(uint32_t address, uint32_t *reg);
esp_loader_error_t loader_change_baudrate_cmd(uint32_t baudrate);
#ifdef __cplusplus
}
#endif

View File

@@ -0,0 +1,31 @@
/* Copyright 2020-2023 Espressif Systems (Shanghai) CO LTD
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <stdint.h>
#include <stdbool.h>
#include <stddef.h>
#include "esp_loader.h"
#include "protocol.h"
void log_loader_internal_error(error_code_t error);
esp_loader_error_t send_cmd(const void *cmd_data, uint32_t size, uint32_t *reg_value);
esp_loader_error_t send_cmd_with_data(const void *cmd_data, size_t cmd_size,
const void *data, size_t data_size);
esp_loader_error_t send_cmd_md5(const void *cmd_data, size_t cmd_size, uint8_t md5_out[MD5_SIZE]);

View File

@@ -0,0 +1,24 @@
/* Copyright 2020-2023 Espressif Systems (Shanghai) CO LTD
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#warning Please replace serial_io.h with esp_loader_io.h and change the function names \
to match the new API
/* Defines used to avoid breaking existing ports */
#define loader_port_change_baudrate loader_port_change_transmission_rate
#define loader_port_serial_write loader_port_write
#define loader_port_serial_read loader_port_read
#include "esp_loader_io.h"

View File

@@ -0,0 +1,28 @@
/* Copyright 2020-2023 Espressif Systems (Shanghai) CO LTD
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include "esp_loader.h"
#include <stdint.h>
#include <stdlib.h>
esp_loader_error_t SLIP_receive_data(uint8_t *buff, size_t size);
esp_loader_error_t SLIP_receive_packet(uint8_t *buff, size_t size);
esp_loader_error_t SLIP_send(const uint8_t *data, size_t size);
esp_loader_error_t SLIP_send_delimiter(void);

View File

@@ -0,0 +1,4 @@
{
"name": "esp-serial-flasher",
"version": "0.0.0+20230909102418"
}

View File

@@ -0,0 +1,186 @@
#include <Arduino.h>
/* Copyright 2020-2023 Espressif Systems (Shanghai) CO LTD
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "esp32_port.h"
#include "driver/uart.h"
#include "driver/gpio.h"
#include "esp_timer.h"
#include "esp_log.h"
#include "esp_idf_version.h"
#include <unistd.h>
#ifdef SERIAL_FLASHER_DEBUG_TRACE
static void transfer_debug_print(const uint8_t *data, uint16_t size, bool write)
{
static bool write_prev = false;
if (write_prev != write) {
write_prev = write;
printf("\n%s %d bytes: ", write ? "Write" : "Read", size);
}
for (uint32_t i = 0; i < size; i++) {
printf("%02x", data[i]);
if ((i + 1) % 16 == 0) {
printf("\n");
}
}
}
#endif
static int64_t s_time_end;
static int32_t s_uart_port;
static int32_t s_reset_trigger_pin;
static int32_t s_gpio0_trigger_pin;
esp_loader_error_t loader_port_esp32_init(const loader_esp32_config_t *config)
{
s_uart_port = config->uart_port;
s_reset_trigger_pin = config->reset_trigger_pin;
s_gpio0_trigger_pin = config->gpio0_trigger_pin;
// Initialize UART
uart_config_t uart_config = {
.baud_rate = config->baud_rate,
.data_bits = UART_DATA_8_BITS,
.parity = UART_PARITY_DISABLE,
.stop_bits = UART_STOP_BITS_1,
.flow_ctrl = UART_HW_FLOWCTRL_DISABLE,
#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 0, 0)
.source_clk = UART_SCLK_DEFAULT,
#endif
};
int rx_buffer_size = config->rx_buffer_size ? config->rx_buffer_size : 400;
int tx_buffer_size = config->tx_buffer_size ? config->tx_buffer_size : 400;
QueueHandle_t *uart_queue = config->uart_queue ? config->uart_queue : NULL;
int queue_size = config->queue_size ? config->queue_size : 0;
if ( uart_param_config(s_uart_port, &uart_config) != ESP_OK ) {
return ESP_LOADER_ERROR_FAIL;
}
if ( uart_set_pin(s_uart_port, config->uart_tx_pin, config->uart_rx_pin, UART_PIN_NO_CHANGE, UART_PIN_NO_CHANGE) != ESP_OK ) {
return ESP_LOADER_ERROR_FAIL;
}
if ( uart_driver_install(s_uart_port, rx_buffer_size, tx_buffer_size, queue_size, uart_queue, 0) != ESP_OK ) {
return ESP_LOADER_ERROR_FAIL;
}
// Initialize boot pin selection pins
gpio_reset_pin(s_reset_trigger_pin);
gpio_set_pull_mode(s_reset_trigger_pin, GPIO_PULLUP_ONLY);
gpio_set_direction(s_reset_trigger_pin, GPIO_MODE_OUTPUT);
gpio_reset_pin(s_gpio0_trigger_pin);
gpio_set_pull_mode(s_gpio0_trigger_pin, GPIO_PULLUP_ONLY);
gpio_set_direction(s_gpio0_trigger_pin, GPIO_MODE_OUTPUT);
return ESP_LOADER_SUCCESS;
}
void loader_port_esp32_deinit(void)
{
uart_driver_delete(s_uart_port);
}
esp_loader_error_t loader_port_write(const uint8_t *data, uint16_t size, uint32_t timeout)
{
uart_write_bytes(s_uart_port, (const char *)data, size);
esp_err_t err = uart_wait_tx_done(s_uart_port, pdMS_TO_TICKS(timeout));
if (err == ESP_OK) {
#ifdef SERIAL_FLASHER_DEBUG_TRACE
transfer_debug_print(data, size, true);
#endif
return ESP_LOADER_SUCCESS;
} else if (err == ESP_ERR_TIMEOUT) {
return ESP_LOADER_ERROR_TIMEOUT;
} else {
return ESP_LOADER_ERROR_FAIL;
}
}
esp_loader_error_t loader_port_read(uint8_t *data, uint16_t size, uint32_t timeout)
{
int read = uart_read_bytes(s_uart_port, data, size, pdMS_TO_TICKS(timeout));
if (read < 0) {
return ESP_LOADER_ERROR_FAIL;
} else if (read < size) {
#ifdef SERIAL_FLASHER_DEBUG_TRACE
transfer_debug_print(data, read, false);
#endif
return ESP_LOADER_ERROR_TIMEOUT;
} else {
#ifdef SERIAL_FLASHER_DEBUG_TRACE
transfer_debug_print(data, read, false);
#endif
return ESP_LOADER_SUCCESS;
}
}
// Set GPIO0 LOW, then
// assert reset pin for 50 milliseconds.
void loader_port_enter_bootloader(void)
{
gpio_set_level(s_gpio0_trigger_pin, 0);
loader_port_reset_target();
loader_port_delay_ms(SERIAL_FLASHER_BOOT_HOLD_TIME_MS);
gpio_set_level(s_gpio0_trigger_pin, 1);
}
void loader_port_reset_target(void)
{
gpio_set_level(s_reset_trigger_pin, 0);
loader_port_delay_ms(SERIAL_FLASHER_RESET_HOLD_TIME_MS);
gpio_set_level(s_reset_trigger_pin, 1);
}
void loader_port_delay_ms(uint32_t ms)
{
usleep(ms * 1000);
}
void loader_port_start_timer(uint32_t ms)
{
s_time_end = esp_timer_get_time() + ms * 1000;
}
uint32_t loader_port_remaining_time(void)
{
int64_t remaining = (s_time_end - esp_timer_get_time()) / 1000;
return (remaining > 0) ? (uint32_t)remaining : 0;
}
void loader_port_debug_print(const char *str)
{
printf("DEBUG: %s\n", str);
}
esp_loader_error_t loader_port_change_transmission_rate(uint32_t baudrate)
{
esp_err_t err = uart_set_baudrate(s_uart_port, baudrate);
return (err == ESP_OK) ? ESP_LOADER_SUCCESS : ESP_LOADER_ERROR_FAIL;
}

View File

@@ -0,0 +1,417 @@
#include <Arduino.h>
/* Copyright 2020-2023 Espressif Systems (Shanghai) CO LTD
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "protocol.h"
#include "esp_loader_io.h"
#include "esp_loader.h"
#include "esp_targets.h"
#include "md5_hash.h"
#include <string.h>
#include <assert.h>
#ifndef MAX
#define MAX(a, b) ((a) > (b)) ? (a) : (b)
#endif
#ifndef MIN
#define MIN(a, b) ((a) < (b)) ? (a) : (b)
#endif
#ifndef ROUNDUP
#define ROUNDUP(a, b) (((int)a + (int)b - 1) / (int)b)
#endif
static const uint32_t DEFAULT_TIMEOUT = 3000;
static const uint32_t DEFAULT_FLASH_TIMEOUT = 3000; // timeout for most flash operations
static const uint32_t LOAD_RAM_TIMEOUT_PER_MB = 2000000; // timeout (per megabyte) for erasing a region
typedef enum {
SPI_FLASH_READ_ID = 0x9F
} spi_flash_cmd_t;
static const target_registers_t *s_reg = NULL;
static target_chip_t s_target = ESP_UNKNOWN_CHIP;
#if MD5_ENABLED
static const uint32_t MD5_TIMEOUT_PER_MB = 800;
static struct MD5Context s_md5_context;
static uint32_t s_start_address;
static uint32_t s_image_size;
static inline void init_md5(uint32_t address, uint32_t size)
{
s_start_address = address;
s_image_size = size;
MD5Init(&s_md5_context);
}
static inline void md5_update(const uint8_t *data, uint32_t size)
{
MD5Update(&s_md5_context, data, size);
}
static inline void md5_final(uint8_t digets[16])
{
MD5Final(digets, &s_md5_context);
}
#else
static inline void init_md5(uint32_t address, uint32_t size) { }
static inline void md5_update(const uint8_t *data, uint32_t size) { }
static inline void md5_final(uint8_t digets[16]) { }
#endif
static uint32_t timeout_per_mb(uint32_t size_bytes, uint32_t time_per_mb)
{
uint32_t timeout = time_per_mb * (size_bytes / 1e6);
return MAX(timeout, DEFAULT_FLASH_TIMEOUT);
}
esp_loader_error_t esp_loader_connect(esp_loader_connect_args_t *connect_args)
{
loader_port_enter_bootloader();
RETURN_ON_ERROR(loader_initialize_conn(connect_args));
RETURN_ON_ERROR(loader_detect_chip(&s_target, &s_reg));
#ifdef SERIAL_FLASHER_INTERFACE_UART
esp_loader_error_t err;
uint32_t spi_config;
if (s_target == ESP8266_CHIP) {
err = loader_flash_begin_cmd(0, 0, 0, 0, s_target);
} else {
RETURN_ON_ERROR( loader_read_spi_config(s_target, &spi_config) );
loader_port_start_timer(DEFAULT_TIMEOUT);
err = loader_spi_attach_cmd(spi_config);
}
return err;
#endif /* SERIAL_FLASHER_INTERFACE_UART */
return ESP_LOADER_SUCCESS;
}
target_chip_t esp_loader_get_target(void)
{
return s_target;
}
#ifdef SERIAL_FLASHER_INTERFACE_UART
static uint32_t s_flash_write_size = 0;
static esp_loader_error_t spi_set_data_lengths(size_t mosi_bits, size_t miso_bits)
{
if (mosi_bits > 0) {
RETURN_ON_ERROR( esp_loader_write_register(s_reg->mosi_dlen, mosi_bits - 1) );
}
if (miso_bits > 0) {
RETURN_ON_ERROR( esp_loader_write_register(s_reg->miso_dlen, miso_bits - 1) );
}
return ESP_LOADER_SUCCESS;
}
static esp_loader_error_t spi_set_data_lengths_8266(size_t mosi_bits, size_t miso_bits)
{
uint32_t mosi_mask = (mosi_bits == 0) ? 0 : mosi_bits - 1;
uint32_t miso_mask = (miso_bits == 0) ? 0 : miso_bits - 1;
return esp_loader_write_register(s_reg->usr1, (miso_mask << 8) | (mosi_mask << 17));
}
static esp_loader_error_t spi_flash_command(spi_flash_cmd_t cmd, void *data_tx, size_t tx_size, void *data_rx, size_t rx_size)
{
assert(rx_size <= 32); // Reading more than 32 bits back from a SPI flash operation is unsupported
assert(tx_size <= 64); // Writing more than 64 bytes of data with one SPI command is unsupported
uint32_t SPI_USR_CMD = (1 << 31);
uint32_t SPI_USR_MISO = (1 << 28);
uint32_t SPI_USR_MOSI = (1 << 27);
uint32_t SPI_CMD_USR = (1 << 18);
uint32_t CMD_LEN_SHIFT = 28;
// Save SPI configuration
uint32_t old_spi_usr;
uint32_t old_spi_usr2;
RETURN_ON_ERROR( esp_loader_read_register(s_reg->usr, &old_spi_usr) );
RETURN_ON_ERROR( esp_loader_read_register(s_reg->usr2, &old_spi_usr2) );
if (s_target == ESP8266_CHIP) {
RETURN_ON_ERROR( spi_set_data_lengths_8266(tx_size, rx_size) );
} else {
RETURN_ON_ERROR( spi_set_data_lengths(tx_size, rx_size) );
}
uint32_t usr_reg_2 = (7 << CMD_LEN_SHIFT) | cmd;
uint32_t usr_reg = SPI_USR_CMD;
if (rx_size > 0) {
usr_reg |= SPI_USR_MISO;
}
if (tx_size > 0) {
usr_reg |= SPI_USR_MOSI;
}
RETURN_ON_ERROR( esp_loader_write_register(s_reg->usr, usr_reg) );
RETURN_ON_ERROR( esp_loader_write_register(s_reg->usr2, usr_reg_2 ) );
if (tx_size == 0) {
// clear data register before we read it
RETURN_ON_ERROR( esp_loader_write_register(s_reg->w0, 0) );
} else {
uint32_t *data = (uint32_t *)data_tx;
uint32_t words_to_write = (tx_size + 31) / (8 * 4);
uint32_t data_reg_addr = s_reg->w0;
while (words_to_write--) {
uint32_t word = *data++;
RETURN_ON_ERROR( esp_loader_write_register(data_reg_addr, word) );
data_reg_addr += 4;
}
}
RETURN_ON_ERROR( esp_loader_write_register(s_reg->cmd, SPI_CMD_USR) );
uint32_t trials = 10;
while (trials--) {
uint32_t cmd_reg;
RETURN_ON_ERROR( esp_loader_read_register(s_reg->cmd, &cmd_reg) );
if ((cmd_reg & SPI_CMD_USR) == 0) {
break;
}
}
if (trials == 0) {
return ESP_LOADER_ERROR_TIMEOUT;
}
RETURN_ON_ERROR( esp_loader_read_register(s_reg->w0, data_rx) );
// Restore SPI configuration
RETURN_ON_ERROR( esp_loader_write_register(s_reg->usr, old_spi_usr) );
RETURN_ON_ERROR( esp_loader_write_register(s_reg->usr2, old_spi_usr2) );
return ESP_LOADER_SUCCESS;
}
static esp_loader_error_t detect_flash_size(size_t *flash_size)
{
uint32_t flash_id = 0;
RETURN_ON_ERROR( spi_flash_command(SPI_FLASH_READ_ID, NULL, 0, &flash_id, 24) );
uint32_t size_id = flash_id >> 16;
if (size_id < 0x12 || size_id > 0x18) {
return ESP_LOADER_ERROR_UNSUPPORTED_CHIP;
}
*flash_size = 1 << size_id;
return ESP_LOADER_SUCCESS;
}
static uint32_t calc_erase_size(const target_chip_t target, const uint32_t offset,
const uint32_t image_size)
{
if (target != ESP8266_CHIP) {
return image_size;
} else {
/* Needed to fix a bug in the ESP8266 ROM */
const uint32_t sectors_per_block = 16U;
const uint32_t sector_size = 4096U;
const uint32_t num_sectors = (image_size + sector_size - 1) / sector_size;
const uint32_t start_sector = offset / sector_size;
uint32_t head_sectors = sectors_per_block - (start_sector % sectors_per_block);
/* The ROM bug deletes extra num_sectors if we don't cross the block boundary
and extra head_sectors if we do */
if (num_sectors <= head_sectors) {
return ((num_sectors + 1) / 2) * sector_size;
} else {
return (num_sectors - head_sectors) * sector_size;
}
}
}
esp_loader_error_t esp_loader_flash_start(uint32_t offset, uint32_t image_size, uint32_t block_size)
{
s_flash_write_size = block_size;
size_t flash_size = 0;
if (detect_flash_size(&flash_size) == ESP_LOADER_SUCCESS) {
if (image_size > flash_size) {
return ESP_LOADER_ERROR_IMAGE_SIZE;
}
loader_port_start_timer(DEFAULT_TIMEOUT);
RETURN_ON_ERROR( loader_spi_parameters(flash_size) );
} else {
loader_port_debug_print("Flash size detection failed, falling back to default");
}
init_md5(offset, image_size);
bool encryption_in_cmd = encryption_in_begin_flash_cmd(s_target);
const uint32_t erase_size = calc_erase_size(esp_loader_get_target(), offset, image_size);
const uint32_t blocks_to_write = (image_size + block_size - 1) / block_size;
const uint32_t erase_region_timeout_per_mb = 10000;
loader_port_start_timer(timeout_per_mb(erase_size, erase_region_timeout_per_mb));
return loader_flash_begin_cmd(offset, erase_size, block_size, blocks_to_write, encryption_in_cmd);
}
esp_loader_error_t esp_loader_flash_write(void *payload, uint32_t size)
{
uint32_t padding_bytes = s_flash_write_size - size;
uint8_t *data = (uint8_t *)payload;
uint32_t padding_index = size;
if (size > s_flash_write_size) {
return ESP_LOADER_ERROR_INVALID_PARAM;
}
const uint8_t padding_pattern = 0xFF;
while (padding_bytes--) {
data[padding_index++] = padding_pattern;
}
md5_update(payload, (size + 3) & ~3);
loader_port_start_timer(DEFAULT_TIMEOUT);
return loader_flash_data_cmd(data, s_flash_write_size);
}
esp_loader_error_t esp_loader_flash_finish(bool reboot)
{
loader_port_start_timer(DEFAULT_TIMEOUT);
return loader_flash_end_cmd(!reboot);
}
#endif /* SERIAL_FLASHER_INTERFACE_UART */
esp_loader_error_t esp_loader_mem_start(uint32_t offset, uint32_t size, uint32_t block_size)
{
uint32_t blocks_to_write = ROUNDUP(size, block_size);
loader_port_start_timer(timeout_per_mb(size, LOAD_RAM_TIMEOUT_PER_MB));
return loader_mem_begin_cmd(offset, size, blocks_to_write, block_size);
}
esp_loader_error_t esp_loader_mem_write(const void *payload, uint32_t size)
{
const uint8_t *data = (const uint8_t *)payload;
loader_port_start_timer(timeout_per_mb(size, LOAD_RAM_TIMEOUT_PER_MB));
return loader_mem_data_cmd(data, size);
}
esp_loader_error_t esp_loader_mem_finish(uint32_t entrypoint)
{
loader_port_start_timer(DEFAULT_TIMEOUT);
return loader_mem_end_cmd(entrypoint);
}
esp_loader_error_t esp_loader_read_register(uint32_t address, uint32_t *reg_value)
{
loader_port_start_timer(DEFAULT_TIMEOUT);
return loader_read_reg_cmd(address, reg_value);
}
esp_loader_error_t esp_loader_write_register(uint32_t address, uint32_t reg_value)
{
loader_port_start_timer(DEFAULT_TIMEOUT);
return loader_write_reg_cmd(address, reg_value, 0xFFFFFFFF, 0);
}
esp_loader_error_t esp_loader_change_transmission_rate(uint32_t transmission_rate)
{
if (s_target == ESP8266_CHIP) {
return ESP_LOADER_ERROR_UNSUPPORTED_FUNC;
}
loader_port_start_timer(DEFAULT_TIMEOUT);
return loader_change_baudrate_cmd(transmission_rate);
}
#if MD5_ENABLED
static void hexify(const uint8_t raw_md5[16], uint8_t hex_md5_out[32])
{
static const uint8_t dec_to_hex[] = {
'0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
};
for (int i = 0; i < 16; i++) {
*hex_md5_out++ = dec_to_hex[raw_md5[i] >> 4];
*hex_md5_out++ = dec_to_hex[raw_md5[i] & 0xF];
}
}
esp_loader_error_t esp_loader_flash_verify(void)
{
if (s_target == ESP8266_CHIP) {
return ESP_LOADER_ERROR_UNSUPPORTED_FUNC;
}
uint8_t raw_md5[16] = {0};
/* Zero termination and new line character require 2 bytes */
uint8_t hex_md5[MD5_SIZE + 2] = {0};
uint8_t received_md5[MD5_SIZE + 2] = {0};
md5_final(raw_md5);
hexify(raw_md5, hex_md5);
loader_port_start_timer(timeout_per_mb(s_image_size, MD5_TIMEOUT_PER_MB));
RETURN_ON_ERROR( loader_md5_cmd(s_start_address, s_image_size, received_md5) );
bool md5_match = memcmp(hex_md5, received_md5, MD5_SIZE) == 0;
if (!md5_match) {
hex_md5[MD5_SIZE] = '\n';
received_md5[MD5_SIZE] = '\n';
loader_port_debug_print("Error: MD5 checksum does not match:\n");
loader_port_debug_print("Expected:\n");
loader_port_debug_print((char *)received_md5);
loader_port_debug_print("Actual:\n");
loader_port_debug_print((char *)hex_md5);
return ESP_LOADER_ERROR_INVALID_MD5;
}
return ESP_LOADER_SUCCESS;
}
#endif
void esp_loader_reset_target(void)
{
loader_port_reset_target();
}

View File

@@ -0,0 +1,297 @@
/* Copyright 2020 Espressif Systems (Shanghai) PTE LTD
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "esp_targets.h"
#include <stddef.h>
#define MAX_MAGIC_VALUES 2
typedef esp_loader_error_t (*read_spi_config_t)(uint32_t efuse_base, uint32_t *spi_config);
typedef struct {
target_registers_t regs;
uint32_t efuse_base;
uint32_t chip_magic_value[MAX_MAGIC_VALUES];
read_spi_config_t read_spi_config;
bool encryption_in_begin_flash_cmd;
} esp_target_t;
// This ROM address has a different value on each chip model
#define CHIP_DETECT_MAGIC_REG_ADDR 0x40001000
#define ESP8266_SPI_REG_BASE 0x60000200
#define ESP32S2_SPI_REG_BASE 0x3f402000
#define ESP32C6_SPI_REG_BASE 0x60003000
#define ESP32xx_SPI_REG_BASE 0x60002000
#define ESP32_SPI_REG_BASE 0x3ff42000
static esp_loader_error_t spi_config_esp32(uint32_t efuse_base, uint32_t *spi_config);
static esp_loader_error_t spi_config_esp32xx(uint32_t efuse_base, uint32_t *spi_config);
static const esp_target_t esp_target[ESP_MAX_CHIP] = {
// ESP8266
{
.regs = {
.cmd = ESP8266_SPI_REG_BASE + 0x00,
.usr = ESP8266_SPI_REG_BASE + 0x1c,
.usr1 = ESP8266_SPI_REG_BASE + 0x20,
.usr2 = ESP8266_SPI_REG_BASE + 0x24,
.w0 = ESP8266_SPI_REG_BASE + 0x40,
.mosi_dlen = 0,
.miso_dlen = 0,
},
.efuse_base = 0, // Not used
.chip_magic_value = { 0xfff0c101, 0 },
.read_spi_config = NULL, // Not used
.encryption_in_begin_flash_cmd = false,
},
// ESP32
{
.regs = {
.cmd = ESP32_SPI_REG_BASE + 0x00,
.usr = ESP32_SPI_REG_BASE + 0x1c,
.usr1 = ESP32_SPI_REG_BASE + 0x20,
.usr2 = ESP32_SPI_REG_BASE + 0x24,
.w0 = ESP32_SPI_REG_BASE + 0x80,
.mosi_dlen = ESP32_SPI_REG_BASE + 0x28,
.miso_dlen = ESP32_SPI_REG_BASE + 0x2c,
},
.efuse_base = 0x3ff5A000,
.chip_magic_value = { 0x00f01d83, 0 },
.read_spi_config = spi_config_esp32,
.encryption_in_begin_flash_cmd = false,
},
// ESP32S2
{
.regs = {
.cmd = ESP32S2_SPI_REG_BASE + 0x00,
.usr = ESP32S2_SPI_REG_BASE + 0x18,
.usr1 = ESP32S2_SPI_REG_BASE + 0x1c,
.usr2 = ESP32S2_SPI_REG_BASE + 0x20,
.w0 = ESP32S2_SPI_REG_BASE + 0x58,
.mosi_dlen = ESP32S2_SPI_REG_BASE + 0x24,
.miso_dlen = ESP32S2_SPI_REG_BASE + 0x28,
},
.efuse_base = 0x3f41A000,
.chip_magic_value = { 0x000007c6, 0 },
.read_spi_config = spi_config_esp32xx,
.encryption_in_begin_flash_cmd = true,
},
// ESP32C3
{
.regs = {
.cmd = ESP32xx_SPI_REG_BASE + 0x00,
.usr = ESP32xx_SPI_REG_BASE + 0x18,
.usr1 = ESP32xx_SPI_REG_BASE + 0x1c,
.usr2 = ESP32xx_SPI_REG_BASE + 0x20,
.w0 = ESP32xx_SPI_REG_BASE + 0x58,
.mosi_dlen = ESP32xx_SPI_REG_BASE + 0x24,
.miso_dlen = ESP32xx_SPI_REG_BASE + 0x28,
},
.efuse_base = 0x60008800,
.chip_magic_value = { 0x6921506f, 0x1b31506f },
.read_spi_config = spi_config_esp32xx,
.encryption_in_begin_flash_cmd = true,
},
// ESP32S3
{
.regs = {
.cmd = ESP32xx_SPI_REG_BASE + 0x00,
.usr = ESP32xx_SPI_REG_BASE + 0x18,
.usr1 = ESP32xx_SPI_REG_BASE + 0x1c,
.usr2 = ESP32xx_SPI_REG_BASE + 0x20,
.w0 = ESP32xx_SPI_REG_BASE + 0x58,
.mosi_dlen = ESP32xx_SPI_REG_BASE + 0x24,
.miso_dlen = ESP32xx_SPI_REG_BASE + 0x28,
},
.efuse_base = 0x60007000,
.chip_magic_value = { 0x00000009, 0 },
.read_spi_config = spi_config_esp32xx,
.encryption_in_begin_flash_cmd = true,
},
// ESP32C2
{
.regs = {
.cmd = ESP32xx_SPI_REG_BASE + 0x00,
.usr = ESP32xx_SPI_REG_BASE + 0x18,
.usr1 = ESP32xx_SPI_REG_BASE + 0x1c,
.usr2 = ESP32xx_SPI_REG_BASE + 0x20,
.w0 = ESP32xx_SPI_REG_BASE + 0x58,
.mosi_dlen = ESP32xx_SPI_REG_BASE + 0x24,
.miso_dlen = ESP32xx_SPI_REG_BASE + 0x28,
},
.efuse_base = 0x60008800,
.chip_magic_value = { 0x6f51306f, 0x7c41a06f },
.read_spi_config = spi_config_esp32xx,
.encryption_in_begin_flash_cmd = true,
},
// ESP32H4
{
.regs = {
.cmd = ESP32xx_SPI_REG_BASE + 0x00,
.usr = ESP32xx_SPI_REG_BASE + 0x18,
.usr1 = ESP32xx_SPI_REG_BASE + 0x1c,
.usr2 = ESP32xx_SPI_REG_BASE + 0x20,
.w0 = ESP32xx_SPI_REG_BASE + 0x58,
.mosi_dlen = ESP32xx_SPI_REG_BASE + 0x24,
.miso_dlen = ESP32xx_SPI_REG_BASE + 0x28,
},
.efuse_base = 0x6001A000,
.chip_magic_value = {0xca26cc22, 0x6881b06f}, // ESP32H4-BETA1, ESP32H4-BETA2
.read_spi_config = spi_config_esp32xx,
.encryption_in_begin_flash_cmd = true,
},
// ESP32H2
{
.regs = {
.cmd = ESP32xx_SPI_REG_BASE + 0x00,
.usr = ESP32xx_SPI_REG_BASE + 0x18,
.usr1 = ESP32xx_SPI_REG_BASE + 0x1c,
.usr2 = ESP32xx_SPI_REG_BASE + 0x20,
.w0 = ESP32xx_SPI_REG_BASE + 0x58,
.mosi_dlen = ESP32xx_SPI_REG_BASE + 0x24,
.miso_dlen = ESP32xx_SPI_REG_BASE + 0x28,
},
.efuse_base = 0x6001A000,
.chip_magic_value = {0xd7b73e80, 0},
.read_spi_config = spi_config_esp32xx,
.encryption_in_begin_flash_cmd = true,
},
// ESP32C6
{
.regs = {
.cmd = ESP32C6_SPI_REG_BASE + 0x00,
.usr = ESP32C6_SPI_REG_BASE + 0x18,
.usr1 = ESP32C6_SPI_REG_BASE + 0x1c,
.usr2 = ESP32C6_SPI_REG_BASE + 0x20,
.w0 = ESP32C6_SPI_REG_BASE + 0x58,
.mosi_dlen = ESP32C6_SPI_REG_BASE + 0x24,
.miso_dlen = ESP32C6_SPI_REG_BASE + 0x28,
},
.efuse_base = 0x600B0800,
.chip_magic_value = { 0x2CE0806F, 0 },
.read_spi_config = spi_config_esp32xx,
.encryption_in_begin_flash_cmd = true,
},
};
const target_registers_t *get_esp_target_data(target_chip_t chip)
{
return (const target_registers_t *)&esp_target[chip];
}
esp_loader_error_t loader_detect_chip(target_chip_t *target_chip, const target_registers_t **target_data)
{
uint32_t magic_value;
RETURN_ON_ERROR( esp_loader_read_register(CHIP_DETECT_MAGIC_REG_ADDR, &magic_value) );
for (int chip = 0; chip < ESP_MAX_CHIP; chip++) {
for(int index = 0; index < MAX_MAGIC_VALUES; index++) {
if (magic_value == esp_target[chip].chip_magic_value[index]) {
*target_chip = (target_chip_t)chip;
*target_data = (target_registers_t *)&esp_target[chip];
return ESP_LOADER_SUCCESS;
}
}
}
return ESP_LOADER_ERROR_INVALID_TARGET;
}
esp_loader_error_t loader_read_spi_config(target_chip_t target_chip, uint32_t *spi_config)
{
const esp_target_t *target = &esp_target[target_chip];
return target->read_spi_config(target->efuse_base, spi_config);
}
static inline uint32_t efuse_word_addr(uint32_t efuse_base, uint32_t n)
{
return efuse_base + (n * 4);
}
// 30->GPIO32 | 31->GPIO33
static inline uint8_t adjust_pin_number(uint8_t num)
{
return (num >= 30) ? num + 2 : num;
}
static esp_loader_error_t spi_config_esp32(uint32_t efuse_base, uint32_t *spi_config)
{
*spi_config = 0;
uint32_t reg5, reg3;
RETURN_ON_ERROR( esp_loader_read_register(efuse_word_addr(efuse_base, 5), &reg5) );
RETURN_ON_ERROR( esp_loader_read_register(efuse_word_addr(efuse_base, 3), &reg3) );
uint32_t pins = reg5 & 0xfffff;
if (pins == 0 || pins == 0xfffff) {
return ESP_LOADER_SUCCESS;
}
uint8_t clk = adjust_pin_number( (pins >> 0) & 0x1f );
uint8_t q = adjust_pin_number( (pins >> 5) & 0x1f );
uint8_t d = adjust_pin_number( (pins >> 10) & 0x1f );
uint8_t cs = adjust_pin_number( (pins >> 15) & 0x1f );
uint8_t hd = adjust_pin_number( (reg3 >> 4) & 0x1f );
if (clk == cs || clk == d || clk == q || q == cs || q == d || q == d) {
return ESP_LOADER_SUCCESS;
}
*spi_config = (hd << 24) | (cs << 18) | (d << 12) | (q << 6) | clk;
return ESP_LOADER_SUCCESS;
}
// Applies for esp32s2, esp32c3 and esp32c3
static esp_loader_error_t spi_config_esp32xx(uint32_t efuse_base, uint32_t *spi_config)
{
*spi_config = 0;
// *** FIXME
// There seems to be a bug here.
// For ESP32-C6, esptool reads registers 0x600b0844 and 0x600b0848 (0x11 and 0x12).
// This tools reads registers 0x600b0848 and 0x600b084C (0x12 and 0x13).
// This function is supposted to read non-default SPI pins.
// As mostly they will be connected like default, it's pretty save to just exit.
return ESP_LOADER_SUCCESS;
// *** end FIXME
uint32_t reg1, reg2;
RETURN_ON_ERROR( esp_loader_read_register(efuse_word_addr(efuse_base, 18), &reg1) );
RETURN_ON_ERROR( esp_loader_read_register(efuse_word_addr(efuse_base, 19), &reg2) );
uint32_t pins = ((reg1 >> 16) | ((reg2 & 0xfffff) << 16)) & 0x3fffffff;
if (pins == 0 || pins == 0xffffffff) {
return ESP_LOADER_SUCCESS;
}
*spi_config = pins;
return ESP_LOADER_SUCCESS;
}
bool encryption_in_begin_flash_cmd(const target_chip_t target)
{
return esp_target[target].encryption_in_begin_flash_cmd;
}

View File

@@ -0,0 +1,262 @@
/*
* MD5 hash implementation and interface functions
* Copyright (c) 2003-2005, Jouni Malinen <j@w1.fi>
*
* This software may be distributed under the terms of the BSD license.
* See README for more details.
*/
#include "md5_hash.h"
#include <stdlib.h>
#include <string.h>
static void MD5Transform(uint32_t buf[4], uint32_t const in[16]);
/* ===== start - public domain MD5 implementation ===== */
/*
* This code implements the MD5 message-digest algorithm.
* The algorithm is due to Ron Rivest. This code was
* written by Colin Plumb in 1993, no copyright is claimed.
* This code is in the public domain; do with it what you wish.
*
* Equivalent code is available from RSA Data Security, Inc.
* This code has been tested against that, and is equivalent,
* except that you don't need to include two pages of legalese
* with every copy.
*
* To compute the message digest of a chunk of bytes, declare an
* MD5Context structure, pass it to MD5Init, call MD5Update as
* needed on buffers full of bytes, and then call MD5Final, which
* will fill a supplied 16-byte array with the digest.
*/
#ifndef WORDS_BIGENDIAN
#define byteReverse(buf, len) /* Nothing */
#else
/*
* Note: this code is harmless on little-endian machines.
*/
static void byteReverse(unsigned char *buf, unsigned longs)
{
uint32_t t;
do {
t = (uint32_t) ((unsigned) buf[3] << 8 | buf[2]) << 16 |
((unsigned) buf[1] << 8 | buf[0]);
*(uint32_t *) buf = t;
buf += 4;
} while (--longs);
}
#endif
/*
* Start MD5 accumulation. Set bit count to 0 and buffer to mysterious
* initialization constants.
*/
void MD5Init(struct MD5Context *ctx)
{
ctx->buf[0] = 0x67452301;
ctx->buf[1] = 0xefcdab89;
ctx->buf[2] = 0x98badcfe;
ctx->buf[3] = 0x10325476;
ctx->bits[0] = 0;
ctx->bits[1] = 0;
}
/*
* Update context to reflect the concatenation of another buffer full
* of bytes.
*/
void MD5Update(struct MD5Context *ctx, unsigned char const *buf, unsigned len)
{
uint32_t t;
/* Update bitcount */
t = ctx->bits[0];
if ((ctx->bits[0] = t + ((uint32_t) len << 3)) < t) {
ctx->bits[1]++; /* Carry from low to high */
}
ctx->bits[1] += len >> 29;
t = (t >> 3) & 0x3f; /* Bytes already in shsInfo->data */
/* Handle any leading odd-sized chunks */
if (t) {
unsigned char *p = (unsigned char *) ctx->in + t;
t = 64 - t;
if (len < t) {
memcpy(p, buf, len);
return;
}
memcpy(p, buf, t);
byteReverse(ctx->in, 16);
MD5Transform((uint32_t *)ctx->buf, (uint32_t *) ctx->in);
buf += t;
len -= t;
}
/* Process data in 64-byte chunks */
while (len >= 64) {
memcpy(ctx->in, buf, 64);
byteReverse(ctx->in, 16);
MD5Transform((uint32_t *)ctx->buf, (uint32_t *) ctx->in);
buf += 64;
len -= 64;
}
/* Handle any remaining bytes of data. */
memcpy(ctx->in, buf, len);
}
/*
* Final wrapup - pad to 64-byte boundary with the bit pattern
* 1 0* (64-bit count of bits processed, MSB-first)
*/
void MD5Final(unsigned char digest[16], struct MD5Context *ctx)
{
unsigned count;
unsigned char *p;
/* Compute number of bytes mod 64 */
count = (ctx->bits[0] >> 3) & 0x3F;
/* Set the first char of padding to 0x80. This is safe since there is
always at least one byte free */
p = ctx->in + count;
*p++ = 0x80;
/* Bytes of padding needed to make 64 bytes */
count = 64 - 1 - count;
/* Pad out to 56 mod 64 */
if (count < 8) {
/* Two lots of padding: Pad the first block to 64 bytes */
memset(p, 0, count);
byteReverse(ctx->in, 16);
MD5Transform((uint32_t *)ctx->buf, (uint32_t *) ctx->in);
/* Now fill the next block with 56 bytes */
memset(ctx->in, 0, 56);
} else {
/* Pad block to 56 bytes */
memset(p, 0, count - 8);
}
byteReverse(ctx->in, 14);
/* Append length in bits and transform */
((uint32_t *) ctx->in)[14] = ctx->bits[0];
((uint32_t *) ctx->in)[15] = ctx->bits[1];
MD5Transform((uint32_t *)ctx->buf, (uint32_t *) ctx->in);
byteReverse((unsigned char *) ctx->buf, 4);
memcpy(digest, ctx->buf, 16);
memset(ctx, 0, sizeof(struct MD5Context)); /* In case it's sensitive */
}
/* The four core functions - F1 is optimized somewhat */
/* #define F1(x, y, z) (x & y | ~x & z) */
#define F1(x, y, z) (z ^ (x & (y ^ z)))
#define F2(x, y, z) F1(z, x, y)
#define F3(x, y, z) (x ^ y ^ z)
#define F4(x, y, z) (y ^ (x | ~z))
/* This is the central step in the MD5 algorithm. */
#define MD5STEP(f, w, x, y, z, data, s) \
( w += f(x, y, z) + data, w = w<<s | w>>(32-s), w += x )
/*
* The core of the MD5 algorithm, this alters an existing MD5 hash to
* reflect the addition of 16 longwords of new data. MD5Update blocks
* the data and converts bytes into longwords for this routine.
*/
static void MD5Transform(uint32_t buf[4], uint32_t const in[16])
{
register uint32_t a, b, c, d;
a = buf[0];
b = buf[1];
c = buf[2];
d = buf[3];
MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7);
MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12);
MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17);
MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22);
MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7);
MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12);
MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17);
MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22);
MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7);
MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12);
MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17);
MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22);
MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7);
MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12);
MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17);
MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22);
MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5);
MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9);
MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14);
MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20);
MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5);
MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9);
MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14);
MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20);
MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5);
MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9);
MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14);
MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20);
MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5);
MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9);
MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14);
MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20);
MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4);
MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11);
MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16);
MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23);
MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4);
MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11);
MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16);
MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23);
MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4);
MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11);
MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16);
MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23);
MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4);
MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11);
MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16);
MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23);
MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6);
MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10);
MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15);
MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21);
MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6);
MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10);
MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15);
MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21);
MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6);
MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10);
MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15);
MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21);
MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6);
MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10);
MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15);
MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21);
buf[0] += a;
buf[1] += b;
buf[2] += c;
buf[3] += d;
}
/* ===== end - public domain MD5 implementation ===== */

View File

@@ -0,0 +1,301 @@
/* Copyright 2020-2023 Espressif Systems (Shanghai) CO LTD
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "protocol.h"
#include "protocol_prv.h"
#include "esp_loader_io.h"
#include <stddef.h>
#include <string.h>
#define CMD_SIZE(cmd) ( sizeof(cmd) - sizeof(command_common_t) )
static uint32_t s_sequence_number = 0;
static uint8_t compute_checksum(const uint8_t *data, uint32_t size)
{
uint8_t checksum = 0xEF;
while (size--) {
checksum ^= *data++;
}
return checksum;
}
void log_loader_internal_error(error_code_t error)
{
loader_port_debug_print("Error: ");
switch (error) {
case INVALID_CRC: loader_port_debug_print("INVALID_CRC"); break;
case INVALID_COMMAND: loader_port_debug_print("INVALID_COMMAND"); break;
case COMMAND_FAILED: loader_port_debug_print("COMMAND_FAILED"); break;
case FLASH_WRITE_ERR: loader_port_debug_print("FLASH_WRITE_ERR"); break;
case FLASH_READ_ERR: loader_port_debug_print("FLASH_READ_ERR"); break;
case READ_LENGTH_ERR: loader_port_debug_print("READ_LENGTH_ERR"); break;
case DEFLATE_ERROR: loader_port_debug_print("DEFLATE_ERROR"); break;
default: loader_port_debug_print("UNKNOWN ERROR"); break;
}
loader_port_debug_print("\n");
}
esp_loader_error_t loader_flash_begin_cmd(uint32_t offset,
uint32_t erase_size,
uint32_t block_size,
uint32_t blocks_to_write,
bool encryption)
{
flash_begin_command_t flash_begin_cmd = {
.common = {
.direction = WRITE_DIRECTION,
.command = FLASH_BEGIN,
.size = CMD_SIZE(flash_begin_cmd) - (encryption ? 0 : sizeof(uint32_t)),
.checksum = 0
},
.erase_size = erase_size,
.packet_count = blocks_to_write,
.packet_size = block_size,
.offset = offset,
.encrypted = 0
};
s_sequence_number = 0;
return send_cmd(&flash_begin_cmd,
sizeof(flash_begin_cmd) - (encryption ? 0 : sizeof(uint32_t)),
NULL);
}
esp_loader_error_t loader_flash_data_cmd(const uint8_t *data, uint32_t size)
{
data_command_t data_cmd = {
.common = {
.direction = WRITE_DIRECTION,
.command = FLASH_DATA,
.size = CMD_SIZE(data_cmd) + size,
.checksum = compute_checksum(data, size)
},
.data_size = size,
.sequence_number = s_sequence_number++,
};
return send_cmd_with_data(&data_cmd, sizeof(data_cmd), data, size);
}
esp_loader_error_t loader_flash_end_cmd(bool stay_in_loader)
{
flash_end_command_t end_cmd = {
.common = {
.direction = WRITE_DIRECTION,
.command = FLASH_END,
.size = CMD_SIZE(end_cmd),
.checksum = 0
},
.stay_in_loader = stay_in_loader
};
return send_cmd(&end_cmd, sizeof(end_cmd), NULL);
}
esp_loader_error_t loader_mem_begin_cmd(uint32_t offset, uint32_t size, uint32_t blocks_to_write, uint32_t block_size)
{
mem_begin_command_t mem_begin_cmd = {
.common = {
.direction = WRITE_DIRECTION,
.command = MEM_BEGIN,
.size = CMD_SIZE(mem_begin_cmd),
.checksum = 0
},
.total_size = size,
.blocks = blocks_to_write,
.block_size = block_size,
.offset = offset
};
s_sequence_number = 0;
return send_cmd(&mem_begin_cmd, sizeof(mem_begin_cmd), NULL);
}
esp_loader_error_t loader_mem_data_cmd(const uint8_t *data, uint32_t size)
{
data_command_t data_cmd = {
.common = {
.direction = WRITE_DIRECTION,
.command = MEM_DATA,
.size = CMD_SIZE(data_cmd) + size,
.checksum = compute_checksum(data, size)
},
.data_size = size,
.sequence_number = s_sequence_number++,
};
return send_cmd_with_data(&data_cmd, sizeof(data_cmd), data, size);
}
esp_loader_error_t loader_mem_end_cmd(uint32_t entrypoint)
{
mem_end_command_t end_cmd = {
.common = {
.direction = WRITE_DIRECTION,
.command = MEM_END,
.size = CMD_SIZE(end_cmd),
},
.stay_in_loader = (entrypoint == 0),
.entry_point_address = entrypoint
};
return send_cmd(&end_cmd, sizeof(end_cmd), NULL);
}
esp_loader_error_t loader_sync_cmd(void)
{
sync_command_t sync_cmd = {
.common = {
.direction = WRITE_DIRECTION,
.command = SYNC,
.size = CMD_SIZE(sync_cmd),
.checksum = 0
},
.sync_sequence = {
0x07, 0x07, 0x12, 0x20,
0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55,
0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55,
0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55,
0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55,
}
};
return send_cmd(&sync_cmd, sizeof(sync_cmd), NULL);
}
esp_loader_error_t loader_write_reg_cmd(uint32_t address, uint32_t value,
uint32_t mask, uint32_t delay_us)
{
write_reg_command_t write_cmd = {
.common = {
.direction = WRITE_DIRECTION,
.command = WRITE_REG,
.size = CMD_SIZE(write_cmd),
.checksum = 0
},
.address = address,
.value = value,
.mask = mask,
.delay_us = delay_us
};
return send_cmd(&write_cmd, sizeof(write_cmd), NULL);
}
esp_loader_error_t loader_read_reg_cmd(uint32_t address, uint32_t *reg)
{
read_reg_command_t read_cmd = {
.common = {
.direction = WRITE_DIRECTION,
.command = READ_REG,
.size = CMD_SIZE(read_cmd),
.checksum = 0
},
.address = address,
};
return send_cmd(&read_cmd, sizeof(read_cmd), reg);
}
esp_loader_error_t loader_spi_attach_cmd(uint32_t config)
{
spi_attach_command_t attach_cmd = {
.common = {
.direction = WRITE_DIRECTION,
.command = SPI_ATTACH,
.size = CMD_SIZE(attach_cmd),
.checksum = 0
},
.configuration = config,
.zero = 0
};
return send_cmd(&attach_cmd, sizeof(attach_cmd), NULL);
}
esp_loader_error_t loader_change_baudrate_cmd(uint32_t baudrate)
{
change_baudrate_command_t baudrate_cmd = {
.common = {
.direction = WRITE_DIRECTION,
.command = CHANGE_BAUDRATE,
.size = CMD_SIZE(baudrate_cmd),
.checksum = 0
},
.new_baudrate = baudrate,
.old_baudrate = 0 // ESP32 ROM only
};
return send_cmd(&baudrate_cmd, sizeof(baudrate_cmd), NULL);
}
esp_loader_error_t loader_md5_cmd(uint32_t address, uint32_t size, uint8_t *md5_out)
{
spi_flash_md5_command_t md5_cmd = {
.common = {
.direction = WRITE_DIRECTION,
.command = SPI_FLASH_MD5,
.size = CMD_SIZE(md5_cmd),
.checksum = 0
},
.address = address,
.size = size,
.reserved_0 = 0,
.reserved_1 = 0
};
return send_cmd_md5(&md5_cmd, sizeof(md5_cmd), md5_out);
}
esp_loader_error_t loader_spi_parameters(uint32_t total_size)
{
write_spi_command_t spi_cmd = {
.common = {
.direction = WRITE_DIRECTION,
.command = SPI_SET_PARAMS,
.size = 24,
.checksum = 0
},
.id = 0,
.total_size = total_size,
.block_size = 64 * 1024,
.sector_size = 4 * 1024,
.page_size = 0x100,
.status_mask = 0xFFFF,
};
return send_cmd(&spi_cmd, sizeof(spi_cmd), NULL);
}
__attribute__ ((weak)) void loader_port_debug_print(const char *str)
{
}

View File

@@ -0,0 +1,116 @@
#include <Arduino.h>
/* Copyright 2020-2023 Espressif Systems (Shanghai) CO LTD
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "protocol.h"
#include "protocol_prv.h"
#include "esp_loader_io.h"
#include "slip.h"
#include <stddef.h>
#include <string.h>
static esp_loader_error_t check_response(command_t cmd, uint32_t *reg_value, void* resp, uint32_t resp_size);
esp_loader_error_t loader_initialize_conn(esp_loader_connect_args_t *connect_args) {
esp_loader_error_t err;
int32_t trials = connect_args->trials;
do {
loader_port_start_timer(connect_args->sync_timeout);
err = loader_sync_cmd();
if (err == ESP_LOADER_ERROR_TIMEOUT) {
if (--trials == 0) {
return ESP_LOADER_ERROR_TIMEOUT;
}
loader_port_delay_ms(100);
} else if (err != ESP_LOADER_SUCCESS) {
return err;
}
} while (err != ESP_LOADER_SUCCESS);
return err;
}
esp_loader_error_t send_cmd(const void *cmd_data, uint32_t size, uint32_t *reg_value)
{
response_t response;
command_t command = ((const command_common_t *)cmd_data)->command;
RETURN_ON_ERROR( SLIP_send_delimiter() );
RETURN_ON_ERROR( SLIP_send((const uint8_t *)cmd_data, size) );
RETURN_ON_ERROR( SLIP_send_delimiter() );
return check_response(command, reg_value, &response, sizeof(response));
}
esp_loader_error_t send_cmd_with_data(const void *cmd_data, size_t cmd_size,
const void *data, size_t data_size)
{
response_t response;
command_t command = ((const command_common_t *)cmd_data)->command;
RETURN_ON_ERROR( SLIP_send_delimiter() );
RETURN_ON_ERROR( SLIP_send((const uint8_t *)cmd_data, cmd_size) );
RETURN_ON_ERROR( SLIP_send(data, data_size) );
RETURN_ON_ERROR( SLIP_send_delimiter() );
return check_response(command, NULL, &response, sizeof(response));
}
esp_loader_error_t send_cmd_md5(const void *cmd_data, size_t cmd_size, uint8_t md5_out[MD5_SIZE])
{
rom_md5_response_t response;
command_t command = ((const command_common_t *)cmd_data)->command;
RETURN_ON_ERROR( SLIP_send_delimiter() );
RETURN_ON_ERROR( SLIP_send((const uint8_t *)cmd_data, cmd_size) );
RETURN_ON_ERROR( SLIP_send_delimiter() );
RETURN_ON_ERROR( check_response(command, NULL, &response, sizeof(response)) );
memcpy(md5_out, response.md5, MD5_SIZE);
return ESP_LOADER_SUCCESS;
}
static esp_loader_error_t check_response(command_t cmd, uint32_t *reg_value, void* resp, uint32_t resp_size)
{
esp_loader_error_t err;
common_response_t *response = (common_response_t *)resp;
do {
err = SLIP_receive_packet(resp, resp_size);
if (err != ESP_LOADER_SUCCESS) {
return err;
}
} while ((response->direction != READ_DIRECTION) || (response->command != cmd));
response_status_t *status = (response_status_t *)((uint8_t *)resp + resp_size - sizeof(response_status_t));
if (status->failed) {
log_loader_internal_error(status->error);
return ESP_LOADER_ERROR_INVALID_RESPONSE;
}
if (reg_value != NULL) {
*reg_value = response->value;
}
return ESP_LOADER_SUCCESS;
}

View File

@@ -0,0 +1,125 @@
/* Copyright 2020-2023 Espressif Systems (Shanghai) CO LTD
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "slip.h"
#include "esp_loader_io.h"
static const uint8_t DELIMITER = 0xC0;
static const uint8_t C0_REPLACEMENT[2] = {0xDB, 0xDC};
static const uint8_t DB_REPLACEMENT[2] = {0xDB, 0xDD};
static inline esp_loader_error_t peripheral_read(uint8_t *buff, const size_t size)
{
return loader_port_read(buff, size, loader_port_remaining_time());
}
static inline esp_loader_error_t peripheral_write(const uint8_t *buff, const size_t size)
{
return loader_port_write(buff, size, loader_port_remaining_time());
}
esp_loader_error_t SLIP_receive_data(uint8_t *buff, const size_t size)
{
uint8_t ch;
for (uint32_t i = 0; i < size; i++) {
RETURN_ON_ERROR( peripheral_read(&ch, 1) );
if (ch == 0xDB) {
RETURN_ON_ERROR( peripheral_read(&ch, 1) );
if (ch == 0xDC) {
buff[i] = 0xC0;
} else if (ch == 0xDD) {
buff[i] = 0xDB;
} else {
return ESP_LOADER_ERROR_INVALID_RESPONSE;
}
} else {
buff[i] = ch;
}
}
return ESP_LOADER_SUCCESS;
}
esp_loader_error_t SLIP_receive_packet(uint8_t *buff, const size_t size)
{
uint8_t ch;
// Wait for delimiter
do {
RETURN_ON_ERROR( peripheral_read(&ch, 1) );
} while (ch != DELIMITER);
// Workaround: bootloader sends two dummy(0xC0) bytes after response when baud rate is changed.
do {
RETURN_ON_ERROR( peripheral_read(&ch, 1) );
} while (ch == DELIMITER);
buff[0] = ch;
RETURN_ON_ERROR( SLIP_receive_data(&buff[1], size - 1) );
// Wait for delimiter
do {
RETURN_ON_ERROR( peripheral_read(&ch, 1) );
} while (ch != DELIMITER);
return ESP_LOADER_SUCCESS;
}
esp_loader_error_t SLIP_send(const uint8_t *data, const size_t size)
{
uint32_t to_write = 0; // Bytes ready to write as they are
uint32_t written = 0; // Bytes already written
for (uint32_t i = 0; i < size; i++) {
if (data[i] != 0xC0 && data[i] != 0xDB) {
to_write++; // Queue this byte for writing
continue;
}
// We have a byte that needs encoding, write the queue first
if (to_write > 0) {
RETURN_ON_ERROR( peripheral_write(&data[written], to_write) );
}
// Write the encoded byte
if (data[i] == 0xC0) {
RETURN_ON_ERROR( peripheral_write(C0_REPLACEMENT, 2) );
} else {
RETURN_ON_ERROR( peripheral_write(DB_REPLACEMENT, 2) );
}
// Update to start again after the encoded byte
written = i + 1;
to_write = 0;
}
// Write the rest of the bytes that didn't need encoding
if (to_write > 0) {
RETURN_ON_ERROR( peripheral_write(&data[written], to_write) );
}
return ESP_LOADER_SUCCESS;
}
esp_loader_error_t SLIP_send_delimiter(void)
{
return peripheral_write(&DELIMITER, 1);
}

View File

@@ -64,7 +64,7 @@ build_flags =
-D FLASHER_LED=15
-D FLASHER_RGB_LED=33
build_src_filter =
+<*>-<usbflasher.cpp>-<swd.cpp>
+<*>-<usbflasher.cpp>-<swd.cpp>-<espflasher.cpp>
board_build.psram_type=qspi_opi
board_upload.maximum_size = 4194304
board_upload.maximum_ram_size = 327680
@@ -99,7 +99,7 @@ build_flags =
-D FLASHER_LED=15
-D FLASHER_RGB_LED=-1
build_src_filter =
+<*>-<usbflasher.cpp>-<swd.cpp>
+<*>-<usbflasher.cpp>-<swd.cpp>-<espflasher.cpp>
board_build.psram_type=qspi_opi
board_upload.maximum_size = 4194304
board_upload.maximum_ram_size = 327680
@@ -157,6 +157,8 @@ build_flags =
-D FLASHER_ALT_TEST=13
-D FLASHER_LED=21
-D FLASHER_RGB_LED=48
build_src_filter =
+<*>-<espflasher.cpp>
board_build.flash_mode=qio
board_build.arduino.memory_type = qio_opi
board_build.psram_type=qspi_opi
@@ -186,7 +188,7 @@ build_flags =
-D FLASHER_AP_RXD=16
-D FLASHER_LED=22
build_src_filter =
+<*>-<usbflasher.cpp>-<swd.cpp>
+<*>-<usbflasher.cpp>-<swd.cpp>-<espflasher.cpp>
; ----------------------------------------------------------------------------------------
; !!! this configuration expects an wemos_d1_mini32
@@ -212,7 +214,7 @@ build_flags =
-D FLASHER_AP_RXD=17
-D FLASHER_LED=22
build_src_filter =
+<*>-<usbflasher.cpp>-<swd.cpp>
+<*>-<usbflasher.cpp>-<swd.cpp>-<espflasher.cpp>
; ----------------------------------------------------------------------------------------
; !!! this configuration expects an m5stack esp32
@@ -249,7 +251,7 @@ build_flags =
-D ILI9341_DRIVER
-D SMOOTH_FONT
build_src_filter =
+<*>-<usbflasher.cpp>-<swd.cpp>
+<*>-<usbflasher.cpp>-<swd.cpp>-<espflasher.cpp>
; ----------------------------------------------------------------------------------------
; !!! this configuration expects an ESP32-S3 16MB Flash 8MB RAM
;
@@ -258,9 +260,11 @@ build_src_filter =
board = esp32-s3-devkitc-1
board_build.partitions = large_spiffs_16MB.csv
build_unflags =
-D ARDUINO_USB_MODE=1
-D CONFIG_MBEDTLS_INTERNAL_MEM_ALLOC=y
-D ILI9341_DRIVER
-D ARDUINO_USB_MODE=1
-D CONFIG_MBEDTLS_INTERNAL_MEM_ALLOC=y
-D ILI9341_DRIVER
lib_deps =
${env.lib_deps}
build_flags =
${env.build_flags}
-D YELLOW_IPS_AP
@@ -282,6 +286,7 @@ build_flags =
-D FLASHER_AP_RXD=18
-D FLASHER_DEBUG_TXD=19
-D FLASHER_DEBUG_RXD=20
-D FLASHER_DEBUG_PROG=21
-D FLASHER_LED=16
-D HAS_RGB_LED
-D FLASHER_RGB_LED=48
@@ -297,6 +302,10 @@ build_flags =
-D TFT_RGB_ORDER=TFT_BGR
-D USE_HSPI_PORT
-D LOAD_FONT2
-D MD5_ENABLED=1
-D SERIAL_FLASHER_INTERFACE_UART=1
-D SERIAL_FLASHER_BOOT_HOLD_TIME_MS=50
-D SERIAL_FLASHER_RESET_HOLD_TIME_MS=100
build_src_filter =
+<*>-<usbflasher.cpp>-<swd.cpp>
board_build.flash_mode=qio
@@ -331,7 +340,7 @@ build_flags =
-D FLASHER_AP_RXD=23
-D FLASHER_LED=2
build_src_filter =
+<*>-<usbflasher.cpp>-<swd.cpp>
+<*>-<usbflasher.cpp>-<swd.cpp>-<espflasher.cpp>
board_build.psram_type=qspi_opi
board_upload.maximum_size = 4194304
board_upload.maximum_ram_size = 327680
@@ -366,7 +375,7 @@ build_flags =
-D FLASHER_LED=2
-D FLASHER_RGB_LED=-1
build_src_filter =
+<*>-<usbflasher.cpp>-<swd.cpp>
+<*>-<usbflasher.cpp>-<swd.cpp>-<espflasher.cpp>
board_build.psram_type=qspi_opi
board_upload.maximum_size = 4194304
board_upload.maximum_ram_size = 327680
@@ -405,7 +414,7 @@ build_flags =
-D FLASHER_LED=21
-D FLASHER_RGB_LED=38
build_src_filter =
+<*>-<usbflasher.cpp>-<swd.cpp>
+<*>-<usbflasher.cpp>-<swd.cpp>-<espflasher.cpp>
board_build.flash_mode=opi
board_build.arduino.memory_type = opi_opi
board_build.psram_type=qspi_opi

View File

@@ -192,6 +192,19 @@ void drawNew(const uint8_t mac[8], const bool buttonPressed, tagRecord *&taginfo
imageParams.symbols = 0;
imageParams.rotate = taginfo->rotate;
imageParams.shortlut = hwdata.shortlut;
imageParams.lut = EPD_LUT_NO_REPEATS;
time_t last_midnight = now - now % (24 * 60 * 60) + 3 * 3600; // somewhere in the middle of the night
if (imageParams.shortlut == SHORTLUT_DISABLED || taginfo->lastfullupdate < last_midnight || taginfo->lut == 1) {
imageParams.lut = EPD_LUT_DEFAULT;
taginfo->lastfullupdate = now;
}
if (taginfo->hasCustomLUT && taginfo->capabilities & CAPABILITY_SUPPORTS_CUSTOM_LUTS && taginfo->lut != 1) {
Serial.println("using custom LUT");
imageParams.lut = EPD_LUT_OTA;
}
switch (taginfo->contentMode) {
case 0: // Image
{
@@ -206,7 +219,7 @@ void drawNew(const uint8_t mac[8], const bool buttonPressed, tagRecord *&taginfo
} else {
filename = "/current/" + String(hexmac) + ".raw";
if (contentFS->exists(filename)) {
prepareDataAvail(filename, imageParams.dataType, mac, cfgobj["timetolive"].as<int>(), true);
prepareDataAvail(filename, imageParams.dataType, imageParams.lut, mac, cfgobj["timetolive"].as<int>(), true);
wsLog("File " + configFilename + " not found, resending image " + filename);
} else {
wsErr("File " + configFilename + " not found");
@@ -216,8 +229,9 @@ void drawNew(const uint8_t mac[8], const bool buttonPressed, tagRecord *&taginfo
}
if (imageParams.hasRed) {
imageParams.dataType = DATATYPE_IMG_RAW_2BPP;
if (imageParams.lut = EPD_LUT_NO_REPEATS && imageParams.shortlut == SHORTLUT_ONLY_BLACK) imageParams.lut = EPD_LUT_DEFAULT;
}
if (prepareDataAvail(filename, imageParams.dataType, mac, cfgobj["timetolive"].as<int>())) {
if (prepareDataAvail(filename, imageParams.dataType, imageParams.lut, mac, cfgobj["timetolive"].as<int>())) {
if (cfgobj["delete"].as<String>() == "1") {
contentFS->remove("/" + configFilename);
}
@@ -266,7 +280,7 @@ void drawNew(const uint8_t mac[8], const bool buttonPressed, tagRecord *&taginfo
filename = cfgobj["filename"].as<String>();
if (!util::isEmptyOrNull(filename) && !cfgobj["#fetched"].as<bool>()) {
if (prepareDataAvail(filename, DATATYPE_FW_UPDATE, mac, cfgobj["timetolive"].as<int>())) {
if (prepareDataAvail(filename, DATATYPE_FW_UPDATE, 0, mac, cfgobj["timetolive"].as<int>())) {
cfgobj["#fetched"] = true;
} else {
wsErr("Error accessing " + filename);
@@ -435,8 +449,11 @@ bool updateTagImage(String &filename, const uint8_t *dst, uint16_t nextCheckin,
if (taginfo->hwType == SOLUM_SEG_UK) {
sendAPSegmentedData(dst, (String)imageParams.segments, imageParams.symbols, imageParams.invert, (taginfo->isExternal == false));
} else {
if (imageParams.hasRed) imageParams.dataType = DATATYPE_IMG_RAW_2BPP;
prepareDataAvail(filename, imageParams.dataType, dst, nextCheckin);
if (imageParams.hasRed) {
imageParams.dataType = DATATYPE_IMG_RAW_2BPP;
if (imageParams.lut = EPD_LUT_NO_REPEATS && imageParams.shortlut == SHORTLUT_ONLY_BLACK) imageParams.lut = EPD_LUT_DEFAULT;
}
prepareDataAvail(filename, imageParams.dataType, imageParams.lut, dst, nextCheckin);
}
return true;
}

View File

@@ -0,0 +1,185 @@
#include <Arduino.h>
#include <esp_loader.h>
#include "esp32_port.h"
#include "esp_littlefs.h"
#include "storage.h"
#include "web.h"
esp_loader_error_t connect_to_target(uint32_t higher_transmission_rate) {
esp_loader_connect_args_t connect_config = ESP_LOADER_CONNECT_DEFAULT();
esp_loader_error_t err = esp_loader_connect(&connect_config);
if (err != ESP_LOADER_SUCCESS) {
printf("Cannot connect to target. Error: %u\n", err);
return err;
}
printf("Connected to target\n");
if (higher_transmission_rate && esp_loader_get_target() != ESP8266_CHIP) {
err = esp_loader_change_transmission_rate(higher_transmission_rate);
if (err == ESP_LOADER_ERROR_UNSUPPORTED_FUNC) {
printf("ESP8266 does not support change transmission rate command.");
return err;
} else if (err != ESP_LOADER_SUCCESS) {
printf("Unable to change transmission rate on target.");
return err;
} else {
err = loader_port_change_transmission_rate(higher_transmission_rate);
if (err != ESP_LOADER_SUCCESS) {
printf("Unable to change transmission rate.");
return err;
}
printf("Transmission rate changed\n");
}
}
return ESP_LOADER_SUCCESS;
}
#define MAX(a, b) ((a) > (b) ? (a) : (b))
#define MIN(a, b) ((a) < (b) ? (a) : (b))
esp_loader_error_t flash_binary(const char *file_path, size_t address) {
esp_loader_error_t err;
wsSerial("Flashing " + String(file_path));
File file = contentFS->open(file_path, "rb");
if (!file) {
wsSerial("Failed to open file");
return ESP_LOADER_ERROR_FAIL;
}
size_t size = file.size();
static uint8_t payload[1024];
Serial.println("file size: " + String(size));
printf("Erasing flash (this may take a while)...\n");
err = esp_loader_flash_start(address, size, sizeof(payload));
if (err != ESP_LOADER_SUCCESS) {
wsSerial("Erasing flash failed");
file.close();
return err;
}
printf("Start programming\n");
size_t written = 0;
size_t sizeleft = size;
uint32_t t = millis();
while (sizeleft > 0) {
size_t to_read = MIN(sizeleft, sizeof(payload));
size_t bytes_read = file.readBytes(reinterpret_cast<char *>(payload), to_read);
if (bytes_read != to_read) {
wsSerial("Failed to read file.");
file.close();
return ESP_LOADER_ERROR_FAIL;
}
err = esp_loader_flash_write(payload, to_read);
if (err != ESP_LOADER_SUCCESS) {
wsSerial("Packet could not be written!");
file.close();
return err;
}
sizeleft -= to_read;
written += to_read;
if (millis() - t > 250) {
uint32_t progress = written * 100 / size;
// printf("\rProgress: %d%%", progress);
wsSerial("Progress: " + String(progress) + "%");
fflush(stdout);
t = millis();
}
};
wsSerial("Progress: 100%");
file.close();
printf("\nFinished programming\n");
#if MD5_ENABLED
err = esp_loader_flash_verify();
if (err == ESP_LOADER_ERROR_UNSUPPORTED_FUNC) {
printf("ESP8266 does not support flash verify command.");
return err;
} else if (err != ESP_LOADER_SUCCESS) {
wsSerial("MD5 does not match.");
return err;
}
wsSerial("Flash verified");
#endif
vTaskDelay(1000 / portTICK_PERIOD_MS);
return ESP_LOADER_SUCCESS;
}
bool doC6flash() {
const loader_esp32_config_t config = {
.baud_rate = 115200,
.uart_port = 2,
.uart_rx_pin = FLASHER_DEBUG_TXD,
.uart_tx_pin = FLASHER_DEBUG_RXD,
.reset_trigger_pin = FLASHER_AP_RESET,
.gpio0_trigger_pin = FLASHER_DEBUG_PROG,
};
if (loader_port_esp32_init(&config) != ESP_LOADER_SUCCESS) {
wsSerial("Serial initialization failed");
loader_port_esp32_deinit();
return false;
}
if (connect_to_target(230400) == ESP_LOADER_SUCCESS) {
if (esp_loader_get_target() == ESP32C6_CHIP) {
wsSerial("Connected to ESP32-C6");
int maxRetries = 5;
esp_loader_error_t err;
for (int retry = 0; retry < maxRetries; retry++) {
err = flash_binary("/bootloader.bin", 0x0);
if (err == ESP_LOADER_SUCCESS) break;
Serial.printf("Flash failed with error %d. Retrying...\n", err);
delay(1000);
}
if (err != ESP_LOADER_SUCCESS) {
loader_port_esp32_deinit();
return false;
}
for (int retry = 0; retry < maxRetries; retry++) {
err = flash_binary("/partition-table.bin", 0x8000);
if (err == ESP_LOADER_SUCCESS) break;
Serial.printf("Flash failed with error %d. Retrying...\n", err);
delay(1000);
}
if (err != ESP_LOADER_SUCCESS) {
loader_port_esp32_deinit();
return false;
}
for (int retry = 0; retry < maxRetries; retry++) {
err = flash_binary("/OpenEPaperLink_esp32_C6.bin", 0x10000);
if (err == ESP_LOADER_SUCCESS) break;
Serial.printf("Flash failed with error %d. Retrying...\n", err);
delay(1000);
}
if (err != ESP_LOADER_SUCCESS) {
loader_port_esp32_deinit();
return false;
}
Serial.println("Done!");
} else {
wsSerial("Connected to wrong ESP32 type");
loader_port_esp32_deinit();
return false;
}
} else {
wsSerial("Connection failed");
loader_port_esp32_deinit();
return false;
}
loader_port_esp32_deinit();
return true;
}

View File

@@ -145,6 +145,7 @@ void setup() {
rgbIdle();
#endif
loadDB("/current/tagDB.json");
cleanupCurrent();
// tagDBOwner = xSemaphoreCreateMutex();
xTaskCreate(APTask, "AP Process", 6000, NULL, 2, NULL);
xTaskCreate(networkProcess, "Wifi", 6000, NULL, configMAX_PRIORITIES - 10, NULL);

View File

@@ -113,7 +113,7 @@ void prepareDataAvail(uint8_t* data, uint16_t len, uint8_t dataType, const uint8
wsSendTaginfo(dst, SYNC_TAGSTATUS);
}
bool prepareDataAvail(String& filename, uint8_t dataType, const uint8_t* dst, uint16_t nextCheckin, bool resend) {
bool prepareDataAvail(String& filename, uint8_t dataType, uint8_t dataTypeArgument, const uint8_t* dst, uint16_t nextCheckin, bool resend) {
if (nextCheckin > config.maxsleep) nextCheckin = config.maxsleep;
if (wsClientCount() && config.stopsleep == 1) nextCheckin = 0;
#ifdef YELLOW_IPS_AP
@@ -158,7 +158,6 @@ bool prepareDataAvail(String& filename, uint8_t dataType, const uint8_t* dst, ui
file.close();
uint16_t attempts = 60 * 24;
uint8_t lut = EPD_LUT_NO_REPEATS;
if (memcmp(md5bytes, taginfo->md5pending, 16) == 0) {
wsLog("new image is the same as current or already pending image. not updating tag.");
@@ -169,18 +168,6 @@ bool prepareDataAvail(String& filename, uint8_t dataType, const uint8_t* dst, ui
return true;
}
time_t now;
time(&now);
time_t last_midnight = now - now % (24 * 60 * 60) + 3 * 3600; // somewhere in the middle of the night
if (taginfo->lastfullupdate < last_midnight || taginfo->hwType == SOLUM_29_UC8151 || taginfo->lut == 1) {
lut = EPD_LUT_DEFAULT; // full update once a day
taginfo->lastfullupdate = now;
}
if (taginfo->hasCustomLUT && taginfo->capabilities & CAPABILITY_SUPPORTS_CUSTOM_LUTS && taginfo->lut != 1) {
Serial.println("using custom LUT");
lut = EPD_LUT_OTA;
}
if (dataType != DATATYPE_FW_UPDATE) {
char dst_path[64];
sprintf(dst_path, "/current/%02X%02X%02X%02X%02X%02X%02X%02X.pending\0", dst[7], dst[6], dst[5], dst[4], dst[3], dst[2], dst[1], dst[0]);
@@ -195,7 +182,7 @@ bool prepareDataAvail(String& filename, uint8_t dataType, const uint8_t* dst, ui
time_t now;
time(&now);
taginfo->pendingIdle = now + nextCheckin * 60 + 60;
taginfo->pendingIdle = nextCheckin * 60 + 60;
clearPending(taginfo);
taginfo->filename = filename;
taginfo->len = filesize;
@@ -216,7 +203,7 @@ bool prepareDataAvail(String& filename, uint8_t dataType, const uint8_t* dst, ui
pending.availdatainfo.dataType = dataType;
pending.availdatainfo.dataVer = *((uint64_t*)md5bytes);
pending.availdatainfo.dataSize = filesize;
pending.availdatainfo.dataTypeArgument = lut;
pending.availdatainfo.dataTypeArgument = dataTypeArgument;
pending.availdatainfo.nextCheckIn = nextCheckin;
pending.attemptsLeft = attempts;
checkMirror(taginfo, &pending);
@@ -435,7 +422,7 @@ void processXferTimeout(struct espXferComplete* xfc, bool local) {
time(&now);
tagRecord* taginfo = tagRecord::findByMAC(xfc->src);
if (taginfo != nullptr) {
taginfo->pendingIdle = now + 60;
taginfo->pendingIdle = 60;
memset(taginfo->md5pending, 0, 16 * sizeof(uint8_t));
clearPending(taginfo);
}
@@ -542,22 +529,11 @@ void processTagReturnData(struct espTagReturnData* trd, uint8_t len, bool local)
uint8_t* actualPayload = (uint8_t*)calloc(actualPayloadLength, 1);
memcpy(actualPayload, trd->returnData.data, actualPayloadLength);
}
void refreshAllPending() {
for (int16_t c = 0; c < tagDB.size(); c++) {
tagRecord* taginfo = tagDB.at(c);
if (taginfo->pending) {
clearPending(taginfo);
taginfo->nextupdate = 0;
memset(taginfo->md5, 0, 16 * sizeof(uint8_t));
memset(taginfo->md5pending, 0, 16 * sizeof(uint8_t));
wsSendTaginfo(taginfo->mac, SYNC_TAGSTATUS);
}
}
};
void updateContent(const uint8_t* dst) {
tagRecord* taginfo = tagRecord::findByMAC(dst);
if (taginfo != nullptr) {
void refreshAllPending() {
for (int16_t c = 0; c < tagDB.size(); c++) {
tagRecord* taginfo = tagDB.at(c);
if (taginfo->pending) {
clearPending(taginfo);
taginfo->nextupdate = 0;
memset(taginfo->md5, 0, 16 * sizeof(uint8_t));
@@ -565,176 +541,188 @@ void processTagReturnData(struct espTagReturnData* trd, uint8_t len, bool local)
wsSendTaginfo(taginfo->mac, SYNC_TAGSTATUS);
}
}
};
void setAPchannel() {
if (config.channel == 0) {
// trigger channel autoselect
UDPcomm udpsync;
udpsync.getAPList();
} else {
if (curChannel.channel != config.channel) {
curChannel.channel = config.channel;
sendChannelPower(&curChannel);
}
void updateContent(const uint8_t* dst) {
tagRecord* taginfo = tagRecord::findByMAC(dst);
if (taginfo != nullptr) {
clearPending(taginfo);
taginfo->nextupdate = 0;
memset(taginfo->md5, 0, 16 * sizeof(uint8_t));
memset(taginfo->md5pending, 0, 16 * sizeof(uint8_t));
wsSendTaginfo(taginfo->mac, SYNC_TAGSTATUS);
}
}
void setAPchannel() {
if (config.channel == 0) {
// trigger channel autoselect
UDPcomm udpsync;
udpsync.getAPList();
} else {
if (curChannel.channel != config.channel) {
curChannel.channel = config.channel;
sendChannelPower(&curChannel);
}
}
}
bool sendAPSegmentedData(const uint8_t* dst, String data, uint16_t icons, bool inverted, bool local) {
struct pendingData pending = {0};
memcpy(pending.targetMac, dst, 8);
pending.availdatainfo.dataType = DATATYPE_UK_SEGMENTED;
pending.availdatainfo.dataSize = icons << 16;
memcpy((void*)&(pending.availdatainfo.dataVer), data.c_str(), 10);
pending.availdatainfo.dataTypeArgument = inverted;
pending.availdatainfo.nextCheckIn = 0;
pending.attemptsLeft = 120;
Serial.printf(">AP Segmented Data %02X%02X%02X%02X%02X%02X%02X%02X\n\0", dst[7], dst[6], dst[5], dst[4], dst[3], dst[2], dst[1], dst[0]);
if (local) {
return sendDataAvail(&pending);
} else {
udpsync.netSendDataAvail(&pending);
return true;
}
bool sendAPSegmentedData(const uint8_t* dst, String data, uint16_t icons, bool inverted, bool local) {
struct pendingData pending = {0};
memcpy(pending.targetMac, dst, 8);
pending.availdatainfo.dataType = DATATYPE_UK_SEGMENTED;
pending.availdatainfo.dataSize = icons << 16;
memcpy((void*)&(pending.availdatainfo.dataVer), data.c_str(), 10);
pending.availdatainfo.dataTypeArgument = inverted;
pending.availdatainfo.nextCheckIn = 0;
pending.attemptsLeft = 120;
Serial.printf(">AP Segmented Data %02X%02X%02X%02X%02X%02X%02X%02X\n\0", dst[7], dst[6], dst[5], dst[4], dst[3], dst[2], dst[1], dst[0]);
if (local) {
return sendDataAvail(&pending);
} else {
udpsync.netSendDataAvail(&pending);
return true;
}
}
bool showAPSegmentedInfo(const uint8_t* dst, bool local) {
struct pendingData pending = {0};
memcpy(pending.targetMac, dst, 8);
pending.availdatainfo.dataType = DATATYPE_UK_SEGMENTED;
pending.availdatainfo.dataSize = 0x00;
pending.availdatainfo.dataVer = 0x00;
pending.availdatainfo.dataTypeArgument = 0;
pending.availdatainfo.nextCheckIn = 0;
pending.attemptsLeft = 120;
Serial.printf(">SDA %02X%02X%02X%02X%02X%02X%02X%02X\n\0", dst[7], dst[6], dst[5], dst[4], dst[3], dst[2], dst[1], dst[0]);
if (local) {
return sendDataAvail(&pending);
} else {
udpsync.netSendDataAvail(&pending);
return true;
}
}
bool sendTagCommand(const uint8_t* dst, uint8_t cmd, bool local, const uint8_t* payload) {
struct pendingData pending = {0};
memcpy(pending.targetMac, dst, 8);
pending.availdatainfo.dataType = DATATYPE_COMMAND_DATA;
pending.availdatainfo.dataTypeArgument = cmd;
pending.availdatainfo.nextCheckIn = 0;
if (payload != nullptr) {
memcpy(&pending.availdatainfo.dataVer, payload, sizeof(uint64_t));
memcpy(&pending.availdatainfo.dataSize, payload + sizeof(uint64_t), sizeof(uint32_t));
}
pending.attemptsLeft = 120;
Serial.printf(">Tag CMD %02X%02X%02X%02X%02X%02X%02X%02X\n\0", dst[7], dst[6], dst[5], dst[4], dst[3], dst[2], dst[1], dst[0]);
if (local) {
return sendDataAvail(&pending);
} else {
udpsync.netSendDataAvail(&pending);
return true;
}
}
void updateTaginfoitem(struct TagInfo* taginfoitem, IPAddress remoteIP) {
tagRecord* taginfo = tagRecord::findByMAC(taginfoitem->mac);
if (taginfo == nullptr) {
taginfo = new tagRecord;
memcpy(taginfo->mac, taginfoitem->mac, sizeof(taginfo->mac));
taginfo->pending = false;
tagDB.push_back(taginfo);
}
tagRecord initialTagInfo = *taginfo;
switch (taginfoitem->syncMode) {
case SYNC_USERCFG:
taginfo->alias = String(taginfoitem->alias);
taginfo->nextupdate = taginfoitem->nextupdate;
break;
case SYNC_TAGSTATUS:
taginfo->lastseen = taginfoitem->lastseen;
taginfo->nextupdate = taginfoitem->nextupdate;
taginfo->pending = taginfoitem->pending;
taginfo->expectedNextCheckin = taginfoitem->expectedNextCheckin;
taginfo->hwType = taginfoitem->hwType;
taginfo->wakeupReason = taginfoitem->wakeupReason;
taginfo->capabilities = taginfoitem->capabilities;
taginfo->pendingIdle = taginfoitem->pendingIdle;
break;
}
bool showAPSegmentedInfo(const uint8_t* dst, bool local) {
struct pendingData pending = {0};
memcpy(pending.targetMac, dst, 8);
pending.availdatainfo.dataType = DATATYPE_UK_SEGMENTED;
pending.availdatainfo.dataSize = 0x00;
pending.availdatainfo.dataVer = 0x00;
pending.availdatainfo.dataTypeArgument = 0;
pending.availdatainfo.nextCheckIn = 0;
pending.attemptsLeft = 120;
Serial.printf(">SDA %02X%02X%02X%02X%02X%02X%02X%02X\n\0", dst[7], dst[6], dst[5], dst[4], dst[3], dst[2], dst[1], dst[0]);
if (local) {
return sendDataAvail(&pending);
} else {
udpsync.netSendDataAvail(&pending);
return true;
}
char hexmac[17];
mac2hex(taginfo->mac, hexmac);
if (taginfo->contentMode != 12 && taginfoitem->contentMode != 12) {
wsLog("Remote AP at " + remoteIP.toString() + " takes control over tag " + String(hexmac));
taginfo->contentMode = 12;
}
bool sendTagCommand(const uint8_t* dst, uint8_t cmd, bool local, const uint8_t* payload) {
struct pendingData pending = {0};
memcpy(pending.targetMac, dst, 8);
pending.availdatainfo.dataType = DATATYPE_COMMAND_DATA;
pending.availdatainfo.dataTypeArgument = cmd;
pending.availdatainfo.nextCheckIn = 0;
if (payload != nullptr) {
memcpy(&pending.availdatainfo.dataVer, payload, sizeof(uint64_t));
memcpy(&pending.availdatainfo.dataSize, payload + sizeof(uint64_t), sizeof(uint32_t));
}
pending.attemptsLeft = 120;
Serial.printf(">Tag CMD %02X%02X%02X%02X%02X%02X%02X%02X\n\0", dst[7], dst[6], dst[5], dst[4], dst[3], dst[2], dst[1], dst[0]);
if (local) {
return sendDataAvail(&pending);
} else {
udpsync.netSendDataAvail(&pending);
return true;
}
}
void updateTaginfoitem(struct TagInfo * taginfoitem, IPAddress remoteIP) {
tagRecord* taginfo = tagRecord::findByMAC(taginfoitem->mac);
if (taginfo == nullptr) {
taginfo = new tagRecord;
memcpy(taginfo->mac, taginfoitem->mac, sizeof(taginfo->mac));
taginfo->pending = false;
tagDB.push_back(taginfo);
}
tagRecord initialTagInfo = *taginfo;
switch (taginfoitem->syncMode) {
case SYNC_USERCFG:
taginfo->alias = String(taginfoitem->alias);
taginfo->nextupdate = taginfoitem->nextupdate;
break;
case SYNC_TAGSTATUS:
taginfo->lastseen = taginfoitem->lastseen;
taginfo->nextupdate = taginfoitem->nextupdate;
taginfo->pending = taginfoitem->pending;
taginfo->expectedNextCheckin = taginfoitem->expectedNextCheckin;
taginfo->hwType = taginfoitem->hwType;
taginfo->wakeupReason = taginfoitem->wakeupReason;
taginfo->capabilities = taginfoitem->capabilities;
taginfo->pendingIdle = taginfoitem->pendingIdle;
break;
}
char hexmac[17];
mac2hex(taginfo->mac, hexmac);
if (taginfo->contentMode != 12 && taginfoitem->contentMode != 12) {
wsLog("Remote AP at " + remoteIP.toString() + " takes control over tag " + String(hexmac));
taginfo->contentMode = 12;
}
if (taginfoitem->syncMode == SYNC_DELETE) {
taginfo->contentMode = 255;
if (taginfoitem->syncMode == SYNC_DELETE) {
taginfo->contentMode = 255;
wsSendTaginfo(taginfo->mac, SYNC_NOSYNC);
deleteRecord(taginfoitem->mac);
} else {
bool hasChanges = (memcmp(&initialTagInfo, taginfo, sizeof(tagRecord)) != 0);
if (hasChanges) {
wsSendTaginfo(taginfo->mac, SYNC_NOSYNC);
deleteRecord(taginfoitem->mac);
} else {
bool hasChanges = (memcmp(&initialTagInfo, taginfo, sizeof(tagRecord)) != 0);
if (hasChanges) {
wsSendTaginfo(taginfo->mac, SYNC_NOSYNC);
}
}
}
}
bool checkMirror(struct tagRecord * taginfo, struct pendingData * pending) {
for (int16_t c = 0; c < tagDB.size(); c++) {
tagRecord* taginfo2 = tagDB.at(c);
if (taginfo2->contentMode == 20) {
DynamicJsonDocument doc(500);
deserializeJson(doc, taginfo2->modeConfigJson);
JsonObject cfgobj = doc.as<JsonObject>();
uint8_t mac[8] = {0};
if (hex2mac(cfgobj["mac"], mac) && memcmp(mac, taginfo->mac, sizeof(mac)) == 0) {
if (taginfo->data == nullptr) {
fs::File file = contentFS->open(taginfo->filename);
if (!file) {
return false;
}
taginfo->data = getDataForFile(file);
file.close();
bool checkMirror(struct tagRecord* taginfo, struct pendingData* pending) {
for (int16_t c = 0; c < tagDB.size(); c++) {
tagRecord* taginfo2 = tagDB.at(c);
if (taginfo2->contentMode == 20) {
DynamicJsonDocument doc(500);
deserializeJson(doc, taginfo2->modeConfigJson);
JsonObject cfgobj = doc.as<JsonObject>();
uint8_t mac[8] = {0};
if (hex2mac(cfgobj["mac"], mac) && memcmp(mac, taginfo->mac, sizeof(mac)) == 0) {
if (taginfo->data == nullptr) {
fs::File file = contentFS->open(taginfo->filename);
if (!file) {
return false;
}
clearPending(taginfo2);
taginfo2->expectedNextCheckin = taginfo->expectedNextCheckin;
taginfo2->filename = taginfo->filename;
taginfo2->len = taginfo->len;
taginfo2->data = taginfo->data; // copy buffer pointer
taginfo2->dataType = taginfo->dataType;
taginfo2->pending = true;
taginfo2->nextupdate = 3216153600;
memcpy(taginfo2->md5pending, taginfo->md5pending, sizeof(taginfo->md5pending));
struct pendingData pending2 = {0};
memcpy(pending2.targetMac, taginfo2->mac, 8);
pending2.availdatainfo.dataType = taginfo2->dataType;
pending2.availdatainfo.dataVer = *((uint64_t*)taginfo2->md5pending);
pending2.availdatainfo.dataSize = taginfo2->len;
pending2.availdatainfo.dataTypeArgument = pending->availdatainfo.dataTypeArgument;
pending2.availdatainfo.nextCheckIn = pending->availdatainfo.nextCheckIn;
pending2.attemptsLeft = pending->attemptsLeft;
if (taginfo2->isExternal == false) {
sendDataAvail(&pending2);
} else {
char dst_path[64];
sprintf(dst_path, "/current/%02X%02X%02X%02X%02X%02X%02X%02X.pending\0", taginfo2->mac[7], taginfo2->mac[6], taginfo2->mac[5], taginfo2->mac[4], taginfo2->mac[3], taginfo2->mac[2], taginfo2->mac[1], taginfo2->mac[0]);
File file = contentFS->open(dst_path, "w");
if (file) {
file.write(taginfo2->data, taginfo2->len);
file.close();
udpsync.netSendDataAvail(&pending2);
}
}
wsSendTaginfo(taginfo2->mac, SYNC_TAGSTATUS);
taginfo->data = getDataForFile(file);
file.close();
}
clearPending(taginfo2);
taginfo2->expectedNextCheckin = taginfo->expectedNextCheckin;
taginfo2->filename = taginfo->filename;
taginfo2->len = taginfo->len;
taginfo2->data = taginfo->data; // copy buffer pointer
taginfo2->dataType = taginfo->dataType;
taginfo2->pending = true;
taginfo2->nextupdate = 3216153600;
memcpy(taginfo2->md5pending, taginfo->md5pending, sizeof(taginfo->md5pending));
struct pendingData pending2 = {0};
memcpy(pending2.targetMac, taginfo2->mac, 8);
pending2.availdatainfo.dataType = taginfo2->dataType;
pending2.availdatainfo.dataVer = *((uint64_t*)taginfo2->md5pending);
pending2.availdatainfo.dataSize = taginfo2->len;
pending2.availdatainfo.dataTypeArgument = pending->availdatainfo.dataTypeArgument;
pending2.availdatainfo.nextCheckIn = pending->availdatainfo.nextCheckIn;
pending2.attemptsLeft = pending->attemptsLeft;
if (taginfo2->isExternal == false) {
sendDataAvail(&pending2);
} else {
char dst_path[64];
sprintf(dst_path, "/current/%02X%02X%02X%02X%02X%02X%02X%02X.pending\0", taginfo2->mac[7], taginfo2->mac[6], taginfo2->mac[5], taginfo2->mac[4], taginfo2->mac[3], taginfo2->mac[2], taginfo2->mac[1], taginfo2->mac[0]);
File file = contentFS->open(dst_path, "w");
if (file) {
file.write(taginfo2->data, taginfo2->len);
file.close();
udpsync.netSendDataAvail(&pending2);
}
}
wsSendTaginfo(taginfo2->mac, SYNC_TAGSTATUS);
}
}
return false;
}
return false;
}

View File

@@ -7,6 +7,8 @@
#include <MD5Builder.h>
#include <Update.h>
#include "espflasher.h"
#include "serialap.h"
#include "storage.h"
#include "tag_db.h"
#include "util.h"
@@ -234,6 +236,60 @@ void handleRollback(AsyncWebServerRequest* request) {
}
}
void C6firmwareUpdateTask(void* parameter) {
wsSerial("Stopping AP service");
apInfo.isOnline = false;
apInfo.state = AP_STATE_FLASHING;
config.runStatus = RUNSTATUS_STOP;
extern bool rxSerialStopTask2;
rxSerialStopTask2 = true;
Serial1.end();
delay(250);
wsSerial("C6 flash starting");
bool result = doC6flash();
wsSerial("C6 flash end");
if (result) {
apInfo.state = AP_STATE_OFFLINE;
wsSerial("Finishing config...");
vTaskDelay(3000 / portTICK_PERIOD_MS);
wsSerial("starting monitor");
Serial1.begin(115200, SERIAL_8N1, FLASHER_AP_RXD, FLASHER_AP_TXD);
rxSerialStopTask2 = false;
#ifdef FLASHER_DEBUG_RXD
xTaskCreate(rxSerialTask2, "rxSerialTask2", 1750, NULL, configMAX_PRIORITIES - 4, NULL);
#endif
vTaskDelay(1000 / portTICK_PERIOD_MS);
wsSerial("resetting AP");
APTagReset();
vTaskDelay(1000 / portTICK_PERIOD_MS);
wsSerial("bringing AP online");
if (bringAPOnline()) config.runStatus = RUNSTATUS_RUN;
wsSerial("Finished!");
} else {
wsSerial("Flashing failed. :-(");
}
vTaskDelete(NULL);
}
void handleUpdateC6(AsyncWebServerRequest* request) {
#ifdef YELLOW_IPS_AP
xTaskCreate(C6firmwareUpdateTask, "OTAUpdateTask", 6144, NULL, 10, NULL);
request->send(200, "Ok");
#else
request->send(400, "C6 flashing not implemented");
#endif
}
void handleUpdateActions(AsyncWebServerRequest* request) {
wsSerial("Performing cleanup");
File file = contentFS->open("/update_actions.json", "r");

View File

@@ -15,6 +15,7 @@
#include "zbs_interface.h"
QueueHandle_t rxCmdQueue;
SemaphoreHandle_t txActive;
// If a command is sent, it will wait for a reply here
@@ -25,8 +26,9 @@ SemaphoreHandle_t txActive;
volatile uint8_t cmdReplyValue = CMD_REPLY_WAIT;
#define AP_SERIAL_PORT Serial1
volatile bool rxSerialStopTask2 = false;
uint8_t channelList[6];
uint8_t channelList[6];
struct espSetChannelPower curChannel = {0, 11, 10};
#define RX_CMD_RQB 0x01
@@ -264,6 +266,7 @@ bool sendChannelPower(struct espSetChannelPower* scp) {
return false;
}
bool sendPing() {
if (apInfo.state == AP_STATE_FLASHING) return true;
Serial.print("ping");
int t = millis();
if (!txStart()) return false;
@@ -582,13 +585,16 @@ void rxSerialTask(void* parameter) {
void rxSerialTask2(void* parameter) {
char lastchar = 0;
Serial2.begin(115200, SERIAL_8N1, FLASHER_DEBUG_TXD, FLASHER_DEBUG_RXD);
while (1) {
while (rxSerialStopTask2 == false) {
while (Serial2.available()) {
lastchar = Serial2.read();
Serial.write(lastchar);
}
vTaskDelay(1 / portTICK_PERIOD_MS);
}
Serial2.end();
Serial.println("Exiting AP serial monitor");
vTaskDelete(NULL);
}
#endif
@@ -640,6 +646,7 @@ void segmentedShowIp() {
}
bool bringAPOnline() {
if (apInfo.state == AP_STATE_FLASHING) return false;
apInfo.isOnline = false;
apInfo.state = AP_STATE_OFFLINE;
// try without rebooting
@@ -651,6 +658,7 @@ bool bringAPOnline() {
vTaskDelay(300 / portTICK_PERIOD_MS);
}
if (!APrdy) {
if (apInfo.state == AP_STATE_FLASHING) return false;
APTagReset();
vTaskDelay(500 / portTICK_PERIOD_MS);
bootTimeout = millis();
@@ -733,39 +741,42 @@ void APTask(void* parameter) {
updateContent(apInfo.mac);
}
uint16_t fsversion;
fsversion = getAPUpdateVersion(apInfo.type);
if ((fsversion) && (apInfo.version != fsversion) && (FLASHER_AP_MOSI != -1)) {
Serial.printf("Firmware version on LittleFS: %04X\n", fsversion);
Serial.printf("We're going to try to update the AP's FW in\n");
flashCountDown(30);
Serial.printf("\n");
notifySegmentedFlash();
apInfo.isOnline = false;
apInfo.state = AP_STATE_FLASHING;
if (doAPUpdate(apInfo.type)) {
checkWaitPowerCycle();
Serial.printf("Flash completed, let's try to boot the AP!\n");
if (bringAPOnline()) {
// AP works
ShowAPInfo();
setAPchannel();
uint16_t fsversion;
if (FLASHER_AP_MOSI != -1) {
fsversion = getAPUpdateVersion(apInfo.type);
if ((fsversion) && (apInfo.version != fsversion)) {
Serial.printf("Firmware version on LittleFS: %04X\n", fsversion);
Serial.printf("We're going to try to update the AP's FW in\n");
flashCountDown(30);
Serial.printf("\n");
notifySegmentedFlash();
apInfo.isOnline = false;
apInfo.state = AP_STATE_FLASHING;
if (doAPUpdate(apInfo.type)) {
checkWaitPowerCycle();
Serial.printf("Flash completed, let's try to boot the AP!\n");
if (bringAPOnline()) {
// AP works
ShowAPInfo();
setAPchannel();
} else {
Serial.printf("Failed to bring up the AP after flashing seemed successful... That's not supposed to happen!\n");
Serial.printf("This can be caused by a bad AP firmware, failed or failing hardware, or the inability to fully power-cycle the AP\n");
apInfo.state = AP_STATE_FAILED;
#ifdef HAS_RGB_LED
showColorPattern(CRGB::Red, CRGB::Yellow, CRGB::Red);
#endif
}
} else {
Serial.printf("Failed to bring up the AP after flashing seemed successful... That's not supposed to happen!\n");
Serial.printf("This can be caused by a bad AP firmware, failed or failing hardware, or the inability to fully power-cycle the AP\n");
apInfo.state = AP_STATE_FAILED;
#ifdef HAS_RGB_LED
showColorPattern(CRGB::Red, CRGB::Yellow, CRGB::Red);
#endif
checkWaitPowerCycle();
Serial.println("Failed to update version on the AP :(\n");
#ifdef HAS_RGB_LED
showColorPattern(CRGB::Red, CRGB::Red, CRGB::Red);
#endif
}
} else {
apInfo.state = AP_STATE_FAILED;
checkWaitPowerCycle();
Serial.println("Failed to update version on the AP :(\n");
#ifdef HAS_RGB_LED
showColorPattern(CRGB::Red, CRGB::Red, CRGB::Red);
#endif
}
}
refreshAllPending();
@@ -774,14 +785,23 @@ void APTask(void* parameter) {
#define FLASH_TIMEOUT 30
#endif
// AP unavailable, maybe time to flash?
apInfo.isOnline = false;
apInfo.state = AP_STATE_OFFLINE;
Serial.printf("I wasn't able to connect to a ZBS (AP) tag.\n");
Serial.printf("This could be the first time this AP is booted and the AP-tag may be unflashed.\n");
Serial.printf("If this tag was previously flashed succesfully but this message still shows up, there's probably something wrong with the serial connections.\n");
Serial.printf("The build of this firmware expects an AP tag with TXD/RXD on ESP32 pins %d and %d, does this match with your wiring?\n", FLASHER_AP_RXD, FLASHER_AP_TXD);
if (FLASHER_AP_MOSI != -1) {
if (FLASHER_AP_MOSI == -1) {
Serial.printf("I wasn't able to connect to the AP radio. Did you flash it?\n");
Serial.printf("The build of this firmware expects an AP tag with TXD/RXD on ESP32 pins %d and %d, does this match with your wiring?\n", FLASHER_AP_RXD, FLASHER_AP_TXD);
#ifdef HAS_RGB_LED
showColorPattern(CRGB::Red, CRGB::Yellow, CRGB::Red);
#endif
apInfo.isOnline = false;
apInfo.state = AP_STATE_FAILED;
} else {
// AP unavailable, maybe time to flash?
apInfo.isOnline = false;
apInfo.state = AP_STATE_OFFLINE;
Serial.printf("I wasn't able to connect to a ZBS (AP) tag.\n");
Serial.printf("This could be the first time this AP is booted and the AP-tag may be unflashed.\n");
Serial.printf("If this tag was previously flashed succesfully but this message still shows up, there's probably something wrong with the serial connections.\n");
Serial.printf("The build of this firmware expects an AP tag with TXD/RXD on ESP32 pins %d and %d, does this match with your wiring?\n", FLASHER_AP_RXD, FLASHER_AP_TXD);
Serial.printf("Performing firmware flash in about %d seconds!\n", FLASH_TIMEOUT);
flashCountDown(FLASH_TIMEOUT);
if (doAPFlash()) {

View File

@@ -331,9 +331,10 @@ void saveAPconfig() {
}
HwType getHwType(const uint8_t id) {
try {
return hwdata.at(id);
} catch (const std::out_of_range&) {
auto it = hwdata.find(id);
if (it != hwdata.end()) {
return it->second;
} else {
char filename[20];
snprintf(filename, sizeof(filename), "/tagtypes/%02X.json", id);
Serial.printf("read %s\n", filename);
@@ -345,6 +346,7 @@ HwType getHwType(const uint8_t id) {
filter["height"] = true;
filter["rotatebuffer"] = true;
filter["bpp"] = true;
filter["shortlut"] = true;
StaticJsonDocument<250> doc;
DeserializationError error = deserializeJson(doc, jsonFile, DeserializationOption::Filter(filter));
jsonFile.close();
@@ -356,10 +358,11 @@ HwType getHwType(const uint8_t id) {
hwdata[id].height = doc["height"];
hwdata[id].rotatebuffer = doc["rotatebuffer"];
hwdata[id].bpp = doc["bpp"];
hwdata[id].shortlut = doc["shortlut"];
return hwdata.at(id);
}
}
return {0, 0, 0, 0};
return {0, 0, 0, 0, 0};
}
}
@@ -381,3 +384,34 @@ bool setVarDB(const std::string& key, const String& value) {
return false;
}
}
String getBaseName(const String& filename) {
int lastDotIndex = filename.lastIndexOf('.');
return lastDotIndex != -1 ? filename.substring(0, lastDotIndex) : filename;
}
void cleanupCurrent() {
// clean unknown previews
File dir = contentFS->open("/current");
File file = dir.openNextFile();
while (file) {
String filename = file.name();
uint8_t mac[8];
if (hex2mac(getBaseName(filename), mac)) {
bool found = false;
for (tagRecord* record : tagDB) {
if (memcmp(record->mac, mac, 8) == 0) {
found = true;
break;
}
}
if (!found) {
filename = file.path();
file.close();
contentFS->remove(filename);
}
}
file = dir.openNextFile();
}
dir.close();
}

View File

@@ -321,6 +321,31 @@ void init_web() {
sendTagCommand(mac, CMD_DO_DEEPSLEEP, !taginfo->isExternal);
}
if (strcmp(cmdValue, "ledflash") == 0) {
struct ledFlash flashData = {0};
flashData.flashDuration = 8;
flashData.color1 = 0x3C; // green
flashData.color2 = 0xE4; // red
flashData.color3 = 0x03; // blue
flashData.flashCount1 = 1;
flashData.flashCount2 = 1;
flashData.flashCount3 = 1;
flashData.delay1 = 10;
flashData.delay2 = 10;
flashData.delay3 = 10;
flashData.repeats = 2;
const uint8_t *payload = reinterpret_cast<const uint8_t *>(&flashData);
sendTagCommand(mac, CMD_DO_LEDFLASH, !taginfo->isExternal, payload);
}
if (strcmp(cmdValue, "ledflash_long") == 0) {
struct ledFlash flashData = {0};
flashData.flashDuration = 15;
flashData.color1 = 0xE4; // red
flashData.flashCount1 = 5;
flashData.delay1 = 5;
flashData.delay3 = 15;
flashData.repeats = 10;
const uint8_t *payload = reinterpret_cast<const uint8_t *>(&flashData);
sendTagCommand(mac, CMD_DO_LEDFLASH, !taginfo->isExternal, payload);
}
request->send(200, "text/plain", "Ok, done");
} else {
@@ -553,6 +578,7 @@ void init_web() {
server.on("/sysinfo", HTTP_GET, handleSysinfoRequest);
server.on("/check_file", HTTP_GET, handleCheckFile);
server.on("/rollback", HTTP_POST, handleRollback);
server.on("/update_c6", HTTP_POST, handleUpdateC6);
server.on("/update_actions", HTTP_POST, handleUpdateActions);
server.on("/update_ota", HTTP_POST, [](AsyncWebServerRequest *request) {
handleUpdateOTA(request);

View File

@@ -10,6 +10,7 @@
#include "udp.h"
#include "web.h"
#include "ips_display.h"
#include "tag_db.h"
uint8_t WifiManager::apClients = 0;
uint8_t x_buffer[100];
@@ -103,8 +104,23 @@ bool WifiManager::connectToWifi(String ssid, String pass, bool savewhensuccessfu
_APstarted = false;
WiFi.disconnect(false, true);
WiFi.mode(WIFI_MODE_NULL);
char hostname[32] = "OpenEpaperLink-AP\0";
if (config.alias[0] != '\0') {
int len = strlen(config.alias);
int j = 0;
for (int i = 0; i < len; i++) {
char c = config.alias[i];
if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '-') {
hostname[j] = c;
j++;
}
}
hostname[j] = '\0';
}
WiFi.setHostname(hostname);
WiFi.mode(WIFI_STA);
WiFi.setSleep(WIFI_PS_NONE);
WiFi.setSleep(WIFI_PS_MIN_MODEM);
terminalLog("Connecting to WiFi...");
logLine("Connecting to WiFi...");

View File

@@ -224,7 +224,10 @@ to save file system space">
<div id="easyupdate"></div>
<div id="advanceddiv">
<div id="releasetable"></div>
<div id="rollbackOption" style="display:none"><button id="rollbackBtn">Rollback to previous firmware</button></div>
<div>
<div id="rollbackOption" style="display:none"><button id="rollbackBtn">Rollback to previous firmware</button></div>
<div id="updateC6Option"><button id="updateC6Btn">Update ESP32-C6</button></div>
</div>
</div>
</div>
@@ -244,7 +247,7 @@ to save file system space">
<div><span id="runstate"></div>
<div><span id="apstatecolor">&#11044;</span> <span id="apstate">loading</span></div>
<div><span id="apconfigbutton">AP config</span></div>
<div><a href="/edit" target="littlefs" class="filebutton">file system</a></div>
<div><a href="/edit" target="littlefs" class="filebutton">File System</a></div>
</div>
<div id="filterOptions">
<div>

View File

@@ -532,6 +532,11 @@ ul.messages li.new {
display: none;
}
#advanceddiv div:nth-child(2) {
display: flex;
gap: 10px;
}
#releasetable {
margin: 10px 0px;
}

View File

@@ -940,6 +940,7 @@ async function getTagtype(hwtype) {
rotatebuffer: jsonData.rotatebuffer,
colortable: Object.values(jsonData.colortable),
contentids: Object.values(jsonData.contentids ?? []),
options: Object.values(jsonData.options ?? []),
busy: false
};
tagTypes[hwtype] = data;
@@ -1079,7 +1080,7 @@ $('#taglist').addEventListener('contextmenu', (e) => {
const clickedGridItem = e.target.closest('.tagcard');
if (clickedGridItem) {
let mac = clickedGridItem.dataset.mac;
console.log("tagcard");
const hwtype = clickedGridItem.dataset.hwtype;
let contextMenuOptions = [
{ id: 'refresh', label: 'Force refresh' },
{ id: 'clear', label: 'Clear pending status' }
@@ -1090,6 +1091,12 @@ $('#taglist').addEventListener('contextmenu', (e) => {
{ id: 'reboot', label: 'Reboot tag' },
);
};
if (tagTypes[hwtype].options?.includes("led")) {
contextMenuOptions.push(
{ id: 'ledflash', label: 'Flash the LED' },
{ id: 'ledflash_long', label: 'Flash the LED (long)' }
);
}
contextMenuOptions.push(
{ id: 'del', label: 'Delete tag from list' }
);

View File

@@ -336,6 +336,25 @@ $('#rollbackBtn').onclick = function () {
disableButtons(false);
}
$('#updateC6Btn').onclick = function () {
if (running) return;
disableButtons(true);
running = true;
errors = 0;
const consoleDiv = document.getElementById('updateconsole');
consoleDiv.scrollTop = consoleDiv.scrollHeight;
print("Flashing ESP32-C6...");
fetch("/update_c6", {
method: "POST",
body: ''
})
running = false;
disableButtons(false);
}
export function print(line, color = "white") {
const consoleDiv = document.getElementById('updateconsole');
if (consoleDiv) {

View File

@@ -6,7 +6,7 @@ You can use the following flasher-scripts to program various types of tags with
* 88MZ100-based tags
This is the schematic for the flasher, including a pinout for the debug-header that is used by quite a few Solum tags. This flasher is also compatible with the OEPL-AP-Flasher jig/programming boards.
![image](https://github.com/jjwbruijn/OpenEPaperLink/assets/2544995/25227120-d3cb-4c2d-b19d-99fdc795bda1)
![image](https://github.com/jjwbruijn/OpenEPaperLink/assets/2544995/1fa5bef8-6624-4e53-9caa-aeaaf4dbdc55)
This is what it looks like with the wires connected. I've chosen to use 0.635mm pitch wires, to be able to use the jigs with the 1.27mm FDC connectors. After soldering, you can add a little bit of hot-glue to make sure they stay attached.