Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
…ring/teddycloud into develop
  • Loading branch information
SciLor committed Oct 4, 2023
2 parents 870a53a + 7939d06 commit 081a831
Show file tree
Hide file tree
Showing 2 changed files with 100 additions and 26 deletions.
102 changes: 81 additions & 21 deletions contrib/data/www/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -1870,14 +1870,16 @@ <h3>Encode to {this.props.path}</h3>
flashSize: '',
state: '',
filename: '',
flashName: '',
port: null,
originalFlash: null,
patchedFlash: null,
showStatus: false,
showProgress: false,
showDownload: false,
showFlash: false,
connected: false
connected: false,
hostname: window.location.hostname
};
this.fileInputRef = React.createRef();
}
Expand All @@ -1886,25 +1888,72 @@ <h3>Encode to {this.props.path}</h3>
this.fileInputRef.current.click();
}

loadFlashFile = (e) => {
loadFlashFile = async (e) => {
const file = e.target.files[0];

if (!file) {
return;
}

console.log("Read file '" + file + "'");
const reader = new FileReader();
reader.onload = (e) => {
this.setState({ patchedFlash: e.target.result, showFlash: true });
reader.onload = async (e) => {
console.log("Connecting to ESP32");
const port = await this.getPort('Connecting to read MAC-Address');

if (port == null || this.state.connected) {
return;
}

this.setState({ state: `Connecting to ${port.info}`, showFlash: false, connected: true });

var esploader = null;
try {
esploader = new ESPLoader({
port: port,
baudrate: 921600
});
} catch (err) {
this.setState({ state: `Failed to connect: ${err.message}`, connected: false });
alert(err.message);
await port.close();
return;
}

try {
this.setState({ state: `Retrieving MAC address...` });
await esploader.main_fn();

var mac = await esploader.chip.read_mac(esploader);
this.setState({ chipMac: mac });
console.log("Chip MAC: " + mac);
await port.close();

const flashData = new Uint8Array(e.target.result);

const sanitizedName = `ESP32_${mac.replace(/:/g, "")}`;
await this.uploadFlashData(flashData, sanitizedName);

this.setState({ patchedFlash: e.target.result, showFlash: true, connected: false, flashName: 'from file' });
console.log("Done");

} catch (err) {
this.setState({ state: `Failed to communicate: ${err.message}`, connected: false });
console.error(err);
alert(err.message);
await port.close();
return;
}
};

reader.readAsArrayBuffer(file);
}

async getPort() {
async getPort(message) {
if (this.state.port) {
return this.state.port;
}
this.setState({ showStatus: true, showProgress: false, progress: 0, state: "Open serial port" });
this.setState({ showStatus: true, showProgress: false, progress: 0, state: message ? message : "Open serial port" });
let port = null;
try {
port = await navigator.serial.requestPort();
Expand All @@ -1925,7 +1974,6 @@ <h3>Encode to {this.props.path}</h3>
return null;
}


if (!port) {
this.setState({ state: "Invalid serial port" });
return null;
Expand Down Expand Up @@ -2018,6 +2066,7 @@ <h3>Encode to {this.props.path}</h3>
this.setState({ state: `Writing ${(this.state.patchedFlash.byteLength / 1024 / 1024).toFixed(0)} MiB flash` });
await esploader.write_flash(opts);

await port.close();
this.setState({ state: `Writing finished`, connected: false });
} catch (err) {
this.setState({ state: `Failed to communicate: ${err.message}`, connected: false });
Expand All @@ -2026,20 +2075,19 @@ <h3>Encode to {this.props.path}</h3>
await port.close();
return;
}
await port.close();
}

async patchFlash() {
this.setState({ showProgress: false, showFlash: false });
this.setState({ state: `Patching flash image... (will likely take 5 minutes)` });
this.setState({ state: `Patching flash image...` });
const response = await fetch(`/api/patchFirmware?filename=${this.state.filename}&hostname=${this.state.hostname}`, {
method: 'GET'
});
this.setState({ state: `Payload received` });

if (response.ok && response.status == 200) {
const arrayBuffer = await response.arrayBuffer();
this.setState({ patchedFlash: arrayBuffer, showFlash: true });
this.setState({ patchedFlash: arrayBuffer, showFlash: true, flashName: 'patched' });
this.setState({ state: `Patching successful, ready to flash ${(arrayBuffer.byteLength / 1024 / 1024).toFixed(0)} MiB` });
} else {
this.setState({ state: `Patching failed` });
Expand All @@ -2061,7 +2109,6 @@ <h3>Encode to {this.props.path}</h3>

this.setState({ state: `Connecting to ${port.info}`, showFlash: false, connected: true });


try {
esploader = new ESPLoader({
port: port,
Expand Down Expand Up @@ -2106,6 +2153,7 @@ <h3>Encode to {this.props.path}</h3>
this.setState({ progress: prog });
});

await port.close();
this.setState({ state: `Reading finished`, progress: 100, originalFlash: flashData, connected: false });
} catch (err) {
this.setState({ state: `Failed to communicate: ${err.message}`, connected: false });
Expand All @@ -2114,13 +2162,16 @@ <h3>Encode to {this.props.path}</h3>
await port.close();
return;
}
await port.close();

const sanitizedName = `ESP32_${mac.replace(/:/g, "")}`;
await this.uploadFlashData(flashData, sanitizedName);
}

async uploadFlashData(flashData, sanitizedName) {
try {
this.setState({ state: `Uploading` });

const formData = new FormData();
const sanitizedName = `ESP32_${mac.replace(/:/g, "")}`;
formData.append(sanitizedName, new Blob([flashData.buffer]), sanitizedName);

const response = await fetch('/api/uploadFirmware', {
Expand All @@ -2130,17 +2181,17 @@ <h3>Encode to {this.props.path}</h3>

if (response.ok && response.status == 200) {
const filename = await response.text();
this.setState({ showDownload: true });
this.setState({ filename: filename });
this.setState({ state: `Upload successful: saved as ${filename}` });
this.setState({
showDownload: true,
filename: filename,
state: `Upload successful: saved as ${filename}`
});
} else {
this.setState({ state: `Upload failed` });
}
} catch (err) {
console.error('There was an error!', err);
this.setState(prevState => ({
files: prevState.files.map(file => ({ ...file, status: 'Failed' }))
}));
console.error('There was an error when uploading!', err);
this.setState({ state: `Upload failed` });
}
}

Expand All @@ -2153,6 +2204,7 @@ <h3>Encode to {this.props.path}</h3>
return input.replace(/[^a-zA-Z0-9-.]/g, '').trim();
};


return (
<div className="tile encoder-tile">
<h3>ESP32 box flashing</h3>
Expand All @@ -2167,7 +2219,15 @@ <h3>ESP32 box flashing</h3>
<button className="button" disabled={buttonDisabled} onClick={() => this.readFlash()}>Read ESP32</button>
<button className="button" disabled={buttonDisabled} onClick={() => this.openFile()}>Load file</button>
{this.state.showDownload && <button className="button" disabled={buttonDisabled} onClick={() => this.patchFlash()}>Patch image</button>}
{this.state.showFlash && <button className="button-red" disabled={buttonDisabled} onClick={() => this.writeFlash()}>Flash ESP32</button>}
{this.state.showFlash && (
<button
className="button-red"
disabled={buttonDisabled}
onClick={() => this.writeFlash()}
>
{`Flash ESP32${this.state.flashName ? ` (${this.state.flashName})` : ''}`}
</button>
)}

<div className="center-content">
{this.state.showDownload && (
Expand Down
24 changes: 19 additions & 5 deletions src/esp32.c
Original file line number Diff line number Diff line change
Expand Up @@ -141,10 +141,18 @@ size_t esp32_wl_translate(const struct wl_state *state, size_t sector)

DWORD get_fattime()
{
uint32_t year = 2023;
uint32_t mon = 7;
uint32_t day = 31;
return ((uint32_t)(year - 1980) << 25 | (uint32_t)mon << 21 | (uint32_t)day << 16);
// Retrieve current time
time_t time = getCurrentUnixTime();
DateTime date;
convertUnixTimeToDate(time, &date);

return (
(uint32_t)(date.year - 1980) << 25 |
(uint32_t)(date.month) << 21 |
(uint32_t)(date.day) << 16 |
(uint32_t)(date.hours) << 11 |
(uint32_t)(date.minutes) << 5 |
(uint32_t)(date.seconds) >> 1);
}

DRESULT disk_ioctl(BYTE pdrv, BYTE cmd, void *buff)
Expand Down Expand Up @@ -279,7 +287,7 @@ error_t esp32_fixup_fatfs(FsFile *file, size_t offset, size_t length, bool modif
}
TRACE_INFO(" %-12s %-10u %04d-%02d-%02d %02d:%02d:%02d\r\n", fileInfo.fname, fileInfo.fsize,
((fileInfo.fdate >> 9) & 0x7F) + 1980,
(fileInfo.fdate >> 5) & 0x1F,
(fileInfo.fdate >> 5) & 0x0F,
(fileInfo.fdate) & 0x1F,
(fileInfo.ftime >> 11) & 0x1F,
(fileInfo.ftime >> 5) & 0x3F,
Expand Down Expand Up @@ -961,6 +969,12 @@ error_t esp32_inject_ca(const char *rootPath, const char *patchedPath, const cha
ret = ERROR_NOT_FOUND;
break;
}
if (fsRemoveDir(cert_path) != NO_ERROR)
{
TRACE_ERROR("Failed to delete directory during clean-up '%s'\r\n", cert_path);
ret = ERROR_NOT_FOUND;
break;
}
} while (0);

free(cert_path);
Expand Down

0 comments on commit 081a831

Please sign in to comment.