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