Function bodies 132 total
applyMask function · c · L610-L633 (24 LOC)components/qr_display/qrcodegen.c
static void applyMask(const uint8_t functionModules[], uint8_t qrcode[], enum qrcodegen_Mask mask) {
assert(0 <= (int)mask && (int)mask <= 7); // Disallows qrcodegen_Mask_AUTO
int qrsize = qrcodegen_getSize(qrcode);
for (int y = 0; y < qrsize; y++) {
for (int x = 0; x < qrsize; x++) {
if (getModuleBounded(functionModules, x, y))
continue;
bool invert;
switch ((int)mask) {
case 0: invert = (x + y) % 2 == 0; break;
case 1: invert = y % 2 == 0; break;
case 2: invert = x % 3 == 0; break;
case 3: invert = (x + y) % 3 == 0; break;
case 4: invert = (x / 3 + y / 2) % 2 == 0; break;
case 5: invert = x * y % 2 + x * y % 3 == 0; break;
case 6: invert = (x * y % 2 + x * y % 3) % 2 == 0; break;
case 7: invert = ((x + y) % 2 + x * y % 3) % 2 == 0; break;
default: assert(false); return;
}
bool val = getModuleBounded(qrcogetPenaltyScore function · c · L638-L713 (76 LOC)components/qr_display/qrcodegen.c
static long getPenaltyScore(const uint8_t qrcode[]) {
int qrsize = qrcodegen_getSize(qrcode);
long result = 0;
// Adjacent modules in row having same color, and finder-like patterns
for (int y = 0; y < qrsize; y++) {
bool runColor = false;
int runX = 0;
int runHistory[7] = {0};
for (int x = 0; x < qrsize; x++) {
if (getModuleBounded(qrcode, x, y) == runColor) {
runX++;
if (runX == 5)
result += PENALTY_N1;
else if (runX > 5)
result++;
} else {
finderPenaltyAddHistory(runX, runHistory, qrsize);
if (!runColor)
result += finderPenaltyCountPatterns(runHistory, qrsize) * PENALTY_N3;
runColor = getModuleBounded(qrcode, x, y);
runX = 1;
}
}
result += finderPenaltyTerminateAndCount(runColor, runX, runHistory, qrsize) * PENALTY_N3;
}
// Adjacent modules in column having same color, and finder-like patterns
for (int x = 0; x < qrsize; x++) {
bool runColor = false;
int runY = 0;
int runHistory[7] = {0};
for (int y = 0finderPenaltyCountPatterns function · c · L718-L726 (9 LOC)components/qr_display/qrcodegen.c
static int finderPenaltyCountPatterns(const int runHistory[7], int qrsize) {
int n = runHistory[1];
assert(n <= qrsize * 3); (void)qrsize;
bool core = n > 0 && runHistory[2] == n && runHistory[3] == n * 3 && runHistory[4] == n && runHistory[5] == n;
// The maximum QR Code size is 177, hence the dark run length n <= 177.
// Arithmetic is promoted to int, so n*4 will not overflow.
return (core && runHistory[0] >= n * 4 && runHistory[6] >= n ? 1 : 0)
+ (core && runHistory[6] >= n * 4 && runHistory[0] >= n ? 1 : 0);
}finderPenaltyTerminateAndCount function · c · L730-L738 (9 LOC)components/qr_display/qrcodegen.c
static int finderPenaltyTerminateAndCount(bool currentRunColor, int currentRunLength, int runHistory[7], int qrsize) {
if (currentRunColor) { // Terminate dark run
finderPenaltyAddHistory(currentRunLength, runHistory, qrsize);
currentRunLength = 0;
}
currentRunLength += qrsize; // Add light border to final run
finderPenaltyAddHistory(currentRunLength, runHistory, qrsize);
return finderPenaltyCountPatterns(runHistory, qrsize);
}finderPenaltyAddHistory function · c · L742-L747 (6 LOC)components/qr_display/qrcodegen.c
static void finderPenaltyAddHistory(int currentRunLength, int runHistory[7], int qrsize) {
if (runHistory[0] == 0)
currentRunLength += qrsize; // Add light border to initial run
memmove(&runHistory[1], &runHistory[0], 6 * sizeof(runHistory[0]));
runHistory[0] = currentRunLength;
}qrcodegen_getSize function · c · L754-L760 (7 LOC)components/qr_display/qrcodegen.c
int qrcodegen_getSize(const uint8_t qrcode[]) {
assert(qrcode != NULL);
int result = qrcode[0];
assert((qrcodegen_VERSION_MIN * 4 + 17) <= result
&& result <= (qrcodegen_VERSION_MAX * 4 + 17));
return result;
}qrcodegen_getModule function · c · L764-L768 (5 LOC)components/qr_display/qrcodegen.c
bool qrcodegen_getModule(const uint8_t qrcode[], int x, int y) {
assert(qrcode != NULL);
int qrsize = qrcode[0];
return (0 <= x && x < qrsize && 0 <= y && y < qrsize) && getModuleBounded(qrcode, x, y);
}All rows above produced by Repobility · https://repobility.com
getModuleBounded function · c · L772-L777 (6 LOC)components/qr_display/qrcodegen.c
testable bool getModuleBounded(const uint8_t qrcode[], int x, int y) {
int qrsize = qrcode[0];
assert(21 <= qrsize && qrsize <= 177 && 0 <= x && x < qrsize && 0 <= y && y < qrsize);
int index = y * qrsize + x;
return getBit(qrcode[(index >> 3) + 1], index & 7);
}setModuleBounded function · c · L781-L791 (11 LOC)components/qr_display/qrcodegen.c
testable void setModuleBounded(uint8_t qrcode[], int x, int y, bool isDark) {
int qrsize = qrcode[0];
assert(21 <= qrsize && qrsize <= 177 && 0 <= x && x < qrsize && 0 <= y && y < qrsize);
int index = y * qrsize + x;
int bitIndex = index & 7;
int byteIndex = (index >> 3) + 1;
if (isDark)
qrcode[byteIndex] |= 1 << bitIndex;
else
qrcode[byteIndex] &= (1 << bitIndex) ^ 0xFF;
}setModuleUnbounded function · c · L795-L799 (5 LOC)components/qr_display/qrcodegen.c
testable void setModuleUnbounded(uint8_t qrcode[], int x, int y, bool isDark) {
int qrsize = qrcode[0];
if (0 <= x && x < qrsize && 0 <= y && y < qrsize)
setModuleBounded(qrcode, x, y, isDark);
}getBit function · c · L803-L805 (3 LOC)components/qr_display/qrcodegen.c
static bool getBit(int x, int i) {
return ((x >> i) & 1) != 0;
}qrcodegen_isNumeric function · c · L812-L819 (8 LOC)components/qr_display/qrcodegen.c
bool qrcodegen_isNumeric(const char *text) {
assert(text != NULL);
for (; *text != '\0'; text++) {
if (*text < '0' || *text > '9')
return false;
}
return true;
}qrcodegen_isAlphanumeric function · c · L823-L830 (8 LOC)components/qr_display/qrcodegen.c
bool qrcodegen_isAlphanumeric(const char *text) {
assert(text != NULL);
for (; *text != '\0'; text++) {
if (strchr(ALPHANUMERIC_CHARSET, *text) == NULL)
return false;
}
return true;
}qrcodegen_calcSegmentBufferSize function · c · L834-L840 (7 LOC)components/qr_display/qrcodegen.c
size_t qrcodegen_calcSegmentBufferSize(enum qrcodegen_Mode mode, size_t numChars) {
int temp = calcSegmentBitLength(mode, numChars);
if (temp == LENGTH_OVERFLOW)
return SIZE_MAX;
assert(0 <= temp && temp <= INT16_MAX);
return ((size_t)temp + 7) / 8;
}calcSegmentBitLength function · c · L851-L874 (24 LOC)components/qr_display/qrcodegen.c
testable int calcSegmentBitLength(enum qrcodegen_Mode mode, size_t numChars) {
// All calculations are designed to avoid overflow on all platforms
if (numChars > (unsigned int)INT16_MAX)
return LENGTH_OVERFLOW;
long result = (long)numChars;
if (mode == qrcodegen_Mode_NUMERIC)
result = (result * 10 + 2) / 3; // ceil(10/3 * n)
else if (mode == qrcodegen_Mode_ALPHANUMERIC)
result = (result * 11 + 1) / 2; // ceil(11/2 * n)
else if (mode == qrcodegen_Mode_BYTE)
result *= 8;
else if (mode == qrcodegen_Mode_KANJI)
result *= 13;
else if (mode == qrcodegen_Mode_ECI && numChars == 0)
result = 3 * 8;
else { // Invalid argument
assert(false);
return LENGTH_OVERFLOW;
}
assert(result >= 0);
if (result > INT16_MAX)
return LENGTH_OVERFLOW;
return (int)result;
}About: code-quality intelligence by Repobility · https://repobility.com
qrcodegen_makeBytes function · c · L878-L889 (12 LOC)components/qr_display/qrcodegen.c
struct qrcodegen_Segment qrcodegen_makeBytes(const uint8_t data[], size_t len, uint8_t buf[]) {
assert(data != NULL || len == 0);
struct qrcodegen_Segment result;
result.mode = qrcodegen_Mode_BYTE;
result.bitLength = calcSegmentBitLength(result.mode, len);
assert(result.bitLength != LENGTH_OVERFLOW);
result.numChars = (int)len;
if (len > 0)
memcpy(buf, data, len * sizeof(buf[0]));
result.data = buf;
return result;
}qrcodegen_makeNumeric function · c · L893-L923 (31 LOC)components/qr_display/qrcodegen.c
struct qrcodegen_Segment qrcodegen_makeNumeric(const char *digits, uint8_t buf[]) {
assert(digits != NULL);
struct qrcodegen_Segment result;
size_t len = strlen(digits);
result.mode = qrcodegen_Mode_NUMERIC;
int bitLen = calcSegmentBitLength(result.mode, len);
assert(bitLen != LENGTH_OVERFLOW);
result.numChars = (int)len;
if (bitLen > 0)
memset(buf, 0, ((size_t)bitLen + 7) / 8 * sizeof(buf[0]));
result.bitLength = 0;
unsigned int accumData = 0;
int accumCount = 0;
for (; *digits != '\0'; digits++) {
char c = *digits;
assert('0' <= c && c <= '9');
accumData = accumData * 10 + (unsigned int)(c - '0');
accumCount++;
if (accumCount == 3) {
appendBitsToBuffer(accumData, 10, buf, &result.bitLength);
accumData = 0;
accumCount = 0;
}
}
if (accumCount > 0) // 1 or 2 digits remaining
appendBitsToBuffer(accumData, accumCount * 3 + 1, buf, &result.bitLength);
assert(result.bitLength == bitLen);
result.data = buf;
return result;
}qrcodegen_makeAlphanumeric function · c · L927-L957 (31 LOC)components/qr_display/qrcodegen.c
struct qrcodegen_Segment qrcodegen_makeAlphanumeric(const char *text, uint8_t buf[]) {
assert(text != NULL);
struct qrcodegen_Segment result;
size_t len = strlen(text);
result.mode = qrcodegen_Mode_ALPHANUMERIC;
int bitLen = calcSegmentBitLength(result.mode, len);
assert(bitLen != LENGTH_OVERFLOW);
result.numChars = (int)len;
if (bitLen > 0)
memset(buf, 0, ((size_t)bitLen + 7) / 8 * sizeof(buf[0]));
result.bitLength = 0;
unsigned int accumData = 0;
int accumCount = 0;
for (; *text != '\0'; text++) {
const char *temp = strchr(ALPHANUMERIC_CHARSET, *text);
assert(temp != NULL);
accumData = accumData * 45 + (unsigned int)(temp - ALPHANUMERIC_CHARSET);
accumCount++;
if (accumCount == 2) {
appendBitsToBuffer(accumData, 11, buf, &result.bitLength);
accumData = 0;
accumCount = 0;
}
}
if (accumCount > 0) // 1 character remaining
appendBitsToBuffer(accumData, 6, buf, &result.bitLength);
assert(result.bitLength == bitLen);
result.data = buf;
return reqrcodegen_makeEci function · c · L961-L984 (24 LOC)components/qr_display/qrcodegen.c
struct qrcodegen_Segment qrcodegen_makeEci(long assignVal, uint8_t buf[]) {
struct qrcodegen_Segment result;
result.mode = qrcodegen_Mode_ECI;
result.numChars = 0;
result.bitLength = 0;
if (assignVal < 0)
assert(false);
else if (assignVal < (1 << 7)) {
memset(buf, 0, 1 * sizeof(buf[0]));
appendBitsToBuffer((unsigned int)assignVal, 8, buf, &result.bitLength);
} else if (assignVal < (1 << 14)) {
memset(buf, 0, 2 * sizeof(buf[0]));
appendBitsToBuffer(2, 2, buf, &result.bitLength);
appendBitsToBuffer((unsigned int)assignVal, 14, buf, &result.bitLength);
} else if (assignVal < 1000000L) {
memset(buf, 0, 3 * sizeof(buf[0]));
appendBitsToBuffer(6, 3, buf, &result.bitLength);
appendBitsToBuffer((unsigned int)(assignVal >> 10), 11, buf, &result.bitLength);
appendBitsToBuffer((unsigned int)(assignVal & 0x3FF), 10, buf, &result.bitLength);
} else
assert(false);
result.data = buf;
return result;
}getTotalBits function · c · L990-L1008 (19 LOC)components/qr_display/qrcodegen.c
testable int getTotalBits(const struct qrcodegen_Segment segs[], size_t len, int version) {
assert(segs != NULL || len == 0);
long result = 0;
for (size_t i = 0; i < len; i++) {
int numChars = segs[i].numChars;
int bitLength = segs[i].bitLength;
assert(0 <= numChars && numChars <= INT16_MAX);
assert(0 <= bitLength && bitLength <= INT16_MAX);
int ccbits = numCharCountBits(segs[i].mode, version);
assert(0 <= ccbits && ccbits <= 16);
if (numChars >= (1L << ccbits))
return LENGTH_OVERFLOW; // The segment's length doesn't fit the field's bit width
result += 4L + ccbits + bitLength;
if (result > INT16_MAX)
return LENGTH_OVERFLOW; // The sum might overflow an int type
}
assert(0 <= result && result <= INT16_MAX);
return (int)result;
}numCharCountBits function · c · L1013-L1024 (12 LOC)components/qr_display/qrcodegen.c
static int numCharCountBits(enum qrcodegen_Mode mode, int version) {
assert(qrcodegen_VERSION_MIN <= version && version <= qrcodegen_VERSION_MAX);
int i = (version + 7) / 17;
switch (mode) {
case qrcodegen_Mode_NUMERIC : { static const int temp[] = {10, 12, 14}; return temp[i]; }
case qrcodegen_Mode_ALPHANUMERIC: { static const int temp[] = { 9, 11, 13}; return temp[i]; }
case qrcodegen_Mode_BYTE : { static const int temp[] = { 8, 16, 16}; return temp[i]; }
case qrcodegen_Mode_KANJI : { static const int temp[] = { 8, 10, 12}; return temp[i]; }
case qrcodegen_Mode_ECI : return 0;
default: assert(false); return -1; // Dummy value
}
}qr_display_show function · c · L17-L104 (88 LOC)components/qr_display/qr_display.c
esp_err_t qr_display_show(esp_lcd_panel_handle_t panel, const char *text,
uint16_t fg, uint16_t bg)
{
/* Heap-allocate QR buffers (avoid ~8KB stack usage) */
uint8_t *qr_buf = malloc(QR_BUF_LEN);
uint8_t *temp_buf = malloc(QR_BUF_LEN);
if (!qr_buf || !temp_buf) {
ESP_LOGE(TAG, "Failed to allocate QR buffers");
free(qr_buf);
free(temp_buf);
return ESP_FAIL;
}
bool ok = qrcodegen_encodeText(text, temp_buf, qr_buf,
qrcodegen_Ecc_MEDIUM,
qrcodegen_VERSION_MIN, QR_VERSION_MAX,
qrcodegen_Mask_AUTO, true);
/* temp_buf no longer needed after encoding */
free(temp_buf);
if (!ok) {
ESP_LOGE(TAG, "Failed to encode QR code for: %s", text);
free(qr_buf);
return ESP_FAIL;
}
int qr_size = qrcodegen_getSize(qr_buf);
/* Add 2-module quiet zone on each side */
int tunmount_sd function · c · L46-L50 (5 LOC)components/usage_store/usage_store.c
static void unmount_sd(sdmmc_card_t *card)
{
esp_vfs_fat_sdcard_unmount(MOUNT_POINT, card);
}Repobility · open methodology · https://repobility.com/research/
usage_store_init function · c · L53-L61 (9 LOC)components/usage_store/usage_store.c
esp_err_t usage_store_init(spi_host_device_t spi_host, int cs_gpio)
{
s_spi_host = spi_host;
s_cs_gpio = cs_gpio;
s_configured = true;
ESP_LOGI(TAG, "SD card configured on SPI%d, CS=GPIO%d (lazy mount)", spi_host + 1, cs_gpio);
return ESP_OK;
}usage_store_append function · c · L62-L104 (43 LOC)components/usage_store/usage_store.c
esp_err_t usage_store_append(float five_hour, float seven_day)
{
if (!s_configured) return ESP_ERR_INVALID_STATE;
sdmmc_card_t *card = mount_sd();
if (!card) return ESP_FAIL;
time_t now = time(NULL);
struct tm local;
localtime_r(&now, &local);
int mr = mkdir(MOUNT_POINT "/ccusage", 0775);
if (mr != 0 && errno != EEXIST) {
ESP_LOGE(TAG, "mkdir failed: errno=%d", errno);
}
char path[64];
snprintf(path, sizeof(path), MOUNT_POINT "/ccusage/usage_%04d-%02d.csv",
local.tm_year + 1900, local.tm_mon + 1);
struct stat st;
bool new_file = (stat(path, &st) != 0);
FILE *f = fopen(path, "a");
if (!f) {
ESP_LOGE(TAG, "Failed to open %s", path);
unmount_sd(card);
return ESP_FAIL;
}
if (new_file) {
fprintf(f, "timestamp,five_hour,seven_day\n");
}
fprintf(f, "%ld,%.1f,%.1f\n", (long)now, five_hour, seven_day);
fclose(f);
ESP_LOGI(TAG, "Stored: %.1f%% / %.1f%usage_store_read function · c · L105-L158 (54 LOC)components/usage_store/usage_store.c
int usage_store_read(time_t from, time_t to, usage_data_point_t *buf, int max_points,
int stride, usage_column_t col)
{
if (!s_configured) return 0;
if (stride < 1) stride = 1;
sdmmc_card_t *card = mount_sd();
if (!card) return 0;
struct tm from_tm, to_tm;
localtime_r(&from, &from_tm);
localtime_r(&to, &to_tm);
int count = 0;
int skip = 0;
int y = from_tm.tm_year + 1900, m = from_tm.tm_mon + 1;
int y_end = to_tm.tm_year + 1900, m_end = to_tm.tm_mon + 1;
while ((y < y_end || (y == y_end && m <= m_end)) && count < max_points) {
char path[64];
snprintf(path, sizeof(path), MOUNT_POINT "/ccusage/usage_%04d-%02d.csv", y, m);
FILE *f = fopen(path, "r");
if (f) {
char line[64];
fgets(line, sizeof(line), f); /* skip CSV header */
while (fgets(line, sizeof(line), f) && count < max_points) {
long ts;
float five_h, seven_d;
set_state function · c · L54-L62 (9 LOC)components/wifi_manager/wifi_manager.c
static void set_state(wifi_mgr_state_t new_state)
{
s_state = new_state;
ESP_LOGI(TAG, "State -> %d", new_state);
if (s_state_cb) {
s_state_cb(new_state, s_state_cb_arg);
}
}nvs_read_str function · c · L63-L73 (11 LOC)components/wifi_manager/wifi_manager.c
static esp_err_t nvs_read_str(const char *key, char *out, size_t max_len)
{
nvs_handle_t h;
esp_err_t err = nvs_open(NVS_NAMESPACE, NVS_READONLY, &h);
if (err != ESP_OK) return err;
size_t len = max_len;
err = nvs_get_str(h, key, out, &len);
nvs_close(h);
return err;
}nvs_write_str function · c · L74-L84 (11 LOC)components/wifi_manager/wifi_manager.c
static esp_err_t nvs_write_str(const char *key, const char *value)
{
nvs_handle_t h;
esp_err_t err = nvs_open(NVS_NAMESPACE, NVS_READWRITE, &h);
if (err != ESP_OK) return err;
err = nvs_set_str(h, key, value);
if (err == ESP_OK) err = nvs_commit(h);
nvs_close(h);
return err;
}has_stored_credentials function · c · L85-L90 (6 LOC)components/wifi_manager/wifi_manager.c
static bool has_stored_credentials(void)
{
char ssid[33];
return nvs_read_str("ssid", ssid, sizeof(ssid)) == ESP_OK && strlen(ssid) > 0;
}base64url_encode function · c · L96-L108 (13 LOC)components/wifi_manager/wifi_manager.c
static void base64url_encode(const uint8_t *in, size_t in_len, char *out, size_t out_size)
{
size_t olen;
mbedtls_base64_encode((uint8_t *)out, out_size, &olen, in, in_len);
/* base64 → base64url */
for (size_t i = 0; i < olen; i++) {
if (out[i] == '+') out[i] = '-';
else if (out[i] == '/') out[i] = '_';
}
while (olen > 0 && out[olen - 1] == '=') olen--;
out[olen] = '\0';
}Citation: Repobility (2026). State of AI-Generated Code. https://repobility.com/research/
generate_pkce function · c · L109-L121 (13 LOC)components/wifi_manager/wifi_manager.c
static void generate_pkce(void)
{
uint8_t rand_bytes[32];
esp_fill_random(rand_bytes, sizeof(rand_bytes));
base64url_encode(rand_bytes, sizeof(rand_bytes), s_pkce_verifier, sizeof(s_pkce_verifier));
uint8_t hash[32];
mbedtls_sha256((const uint8_t *)s_pkce_verifier, strlen(s_pkce_verifier), hash, 0);
base64url_encode(hash, sizeof(hash), s_pkce_challenge, sizeof(s_pkce_challenge));
ESP_LOGI(TAG, "PKCE generated (verifier=%d chars, state=verifier)", (int)strlen(s_pkce_verifier));
}hex_val function · c · L124-L131 (8 LOC)components/wifi_manager/wifi_manager.c
static int hex_val(char c)
{
if (c >= '0' && c <= '9') return c - '0';
if (c >= 'a' && c <= 'f') return c - 'a' + 10;
if (c >= 'A' && c <= 'F') return c - 'A' + 10;
return -1;
}url_decode function · c · L132-L153 (22 LOC)components/wifi_manager/wifi_manager.c
static void url_decode(char *dst, const char *src, size_t dst_size)
{
size_t di = 0;
for (size_t si = 0; src[si] && di < dst_size - 1; si++) {
if (src[si] == '%' && src[si+1] && src[si+2]) {
int h = hex_val(src[si+1]);
int l = hex_val(src[si+2]);
if (h >= 0 && l >= 0) {
dst[di++] = (char)((h << 4) | l);
si += 2;
continue;
}
}
if (src[si] == '+') {
dst[di++] = ' ';
} else {
dst[di++] = src[si];
}
}
dst[di] = '\0';
}parse_form_field function · c · L156-L178 (23 LOC)components/wifi_manager/wifi_manager.c
static esp_err_t parse_form_field(const char *body, const char *key, char *out, size_t out_size)
{
char search[64];
snprintf(search, sizeof(search), "%s=", key);
const char *start = strstr(body, search);
if (!start) {
out[0] = '\0';
return ESP_ERR_NOT_FOUND;
}
start += strlen(search);
const char *end = strchr(start, '&');
size_t len = end ? (size_t)(end - start) : strlen(start);
/* Temporary buffer for encoded value */
char encoded[256];
if (len >= sizeof(encoded)) len = sizeof(encoded) - 1;
memcpy(encoded, start, len);
encoded[len] = '\0';
url_decode(out, encoded, out_size);
return ESP_OK;
}http_get_root function · c · L181-L187 (7 LOC)components/wifi_manager/wifi_manager.c
static esp_err_t http_get_root(httpd_req_t *req)
{
httpd_resp_set_type(req, "text/html");
httpd_resp_send(req, portal_html, strlen(portal_html));
return ESP_OK;
}http_get_scan function · c · L188-L245 (58 LOC)components/wifi_manager/wifi_manager.c
static esp_err_t http_get_scan(httpd_req_t *req)
{
/* Trigger a WiFi scan */
wifi_scan_config_t scan_cfg = { .show_hidden = false };
esp_err_t err = esp_wifi_scan_start(&scan_cfg, true);
if (err != ESP_OK) {
httpd_resp_send_err(req, HTTPD_500_INTERNAL_SERVER_ERROR, "Scan failed");
return ESP_FAIL;
}
uint16_t ap_count = 0;
esp_wifi_scan_get_ap_num(&ap_count);
if (ap_count > 20) ap_count = 20;
wifi_ap_record_t *ap_list = malloc(ap_count * sizeof(wifi_ap_record_t));
if (!ap_list) {
httpd_resp_send_err(req, HTTPD_500_INTERNAL_SERVER_ERROR, "OOM");
return ESP_FAIL;
}
esp_wifi_scan_get_ap_records(&ap_count, ap_list);
/* Build JSON response */
char *json = malloc(2048);
if (!json) {
free(ap_list);
httpd_resp_send_err(req, HTTPD_500_INTERNAL_SERVER_ERROR, "OOM");
return ESP_FAIL;
}
int pos = 0;
pos += snprintf(json + pos, 2048 - pos, "[");
for (int i = 0; i <reboot_timer_cb function · c · L246-L251 (6 LOC)components/wifi_manager/wifi_manager.c
static void reboot_timer_cb(TimerHandle_t timer)
{
ESP_LOGI(TAG, "Rebooting after provisioning...");
esp_restart();
}http_post_connect function · c · L252-L300 (49 LOC)components/wifi_manager/wifi_manager.c
static esp_err_t http_post_connect(httpd_req_t *req)
{
char buf[512];
int received = httpd_req_recv(req, buf, sizeof(buf) - 1);
if (received <= 0) {
httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, "No data");
return ESP_FAIL;
}
buf[received] = '\0';
char ssid[33] = {0};
char password[65] = {0};
char timezone[64] = {0};
char fetch_int[8] = {0};
parse_form_field(buf, "ssid", ssid, sizeof(ssid));
parse_form_field(buf, "password", password, sizeof(password));
parse_form_field(buf, "timezone", timezone, sizeof(timezone));
parse_form_field(buf, "fetch_int", fetch_int, sizeof(fetch_int));
if (strlen(ssid) == 0) {
httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, "SSID required");
return ESP_FAIL;
}
ESP_LOGI(TAG, "Saving credentials: SSID='%s'", ssid);
nvs_write_str("ssid", ssid);
nvs_write_str("password", password);
if (strlen(timezone) > 0) nvs_write_str("timezone", timezone);
iAll rows above produced by Repobility · https://repobility.com
http_redirect_handler function · c · L303-L445 (143 LOC)components/wifi_manager/wifi_manager.c
static esp_err_t http_redirect_handler(httpd_req_t *req)
{
httpd_resp_set_status(req, "302 Found");
httpd_resp_set_hdr(req, "Location", "http://192.168.4.1/");
httpd_resp_send(req, NULL, 0);
return ESP_OK;
}
/* ---------- Station mode: config page ---------- */
static esp_err_t http_get_config(httpd_req_t *req)
{
wifi_mgr_credentials_t *creds = malloc(sizeof(wifi_mgr_credentials_t));
if (!creds) {
httpd_resp_send_err(req, HTTPD_500_INTERNAL_SERVER_ERROR, "OOM");
return ESP_FAIL;
}
wifi_mgr_get_credentials(creds);
/* Generate fresh PKCE for OAuth link */
generate_pkce();
/* Mask token for display: show first 20 chars + "..." */
char rt_display[28] = {0};
if (strlen(creds->refresh_token) > 20) {
snprintf(rt_display, sizeof(rt_display), "%.20s...", creds->refresh_token);
} else if (strlen(creds->refresh_token) > 0) {
strncpy(rt_display, creds->refresh_token, sizeof(rt_display) - 1);
}
charhttp_get_config function · c · L312-L445 (134 LOC)components/wifi_manager/wifi_manager.c
static esp_err_t http_get_config(httpd_req_t *req)
{
wifi_mgr_credentials_t *creds = malloc(sizeof(wifi_mgr_credentials_t));
if (!creds) {
httpd_resp_send_err(req, HTTPD_500_INTERNAL_SERVER_ERROR, "OOM");
return ESP_FAIL;
}
wifi_mgr_get_credentials(creds);
/* Generate fresh PKCE for OAuth link */
generate_pkce();
/* Mask token for display: show first 20 chars + "..." */
char rt_display[28] = {0};
if (strlen(creds->refresh_token) > 20) {
snprintf(rt_display, sizeof(rt_display), "%.20s...", creds->refresh_token);
} else if (strlen(creds->refresh_token) > 0) {
strncpy(rt_display, creds->refresh_token, sizeof(rt_display) - 1);
}
char *page = malloc(5120);
if (!page) {
free(creds);
httpd_resp_send_err(req, HTTPD_500_INTERNAL_SERVER_ERROR, "OOM");
return ESP_FAIL;
}
int len = snprintf(page, 5120,
"<!DOCTYPE html><html><head>"
"<meta charset=\"utf-8\">"
http_post_config function · c · L446-L486 (41 LOC)components/wifi_manager/wifi_manager.c
static esp_err_t http_post_config(httpd_req_t *req)
{
char *buf = malloc(1024);
if (!buf) {
httpd_resp_send_err(req, HTTPD_500_INTERNAL_SERVER_ERROR, "OOM");
return ESP_FAIL;
}
int received = httpd_req_recv(req, buf, 1023);
if (received <= 0) {
free(buf);
httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, "No data");
return ESP_FAIL;
}
buf[received] = '\0';
char ssid[33] = {0};
char password[65] = {0};
char refresh_tk[256] = {0};
char timezone[64] = {0};
char fetch_int[8] = {0};
parse_form_field(buf, "ssid", ssid, sizeof(ssid));
parse_form_field(buf, "password", password, sizeof(password));
parse_form_field(buf, "refresh_tk", refresh_tk, sizeof(refresh_tk));
parse_form_field(buf, "timezone", timezone, sizeof(timezone));
parse_form_field(buf, "fetch_int", fetch_int, sizeof(fetch_int));
free(buf);
/* Only update non-empty fields */
bool wifi_changed = false;
if (strhttp_post_wifi_reset function · c · L487-L499 (13 LOC)components/wifi_manager/wifi_manager.c
static esp_err_t http_post_wifi_reset(httpd_req_t *req)
{
ESP_LOGI(TAG, "WiFi reset requested via web");
httpd_resp_set_type(req, "application/json");
httpd_resp_sendstr(req, "{\"ok\":true}");
/* Erase WiFi credentials and reboot after response is sent */
vTaskDelay(pdMS_TO_TICKS(500));
wifi_mgr_erase_credentials();
esp_restart();
return ESP_OK; /* unreachable */
}http_post_oauth_exchange function · c · L500-L620 (121 LOC)components/wifi_manager/wifi_manager.c
static esp_err_t http_post_oauth_exchange(httpd_req_t *req)
{
char *buf = malloc(512);
if (!buf) {
httpd_resp_send_err(req, HTTPD_500_INTERNAL_SERVER_ERROR, "OOM");
return ESP_FAIL;
}
int received = httpd_req_recv(req, buf, 511);
if (received <= 0) { free(buf); return ESP_FAIL; }
buf[received] = '\0';
char code[256] = {0};
parse_form_field(buf, "code", code, sizeof(code));
free(buf);
if (strlen(code) == 0 || strlen(s_pkce_verifier) == 0) {
httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, "Missing code or PKCE expired");
return ESP_FAIL;
}
ESP_LOGI(TAG, "OAuth code exchange...");
/* Split code on '#' → pure_code + state (state is after '#') */
char *hash = strchr(code, '#');
char *state = "";
if (hash) {
*hash = '\0';
state = hash + 1;
}
/* Build JSON body for token endpoint */
cJSON *body = cJSON_CreateObject();
cJSON_AddStringToObject(body, "grant_type",start_http_server_provisioning function · c · L623-L625 (3 LOC)components/wifi_manager/wifi_manager.c
static void start_http_server_provisioning(void)
{start_http_server_station function · c · L647-L670 (24 LOC)components/wifi_manager/wifi_manager.c
static void start_http_server_station(void)
{
httpd_config_t config = HTTPD_DEFAULT_CONFIG();
config.max_uri_handlers = 8;
config.stack_size = 16384; /* OAuth exchange needs TLS → big stack */
if (httpd_start(&s_httpd, &config) != ESP_OK) {
ESP_LOGE(TAG, "Failed to start HTTP server");
return;
}
httpd_uri_t root = { .uri = "/", .method = HTTP_GET, .handler = http_get_config };
httpd_uri_t cfg = { .uri = "/config", .method = HTTP_POST, .handler = http_post_config };
httpd_uri_t rst = { .uri = "/wifi-reset", .method = HTTP_POST, .handler = http_post_wifi_reset };
httpd_uri_t oex = { .uri = "/oauth/exchange", .method = HTTP_POST, .handler = http_post_oauth_exchange };
httpd_register_uri_handler(s_httpd, &root);
httpd_register_uri_handler(s_httpd, &cfg);
httpd_register_uri_handler(s_httpd, &rst);
httpd_register_uri_handler(s_httpd, &oex);
ESP_LOGI(TAG, "HTTP server started (station)");
}wifi_event_handler function · c · L673-L704 (32 LOC)components/wifi_manager/wifi_manager.c
static void wifi_event_handler(void *arg, esp_event_base_t event_base,
int32_t event_id, void *event_data)
{
if (event_base == WIFI_EVENT) {
switch (event_id) {
case WIFI_EVENT_STA_START:
esp_wifi_connect();
break;
case WIFI_EVENT_STA_DISCONNECTED:
if (s_state == WIFI_MGR_STATE_CONNECTING) {
if (s_retry_count < MAX_STA_RETRIES) {
s_retry_count++;
ESP_LOGI(TAG, "Retry %d/%d...", s_retry_count, MAX_STA_RETRIES);
esp_wifi_connect();
} else {
ESP_LOGW(TAG, "Connection failed after %d retries", MAX_STA_RETRIES);
xEventGroupSetBits(s_wifi_event_group, WIFI_FAIL_BIT);
}
}
break;
default:
break;
}
} else if (event_base == IP_EVENT && event_id == IP_EVENT_STA_GOT_IP) {
ip_event_got_ip_t *eveAbout: code-quality intelligence by Repobility · https://repobility.com
start_provisioning function · c · L707-L739 (33 LOC)components/wifi_manager/wifi_manager.c
static void start_provisioning(void)
{
/* Create AP netif */
esp_netif_create_default_wifi_ap();
/* Configure SoftAP */
wifi_config_t wifi_cfg = {
.ap = {
.max_connection = 4,
.authmode = WIFI_AUTH_OPEN,
.channel = 1,
},
};
strncpy((char *)wifi_cfg.ap.ssid, s_ap_ssid, sizeof(wifi_cfg.ap.ssid));
wifi_cfg.ap.ssid_len = strlen(s_ap_ssid);
ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_APSTA));
ESP_ERROR_CHECK(esp_wifi_set_config(WIFI_IF_AP, &wifi_cfg));
ESP_ERROR_CHECK(esp_wifi_start());
ESP_LOGI(TAG, "SoftAP started: %s", s_ap_ssid);
/* Start DNS server — redirect all queries to our IP */
dns_server_config_t dns_cfg = DNS_SERVER_CONFIG_SINGLE("*", "WIFI_AP_DEF");
s_dns = start_dns_server(&dns_cfg);
/* Start HTTP captive portal */
start_http_server_provisioning();
/* Update display AFTER WiFi is fully started (avoids SPI/NVS flash conflict) */
set_state(WIFI_MGR_sta_connect_task function · c · L742-L779 (38 LOC)components/wifi_manager/wifi_manager.c
static void sta_connect_task(void *arg)
{
wifi_mgr_credentials_t creds;
wifi_mgr_get_credentials(&creds);
/* Create STA netif */
esp_netif_create_default_wifi_sta();
wifi_config_t wifi_cfg = {0};
strncpy((char *)wifi_cfg.sta.ssid, creds.ssid, sizeof(wifi_cfg.sta.ssid));
strncpy((char *)wifi_cfg.sta.password, creds.password, sizeof(wifi_cfg.sta.password));
/* Enable WPA2/WPA3 and fallback */
wifi_cfg.sta.threshold.authmode = strlen(creds.password) > 0 ? WIFI_AUTH_WPA2_PSK : WIFI_AUTH_OPEN;
ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_STA));
ESP_ERROR_CHECK(esp_wifi_set_config(WIFI_IF_STA, &wifi_cfg));
ESP_ERROR_CHECK(esp_wifi_start());
/* Update display AFTER WiFi is started */
set_state(WIFI_MGR_STATE_CONNECTING);
ESP_LOGI(TAG, "Connecting to '%s'...", creds.ssid);
/* Wait for connection result */
EventBits_t bits = xEventGroupWaitBits(s_wifi_event_group,
WIFI_CONNECTEDwifi_mgr_init function · c · L782-L821 (40 LOC)components/wifi_manager/wifi_manager.c
esp_err_t wifi_mgr_init(wifi_mgr_state_cb_t state_cb, void *cb_arg)
{
s_state_cb = state_cb;
s_state_cb_arg = cb_arg;
/* Initialize NVS */
esp_err_t ret = nvs_flash_init();
if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND) {
ESP_LOGW(TAG, "NVS corrupted, erasing...");
ESP_ERROR_CHECK(nvs_flash_erase());
ret = nvs_flash_init();
}
ESP_ERROR_CHECK(ret);
/* Initialize network stack and event loop */
ESP_ERROR_CHECK(esp_netif_init());
ESP_ERROR_CHECK(esp_event_loop_create_default());
/* Initialize WiFi with default config */
wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
ESP_ERROR_CHECK(esp_wifi_init(&cfg));
/* Register event handlers */
ESP_ERROR_CHECK(esp_event_handler_instance_register(WIFI_EVENT, ESP_EVENT_ANY_ID,
&wifi_event_handler, NULL, NULL));
ESP_ERROR_CHECK(esp_event_handler_instance_register(IP_EVE