ESPHome 2026.3.0-dev
Loading...
Searching...
No Matches
qr_code.cpp
Go to the documentation of this file.
1#include "qr_code.h"
4#include "esphome/core/log.h"
5
6namespace esphome {
7namespace qr_code {
8
9static const char *const TAG = "qr_code";
10
12 ESP_LOGCONFIG(TAG,
13 "QR code:\n"
14 " Value: '%s'",
15 this->value_.c_str());
16}
17
18void QrCode::set_value(const std::string &value) {
19 this->value_ = value;
20 this->needs_update_ = true;
21}
22
23void QrCode::set_ecc(qrcodegen_Ecc ecc) {
24 this->ecc_ = ecc;
25 this->needs_update_ = true;
26}
27
29 ESP_LOGV(TAG, "Generating QR code");
30
31#ifdef USE_ESP32
32 // ESP32 has 8KB stack, safe to allocate ~4KB buffer on stack
33 uint8_t tempbuffer[qrcodegen_BUFFER_LEN_MAX];
34#else
35 // Other platforms (ESP8266: 4KB, RP2040: 2KB, LibreTiny: ~4KB) have smaller stacks
36 // Allocate buffer on heap to avoid stack overflow
37 auto tempbuffer_owner = std::make_unique<uint8_t[]>(qrcodegen_BUFFER_LEN_MAX);
38 uint8_t *tempbuffer = tempbuffer_owner.get();
39#endif
40
41 if (!qrcodegen_encodeText(this->value_.c_str(), tempbuffer, this->qr_, this->ecc_, qrcodegen_VERSION_MIN,
42 qrcodegen_VERSION_MAX, qrcodegen_Mask_AUTO, true)) {
43 ESP_LOGE(TAG, "Failed to generate QR code");
44 }
45}
46
47void QrCode::draw(display::Display *buff, uint16_t x_offset, uint16_t y_offset, Color color, int scale) {
48 ESP_LOGV(TAG, "Drawing QR code at (%d, %d)", x_offset, y_offset);
49
50 if (this->needs_update_) {
51 this->generate_qr_code();
52 this->needs_update_ = false;
53 }
54
55 uint8_t qrcode_width = qrcodegen_getSize(this->qr_);
56
57 for (int y = 0; y < qrcode_width * scale; y++) {
58 for (int x = 0; x < qrcode_width * scale; x++) {
59 if (qrcodegen_getModule(this->qr_, x / scale, y / scale)) {
60 buff->draw_pixel_at(x_offset + x, y_offset + y, color);
61 }
62 }
63 }
64}
65
67 if (this->needs_update_) {
68 this->generate_qr_code();
69 this->needs_update_ = false;
70 }
71
72 uint8_t size = qrcodegen_getSize(this->qr_);
73
74 return size;
75}
76
77} // namespace qr_code
78} // namespace esphome
void draw_pixel_at(int x, int y)
Set a single pixel at the specified coordinates to default color.
Definition display.h:336
uint8_t qr_[qrcodegen_BUFFER_LEN_MAX]
Definition qr_code.h:33
void draw(display::Display *buff, uint16_t x_offset, uint16_t y_offset, Color color, int scale)
Definition qr_code.cpp:47
void set_ecc(qrcodegen_Ecc ecc)
Definition qr_code.cpp:23
void set_value(const std::string &value)
Definition qr_code.cpp:18
void dump_config() override
Definition qr_code.cpp:11
qrcodegen_Ecc ecc_
Definition qr_code.h:31
Providing packet encoding functions for exchanging data with a remote host.
Definition a01nyub.cpp:7
size_t size
Definition helpers.h:854
uint16_t x
Definition tt21100.cpp:5
uint16_t y
Definition tt21100.cpp:6