1
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
35
36
37
38
42
43
44
45
46
47
48
52
53
54
55
56
57
61
62
63
64
65
66
67
68
72
73
74
83
84
85
88
89
90
93
/* ... */
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <sys/unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#include "esp_err.h"
#include "esp_log.h"
#include "esp_cpu.h"
#include "esp_vfs_semihost.h"10 includes
static const char *TAG = "example";
#define STRINGIFY(s) STRINGIFY2(s)
#define STRINGIFY2(s) #s
static uint8_t s_buf[512];
void app_main(void)
{
esp_err_t ret = esp_vfs_semihost_register("/host");
if (ret != ESP_OK) {
ESP_LOGE(TAG, "Failed to register semihost driver (%s)!", esp_err_to_name(ret));
return;
}{...}
ESP_LOGW(TAG, "Switch to semihosted stdout");
FILE *fout = freopen("/host/esp32_stdout.txt", "w", stdout);
if (fout == NULL) {
ESP_LOGE(TAG, "Failed to reopen stdout (%d)!", errno);
return;
}{...}
setvbuf(fout, (char *)s_buf, _IOFBF, sizeof(s_buf));
ESP_LOGW(TAG, "Switched to semihosted stdout");
for (int i = 0; i < 100; i++) {
printf("Semihosted stdout write %d\n", i);
}{...}
ESP_LOGW(TAG, "Switch to UART stdout");
fflush(fout);
int count = ftell(fout);
stdout = freopen("/dev/console", "w", fout);
if (stdout == NULL) {
ESP_LOGE(TAG, "Failed to reopen semihosted stdout (%d)!", errno);
return;
}{...}
ESP_LOGW(TAG, "Switched back to UART stdout");
ESP_LOGI(TAG, "Wrote %d bytes", count);
printf("====================== HOST DATA START =========================\n");
int fd = open("/host/host_file.txt", O_RDONLY, 0);
if (fd == -1) {
ESP_LOGE(TAG, "Failed to open file (%d)!", errno);
return;
}{...}
ssize_t read_bytes;
count = 0;
do {
read_bytes = read(fd, s_buf, sizeof(s_buf));
if(read_bytes == -1) {
ESP_LOGE(TAG, "Failed to read file (%d)!", errno);
}{...} else if(read_bytes > 0) {
fwrite(s_buf, 1, read_bytes, stdout);
count += read_bytes;
}{...}
}{...} while(read_bytes > 0);
printf("====================== HOST DATA END =========================\n");
ESP_LOGI(TAG, "Read %d bytes", count);
if (close(fd) == -1) {
ESP_LOGE(TAG, "Failed to close file (%d)!", errno);
}{...}
ret = esp_vfs_semihost_unregister("/host");
if (ret != ESP_OK) {
ESP_LOGE(TAG, "Failed to unregister semihost driver (%s)!", esp_err_to_name(ret));
}{...}
}{ ... }