### MQTT Configuration Examples Source: https://github.com/gyverlibs/gyverhub/blob/main/docs/2.start.md Examples demonstrating how to use the `hub.mqtt.config` function to set up the MQTT client with different server addresses (hostname or IP) and authentication details. ```C++ void setup() { // настройка на сервер, установленный в приложении по умолчанию hub.mqtt.config("test.mosquitto.org", 1883); // другие примеры hub.mqtt.config(IPAddress(12, 34, 56, 78), 1883); hub.mqtt.config("m8.wqtt.ru", 13448, "user", "pass"); } ``` -------------------------------- ### Configuring WiFi (AP Mode) Source: https://github.com/gyverlibs/gyverhub/blob/main/docs/2.start.md Code for setting up an ESP device to function as a WiFi Access Point (AP). This allows other devices to connect directly to the ESP. ```C++ void setup() { WiFi.mode(WIFI_AP); WiFi.softAP("My Device"); // ... } ``` -------------------------------- ### Configuring Bluetooth Stream (SoftwareSerial) Source: https://github.com/gyverlibs/gyverhub/blob/main/docs/2.start.md Configuring the GyverHub communication stream to use a `SoftwareSerial` object, typically connected to a Bluetooth module via UART. This example defines a `SoftwareSerial` object and configures the stream for Bluetooth communication. ```C++ SoftwareSerial bt(3, 4); void setup() { hub.stream.config(&bt, gh::Connection::Bluetooth); // ... } ``` -------------------------------- ### Configuring WiFi (STA Mode) Source: https://github.com/gyverlibs/gyverhub/blob/main/docs/2.start.md Standard code for connecting an ESP device to a WiFi router in Station (STA) mode using the WiFi library. Includes waiting for a successful connection. ```C++ void setup() { WiFi.mode(WIFI_STA); WiFi.begin("SSID", "PASS"); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } // ... } ``` -------------------------------- ### MQTT Configuration Function Signature Source: https://github.com/gyverlibs/gyverhub/blob/main/docs/2.start.md The function signature for configuring the built-in MQTT client within GyverHub. It specifies parameters for the host, port, optional login, password, QoS level, and retain flag. ```C++ config(const String& host, uint16_t port, const String& login = "", const String& pass = "", uint8_t qos = 0, bool ret = 0) ``` -------------------------------- ### Saving Widget Values with FileData in GyverHub C++ Source: https://github.com/gyverlibs/gyverhub/blob/main/docs/4.widgets.md Provides a comprehensive example of saving widget values to persistent storage (LittleFS) using the `FileData` library. It defines a struct to hold data, initializes `FileData`, connects widgets to struct members, checks for changes using `b.changed()`, and handles reading/writing data in `setup` and `loop`. ```cpp #include #include #include struct Data { uint8_t spinner; uint16_t slider; char str[20]; }; Data data; FileData data(&LittleFS, "/data.dat", 'A', &mydata, sizeof(mydata)); void build(gh::Builder& b) { b.Spinner(&data.spinner); b.Slider(&data.slider); b.Input(data.str); // если что то изменилось - запускаем обновление if (b.changed()) data.update(); } void setup() { // ....... data.read(); } void loop() { // ...... // сохранение в файл происходит по таймауту здесь data.tick(); } ``` -------------------------------- ### Attaching Function Handlers to Button in GyverHub C++ Source: https://github.com/gyverlibs/gyverhub/blob/main/docs/4.widgets.md Illustrates how to attach C++ functions as handlers to button clicks. Two examples are shown: a simple callback and one that receives the `gh::Build` object, providing access to build context like client information. ```cpp void build(gh::Builder& b) { // подключить функцию-обработчик b.Button().attach(btn_cb); // подключить функцию-обработчик с инфо о билде b.Button().attach(btn_cb_b); } ``` -------------------------------- ### Configuring Serial Stream Source: https://github.com/gyverlibs/gyverhub/blob/main/docs/2.start.md Configuring the GyverHub communication stream to use the standard `Serial` object. This sets up communication over the USB/UART interface, specifying the connection type as Serial. ```C++ void setup() { hub.stream.config(&Serial, gh::Connection::Serial); // ... } ``` -------------------------------- ### GyverHub Utility Methods - C++ Source: https://github.com/gyverlibs/gyverhub/blob/main/docs/1.main.md This snippet defines several utility functions for interacting with the GyverHub interface. Functions include triggering a UI refresh, checking if a refresh was requested, controlling widget visibility, detecting widget value changes, getting the current menu item, and adding widgets from JSON strings or files. ```cpp // обновить панель управления (по действию с виджета) void refresh(); // был ли запрос на обновление панели управления bool isRefresh(); // включить/выключить вывод виджетов (только для запроса виджетов) bool show(bool en = true); // было изменено значение виджета (сигнал на сохранение) bool changed(); // номер текущего пункта меню uint8_t menu(); // добавить виджеты из JSON строки void addJSON(AnyText text); // добавить виджеты из JSON строки PROGMEM void addJSON_P(PGM_P text); // добавить виджеты из JSON из файла void addJSON_File(AnyText path); ``` -------------------------------- ### Creating Nested Row and Column Layouts in GyverHub C++ Source: https://github.com/gyverlibs/gyverhub/blob/main/docs/4.widgets.md Provides an example of nesting containers by placing a vertical container (`gh::Col`) inside a horizontal container (`gh::Row`). This demonstrates how to build more complex UI structures. ```cpp void build(gh::Builder& b) { { gh::Row r(b); b.Button(); { gh::Col c(b); b.Button(); b.Button(); } } } ``` -------------------------------- ### gh::Action Enum (C++) Source: https://github.com/gyverlibs/gyverhub/blob/main/docs/1.main.md Defines the gh::Action enumeration, representing various actions or commands within the system, such as UI, Read, Set, Get, None. ```cpp UI Read Set Get None ``` -------------------------------- ### gh::Fetcher Class Definition (C++) Source: https://github.com/gyverlibs/gyverhub/blob/main/docs/1.main.md Defines the gh::Fetcher class, responsible for sending data (files or raw bytes) to the client. It includes methods to fetch files by path or File object, and to fetch raw bytes from RAM or program memory (PGM). It also contains members indicating the start of a download and the path of the file being fetched. ```cpp // отправить файл по пути void fetchFile(const char* path); // отправить файл template void fetchFile(T& file); // отправить сырые данные void fetchBytes(uint8_t* bytes, uint32_t len); // отправить сырые данные из PGM void fetchBytes_P(const uint8_t* bytes, uint32_t len); // true - начало скачивания bool start; // путь к скачиваемому файлу AnyText path; ``` -------------------------------- ### gh::Update Class Definition (C++) Source: https://github.com/gyverlibs/gyverhub/blob/main/docs/1.main.md Defines the gh::Update class, used to initiate and manage updates for widgets. It includes a constructor, a method to start an update for a specific widget or function, a method to send the update packet, and a member variable to hold the current widget being updated. ```cpp Update(GyverHub* hub, Client* client = nullptr); // начать обновление по имени виджета (или список) + имя функции Widget& update(AnyText name, AnyText func); // отправить пакет void send(); // текущий виджет для установки значений ghc::Widget widget; ``` -------------------------------- ### Enable File System Support in GyverHub (C++) Source: https://github.com/gyverlibs/gyverhub/blob/main/docs/3.app.md To enable GyverHub to serve files from the filesystem (e.g., index.html.gz, script.js.gz), you must define the `GH_FILE_PORTAL` macro before including the GyverHub library header file. This tells the library to include the necessary code for file handling. ```C++ #define GH_FILE_PORTAL #include ``` -------------------------------- ### Sending Data and Status via MQTT (C++) Source: https://github.com/gyverlibs/gyverhub/blob/main/docs/1.main.md Provides functions for sending data (various types) and status updates to specific MQTT topics. Includes methods for automatically sending state changes and retrieving topic names. ```cpp // автоматически отправлять новое состояние на get-топик при изменении через set (умолч. false) void sendGetAuto(bool state); // отправить имя-значение на get-топик (MQTT) int/string/bool void sendGet(AnyText name, AnyValue value); // отправить имя-значение на get-топик (MQTT) float void sendGet(AnyText name, double value, uint8_t dec); // отправить значение по имени компонента на get-топик (MQTT) (значение будет прочитано в build). Имена можно передать списком через ; void sendGet(String name); // отправить MQTT LWT команду на включение/выключение void sendStatus(bool status); // топик статуса для отправки String topicStatus(); // общий топик для подписки String topicDiscover(); // топик устройства для подписки String topicHub(); ``` -------------------------------- ### Intercepting File Fetching with GyverHub onFetch (C++) Source: https://github.com/gyverlibs/gyverhub/blob/main/docs/8.advanced.md Demonstrates how to use the `onFetch` handler to intercept file download requests from the GyverHub interface. It allows serving data from memory (RAM or PROGMEM), redirecting to another file, or providing dynamic content like camera frames. The handler receives a `gh::Fetcher` object containing the requested path and state. ```cpp const char* fetch_bytes = "fetch bytes"; const char fetch_pgm[] PROGMEM = "fetch pgm"; void fetch(gh::Fetcher& f) { // например по имени файла можно отправить данные из памяти программы или из PROGMEM if (f.path == "/fetch_bytes.txt") f.fetchBytes((uint8_t*)fetch_bytes, strlen(fetch_bytes)); if (f.path == "/fetch_pgm.txt") f.fetchBytes_P((uint8_t*)fetch_pgm, strlen_P(fetch_pgm)); // или отправить другой файл if (f.path == "/fetch_file.txt") f.fetchFile("/fetch_file123.txt"); // также можно отправить например кадр с камеры: if (f.path == "frame.jpg") { // start == true - начало загрузки if (f.start) { frame = esp_camera_fb_get(); // получить кадр if (frame) f.fetchBytes((uint8_t*)frame->buf, frame->len); // начать отправку // start == true - конец загрузки } else { esp_camera_fb_return(frame); // освободить кадр } } } void setup() { hub.onFetch(fetch); } ``` -------------------------------- ### Defining GyverHub Widgets (C++) Source: https://github.com/gyverlibs/gyverhub/blob/main/docs/1.main.md Functions for creating various GyverHub widget types such as Label, Text, Display, Image, Log, LED, Icon, Gauge, and Table. Each function typically takes initial content or a pointer and returns a reference to the created Widget object, allowing for method chaining. ```cpp Widget& Label(AnyValue text); Widget& Label_(AnyText name, AnyValue text); Widget& Label_(AnyText name, Pairs* pairs); // Окно с текстом. Параметры: value (текст), rows + параметры виджета Widget& Text(AnyValue text); Widget& Text_(AnyText name, AnyValue text); Widget& Text_(AnyText name, Pairs* pairs); // Окно с текстом. Параметры: value (путь), rows + параметры виджета Widget& TextFile(AnyValue text); Widget& TextFile_(AnyText name, AnyValue text); Widget& TextFile_(AnyText name, Pairs* pairs); // Дисплей. Параметры: value (текст), color, fontSize, rows + параметры виджета Widget& Display(AnyValue text); Widget& Display_(AnyText name, AnyValue text); Widget& Display_(AnyText name, Pairs* pairs); // Картинка. Параметры: value (путь) + параметры виджета Widget& Image(AnyText text); Widget& Image_(AnyText name, AnyText text); Widget& Image_(AnyText name, Pairs* pairs); // Лог. value(текст), rows + параметры виджета Widget& Log(gh::Log* ptr); Widget& Log_(AnyText name, gh::Log* ptr); // Светодиод. Параметры: value (состояние 1/0), color + параметры виджета Widget& LED(AnyPtr ptr); Widget& LED_(AnyText name, AnyPtr ptr); // Светодиод-иконка. Параметры: value (состояние 1/0), icon, fontSize, color + параметры виджета Widget& Icon(AnyPtr ptr); Widget& Icon_(AnyText name, AnyPtr ptr); // Индикаторная шкала. Параметры: value (значение), range, unit, color + параметры виджета Widget& Gauge(AnyPtr ptr); Widget& Gauge_(AnyText name, AnyPtr ptr); // Индикаторная шкала круглая. Параметры: value (значение), range, unit, color + параметры виджета Widget& GaugeRound(AnyPtr ptr); Widget& GaugeRound_(AnyText name, AnyPtr ptr); // Индикаторная шкала линейная. Параметры: value (значение), icon, range, unit, color + параметры виджета Widget& GaugeLinear(AnyPtr ptr); Widget& GaugeLinear_(AnyText name, AnyPtr ptr); // Таблица. Параметры: value (текст или путь) + параметры виджета // text: таблица в формате CSV - разделитель столбцов ; разделитель строк \n // width: ширина, список чисел в процентах (например "30;30;50") // align: выравнивание, список из left | center | right (например "left;right") Widget& Table(AnyText text, AnyText width, AnyText align); Widget& Table_(AnyText name, AnyText text, AnyText width, AnyText align); ``` -------------------------------- ### Displaying Widgets Based on Menu Selection (b.show) C++ Source: https://github.com/gyverlibs/gyverhub/blob/main/docs/4.widgets.md Shows the recommended way to conditionally display widgets based on menu selection using `b.show()`. This method ensures all widgets are known to the builder for proper naming and state management, even if not currently displayed. The final `b.show()` without arguments resets the display state. ```cpp b.show(b.menu() == 0); b.Spinner(); b.show(b.menu() == 1); b.Slider(); b.show(b.menu() == 2); b.Input(); b.show(); ``` -------------------------------- ### Creating Dynamic Buttons in GyverHub C++ Source: https://github.com/gyverlibs/gyverhub/blob/main/docs/4.widgets.md Demonstrates how to create multiple buttons dynamically within a loop using `gh::Row` and `gh::Button`. Each button's click event is checked, printing its index to the serial monitor. ```cpp void build(gh::Builder& b) { { gh::Row r(b); for (int i = 0; i < 5; i++) { if (b.Button().click()) { Serial.print("Button #"); Serial.println(i); } } } } ``` -------------------------------- ### Adding Custom Fields to GyverHub Info Tab with onInfo (C++) Source: https://github.com/gyverlibs/gyverhub/blob/main/docs/8.advanced.md Shows how to utilize the `onInfo` handler to add custom key-value pairs to the different sections (Version, Network, Memory, System) of the Info tab within the GyverHub web interface. The handler receives a `gh::Info` object which indicates the section being populated, allowing conditional addition of information. ```cpp void info(gh::Info& info) { switch (info.type) { case gh::Info::Type::Version: info.add("Module", "v123"); break; case gh::Info::Type::Network: info.add(F("5G"), "50%"); break; case gh::Info::Type::Memory: info.add(F("SD"), "10 GB"); break; case gh::Info::Type::System: info.add(F("Battery"), 3.63, 2); info.add("ur mom", "120kg"); break; } } void setup() { hub.onInfo(info); } ``` -------------------------------- ### Creating Tabs in GyverHub C++ Source: https://github.com/gyverlibs/gyverhub/blob/main/docs/4.widgets.md Illustrates how to create tabbed sections in the control panel using the `b.Tabs()` widget. It connects the tabs to a static byte variable `tab` and defines the tab titles. A click on a tab triggers a panel refresh. ```cpp void build(gh::Builder& b) { static byte tab; if (b.Tabs(&tab).text("Spinner;Slider;Input").click()) b.refresh(); // обновить по клику // далее switch(tab) или b.show(tab == x)... } ``` -------------------------------- ### Displaying Widgets Based on Menu Selection (Switch) C++ Source: https://github.com/gyverlibs/gyverhub/blob/main/docs/4.widgets.md Demonstrates conditionally displaying different widgets (Spinner, Slider, Input) based on the currently selected menu item index using a `switch` statement on `b.menu()`. This method may lead to state synchronization issues across multiple clients. ```cpp switch (b.menu()) { case 0: b.Spinner(); break; case 1: b.Slider(); break; case 2: b.Input(); break; } ``` -------------------------------- ### Configuring GyverHub Widget Parameters (C++) Source: https://github.com/gyverlibs/gyverhub/blob/main/docs/1.main.md Methods available to configure properties of a GyverHub Widget object. These methods allow setting visual attributes like size, label, color, font size, and alignment, as well as functional properties like value binding, ranges, units, regex validation, and attaching action callbacks or flags. ```cpp // ===================== BLOCK ===================== // Ширина (относительно) и высота (px) виджета Widget& size(uint16_t width, uint16_t height = 0); // Заголовок виджета Widget& label(AnyText str); // Убрать заголовок виджета Widget& noLabel(bool nolabel = true); // Дополнительный заголовок виджета справа Widget& suffix(AnyText str); // Убрать задний фон виджета Widget& noTab(bool notab = true); // Сделать виджет квадратным Widget& square(bool square = true); // Отключить виджет Widget& disabled(bool disable = true); // Подсказка виджета. Пустая строка - убрать подсказку Widget& hint(AnyText str); // ===================== CUSTOM ===================== // int/string/bool поле Widget& param(AnyText key, AnyValue val); // float поле Widget& param(AnyText key, double val, uint8_t dec); // ===================== VALUE ===================== // привязать переменную как значение Widget& valueVar(AnyPtr data); // int/string/bool значение Widget& value(AnyValue val); // float значение Widget& value(double val, uint8_t dec); // ===================== TEXT ===================== // текст Widget& text(AnyText str); // иконка (glyph или unicode) https://fontawesome.com/v5/search?o=r&m=free&s=solid Widget& icon(AnyText str); // максимальная длина текста Widget& maxLen(uint16_t len); // ===================== MISC ===================== // количество строк поля текста Widget& rows(uint16_t rows); // regex для Input и Pass Widget& regex(AnyText str); // выравнивание текста для label/title Widget& align(gh::Align align); // минимум, максимум и шаг изменения значения (float) Widget& range(double min, double max, double step, uint8_t dec = 2); // минимум, максимум и шаг изменения значения (целые числа) template Widget& range(T min, T max, T step); // единицы измерения Widget& unit(AnyText str); // размер шрифта/кнопки Widget& fontSize(uint16_t size); // цвет uint32_t 24 бит Widget& color(uint32_t color); // цвет gh::Colors Widget& color(gh::Colors col); // Действие (обновить файл, вызвать Confirm/Prompt) Widget& action(bool act = 1); // ===================== ACTION ===================== // Проверка на клик по виджету bool click(); // ===================== ATTACH ===================== // Подключить функцию вида void f() Widget& attach(void (*cb)()); // Подключить функцию вида void f(gh::Build& build) Widget& attach(void (*cb)(gh::Build& build)); // Подключить функцию вида void f(gh::Builder& build) Widget& attach(void (*cb)(gh::Builder& build), gh::Builder& b); // Подключить gh::Flag* флаг Widget& attach(gh::Flag* flag); // Подключить bool* флаг Widget& attach(bool* flag); ``` -------------------------------- ### Public Member Variables (C++) Source: https://github.com/gyverlibs/gyverhub/blob/main/docs/1.main.md Lists public member variables of the main GyverHub class, representing configuration, state (like current menu), and internal components such as bridges, modules, stream handler, and MQTT handler. ```cpp uint8_t menu; // номер текущего пункта меню String prefix = ""; String name = ""; String icon = ""; String version = ""; const char* id; gh::Bridge* bridges[GH_BRIDGE_AMOUNT]; Modules modules; gh::HubStream stream; HubMQTT mqtt; ``` -------------------------------- ### Adding Menu Items in GyverHub C++ Source: https://github.com/gyverlibs/gyverhub/blob/main/docs/4.widgets.md Shows how to add custom items to the GyverHub application's dropdown menu using the `b.Menu()` widget. Menu items are specified as a semicolon-separated string and the widget can only be called once per builder. ```cpp void build(gh::Builder& b) { b.Menu("Spinner;Slider;Input"); } ``` -------------------------------- ### Connecting Dynamic Sliders to an Array in GyverHub C++ Source: https://github.com/gyverlibs/gyverhub/blob/main/docs/4.widgets.md Illustrates how to connect multiple dynamically created slider widgets to elements of a `uint16_t` array. This is the recommended approach for managing state with dynamic widgets. ```cpp uint16_t sliders[5]; void build() { for (int i = 0; i < 5; i++) { b.Slider(&sliders[i]); } } ``` -------------------------------- ### Setting Widget Width with size() in GyverHub C++ Source: https://github.com/gyverlibs/gyverhub/blob/main/docs/4.widgets.md Demonstrates using the `size()` method to control the relative width of widgets within a horizontal container. Widgets distribute the available space proportionally based on their assigned sizes. ```cpp void build(gh::Builder& b) { { gh::Row r(b); b.Slider().size(3); // слайдер шириной 3 b.Button().size(1); // кнопка шириной 1 b.Button(); // тоже 1 } } ``` -------------------------------- ### gh::Connection Enum (C++) Source: https://github.com/gyverlibs/gyverhub/blob/main/docs/1.main.md Defines the gh::Connection enumeration, listing various connection types supported by the system, such as Serial, Bluetooth, WS, MQTT, HTTP, Telegram, and System. ```cpp Serial Bluetooth WS MQTT HTTP Telegram System ``` -------------------------------- ### Canvas Drawing Methods (C++) Source: https://github.com/gyverlibs/gyverhub/blob/main/docs/1.main.md Provides a collection of methods for drawing shapes, text, and images on a canvas, along with state management functions like save and restore. Includes methods for rectangles, paths, curves, arcs, transformations, and text/image rendering. ```cpp Canvas& strokeRect(int x, int y, int w, int h); // очистить область Canvas& clearRect(int x, int y, int w, int h); // залить Canvas& fill(); // обвести Canvas& stroke(); // начать путь Canvas& beginPath(); // переместить курсор Canvas& moveTo(int x, int y); // завершить путь (провести линию на начало) Canvas& closePath(); // нарисовать линию от курсора Canvas& lineTo(int x, int y); // ограничить область рисования // https://www.w3schools.com/tags/canvas_clip.asp Canvas& clip(); // провести кривую // https://www.w3schools.com/tags/canvas_quadraticcurveto.asp Canvas& quadraticCurveTo(int cpx, int cpy, int x, int y); // провести кривую Безье // https://www.w3schools.com/tags/canvas_beziercurveto.asp Canvas& bezierCurveTo(int cp1x, int cp1y, int cp2x, int cp2y, int x, int y); // провести дугу (радианы) // https://www.w3schools.com/tags/canvas_arc.asp Canvas& arc(int x, int y, int r, float sa = 0, float ea = TWO_PI, bool ccw = 0); // скруглить // https://www.w3schools.com/tags/canvas_arcto.asp Canvas& arcTo(int x1, int y1, int x2, int y2, int r); // масштабировать область рисования // https://www.w3schools.com/tags/canvas_scale.asp Canvas& scale(int sw, int sh); // вращать область рисования (в радианах) // https://www.w3schools.com/tags/canvas_rotate.asp Canvas& rotate(float v); // перемещать область рисования // https://www.w3schools.com/tags/canvas_translate.asp Canvas& translate(int x, int y); // вывести закрашенный текст, опционально макс. длина Canvas& fillText(AnyText text, int x, int y, int w = 0); // вывести обведённый текст, опционально макс. длина Canvas& strokeText(AnyText text, int x, int y, int w = 0); // вывести картинку // https://www.w3schools.com/tags/canvas_drawimage.asp Canvas& drawImage(AnyText img, int x, int y); Canvas& drawImage(AnyText img, int x, int y, int w); Canvas& drawImage(AnyText img, int x, int y, int w, int h); Canvas& drawImage(AnyText img, int sx, int sy, int sw, int sh, int x, int y, int w, int h); // сохранить конфигурацию полотна Canvas& save(); // восстановить конфигурацию полотна Canvas& restore(); ``` -------------------------------- ### gh::Build Class Definition (C++) Source: https://github.com/gyverlibs/gyverhub/blob/main/docs/1.main.md Defines the gh::Build class, representing a build action or request within GyverHub. It contains information about the action type, client, component name and value, and provides methods to check if it's a set action or a UI request, and to retrieve the value in different data types (Color, Flags, Pos). ```cpp const Action action; // тип билда Client& client; // клиент const AnyText name; // имя компонента const AnyText value; // значение компонента bool isSet(); // билд-действие bool isUI(); // билд-запрос виджетов Color valueColor(); // получить значение как Color Flags valueFlags(); // получить значение как Flags Pos valuePos(); // получить значение как Pos ``` -------------------------------- ### Retrieving UI Builder Data (C++) Source: https://github.com/gyverlibs/gyverhub/blob/main/docs/1.main.md Functions to retrieve data constructed by the UI builder. Allows fetching the full UI JSON, a JSON object of widget values, or the value of a specific component by name. ```cpp // получить полный JSON пакет панели управления. Флаг enclose true - обернуть в результат в [] String getUI(bool enclose = false); // получить JSON объект {имя:значение, ...} виджетов (из билдера) String getValues(); // получить значение компонента по имени (из билдера) String getValue(AnyText name); ``` -------------------------------- ### gh::FS Class Definition (C++) Source: https://github.com/gyverlibs/gyverhub/blob/main/docs/1.main.md Defines the gh::FS class, providing an interface for file system operations within GyverHub. It includes methods for opening files in different modes, managing the file system lifecycle (begin, end, mounted, format), removing/renaming files, checking existence, querying space usage, managing directories, and listing/showing files. ```cpp File openRead(String path); File openAdd(String path); File openWrite(String path); bool begin(); void end(); bool mounted(); void format(); bool remove(String path, bool remdir = true); bool rename(String from, String to); bool exists(String path); uint64_t freeSpace(); uint64_t totalSpace(); uint64_t usedSpace(); void mkdir(String path); void rmdir(String path); void listDir(String& str, String path, char div); void showFiles(String& answ, String path, uint8_t levels = 0, uint32_t* count = nullptr); ``` -------------------------------- ### Canvas Class Methods (C++) Source: https://github.com/gyverlibs/gyverhub/blob/main/docs/1.main.md Provides a comprehensive set of methods for drawing on a canvas, including functions for buffer management, custom JS code, background, fill, stroke, primitive shapes, text, state management, and methods mirroring the HTML Canvas API. ```cpp // подключить внешний буфер void setBuffer(ghc::Packet* pp); // добавить строку кода на js Canvas& custom(AnyText text); // ===================================================== // =============== PROCESSING-LIKE API ================= // ===================================================== // =================== BACKGROUND ====================== // очистить полотно Canvas& clear(); // залить полотно установленным в fill() цветом Canvas& background(); // залить полотно указанным цветом (цвет, прозрачность) Canvas& background(uint32_t hex, uint8_t a = 255); // ======================== FILL ======================= // выбрать цвет заливки (цвет, прозрачность) Canvas& fill(uint32_t hex, uint8_t a = 255); // отключить заливку Canvas& noFill(); // ===================== STROKE ==================== // выбрать цвет обводки (цвет, прозрачность) Canvas& stroke(uint32_t hex, uint8_t a = 255); // отключить обводку Canvas& noStroke(); // толщина обводки, px Canvas& strokeWeight(int v); // соединение линий: CV::MITER (умолч), CV::BEVEL, CV::ROUND Canvas& strokeJoin(CV v); // края линий: CV::PROJECT (умолч), CV::ROUND, CV::SQUARE Canvas& strokeCap(CV v); // ===================== PRIMITIVES ==================== // окружность (x, y, радиус), px Canvas& circle(int x, int y, int r); // линия (координаты начала и конца) Canvas& line(int x1, int y1, int x2, int y2); // точка Canvas& point(int x, int y); // четырёхугольник (координаты углов) Canvas& quadrangle(int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4); // треугольник (координаты углов) Canvas& triangle(int x1, int y1, int x2, int y2, int x3, int y3); // прямоугольник Canvas& rect(int x, int y, int w, int h, int tl = -1, int tr = -1, int br = 0, int bl = 0); // квадрат Canvas& square(int x, int y, int w); // режим окружности: CV::CENTER (умолч), CV::CORNER Canvas& ellipseMode(CV mode); // режим прямоугольника: CV::CORNER (умолч), CV::CORNERS, CV::CENTER, CV::RADIUS Canvas& rectMode(CV mode); // ======================= TEXT ======================== // шрифт Canvas& textFont(const char* name); // размер шрифта, px Canvas& textSize(int size); // вывести текст, опционально макс длина Canvas& text(String text, int x, int y, int w = 0); // выравнивание текста // CV::LEFT, CV::CENTER, CV::RIGHT // TXT_TOP, TXT_BOTTOM, TXT_CENTER, TXT_BASELINE Canvas& textAlign(CV h, CV v); // сохранить конфигурацию полотна Canvas& push(); // восстановить конфигурацию полотна Canvas& pop(); // ====================================================== // ================== HTML CANVAS API =================== // ====================================================== // цвет заполнения Canvas& fillStyle(uint32_t hex, uint8_t a = 255); // цвет обводки Canvas& strokeStyle(uint32_t hex, uint8_t a = 255); // цвет тени Canvas& shadowColor(uint32_t hex, uint8_t a = 255); // размытость тени, px Canvas& shadowBlur(int v); // отступ тени, px Canvas& shadowOffsetX(int v); // отступ тени, px Canvas& shadowOffsetY(int v); // края линий: CV::BUTT (умолч), CV::ROUND, CV::SQUARE // https://www.w3schools.com/tags/canvas_linecap.asp Canvas& lineCap(CV v); // соединение линий: CV::MITER (умолч), CV::BEVEL, CV::ROUND // https://www.w3schools.com/tags/canvas_linejoin.asp Canvas& lineJoin(CV v); // ширина линий, px Canvas& lineWidth(int v); // длина соединения CV::MITER, px // https://www.w3schools.com/tags/canvas_miterlimit.asp Canvas& miterLimit(int v); // шрифт: "30px Arial" // https://www.w3schools.com/tags/canvas_font.asp Canvas& font(AnyText v); // выравнивание текста: CV::START (умолч), CV::END, CV::CENTER, CV::LEFT, CV::RIGHT // https://www.w3schools.com/tags/canvas_textalign.asp Canvas& textAlign(CV v); // позиция текста: CV::ALPHABETIC (умолч), CV::TOP, CV::HANGING, CV::MIDDLE, CV::IDEOGRAPHIC, CV::BOTTOM // https://www.w3schools.com/tags/canvas_textbaseline.asp Canvas& textBaseline(CV v); // прозрачность рисовки, 0.0-1.0 Canvas& globalAlpha(float v); // тип наложения графики: CV::SRC_OVER (умолч), CV::SRC_ATOP, CV::SRC_IN, CV::SRC_OUT, CV::DST_OVER, CV::DST_ATOP, CV::DST_IN, CV::DST_OUT, CV::LIGHTER, CV::COPY, CV::XOR // https://www.w3schools.com/tags/canvas_globalcompositeoperation.asp Canvas& globalCompositeOperation(CV v); // прямоугольник Canvas& drawRect(int x, int y, int w, int h); // скруглённый прямоугольник Canvas& roundRect(int x, int y, int w, int h, int tl = 0, int tr = -1, int br = -1, int bl = -1); // закрашенный прямоугольник Canvas& fillRect(int x, int y, int w, int h); // обведённый прямоугольник ``` -------------------------------- ### gh::Reboot Enum (C++) Source: https://github.com/gyverlibs/gyverhub/blob/main/docs/1.main.md Defines the gh::Reboot enumeration, specifying different types of reboot actions, including None, Button, Ota, and OtaUrl. ```cpp None Button Ota OtaUrl ``` -------------------------------- ### ghc::Modules Class Definition (C++) Source: https://github.com/gyverlibs/gyverhub/blob/main/docs/1.main.md Defines the ghc::Modules class, used for managing a set of modules represented by a 16-bit integer bitmask. It provides methods to set, clear, set all, clear all, and read the state of individual modules. ```cpp uint16_t mods = 0; void set(uint16_t nmods); void clear(uint16_t nmods); void setAll(); void clearAll(); bool read(gh::Module m); bool read(uint16_t m); ``` -------------------------------- ### CanvasUpdate Class (C++) Source: https://github.com/gyverlibs/gyverhub/blob/main/docs/1.main.md Defines the CanvasUpdate class used for managing and sending canvas updates. It includes a constructor to initialize the update with a name, hub, and optional client, and a send method to dispatch the update. ```cpp gh::CanvasUpdate(AnyText name, GyverHub* hub, Client* client = nullptr); // отправить void send(); ``` -------------------------------- ### Default Vertical Layout in GyverHub C++ Source: https://github.com/gyverlibs/gyverhub/blob/main/docs/4.widgets.md Shows the default layout behavior in the main `build` function, where widgets are placed one below the other in a vertical arrangement. ```cpp void build(gh::Builder& b) { // мы находимся в вертикальном контейнере b.Button(); b.Button(); } ``` -------------------------------- ### Creating Horizontal Row with GH_ROW Macro in GyverHub C++ Source: https://github.com/gyverlibs/gyverhub/blob/main/docs/4.widgets.md Demonstrates creating a horizontal container using the `GH_ROW` macro. This macro simplifies the syntax and allows specifying the container's width directly. ```cpp void build(gh::Builder& b) { GH_ROW(b, 1, b.Button(); b.Button(); ); } ``` -------------------------------- ### Creating Horizontal Row with beginRow/endRow in GyverHub C++ Source: https://github.com/gyverlibs/gyverhub/blob/main/docs/4.widgets.md Shows how to create a horizontal container using the `beginRow()` and `endRow()` methods. Widgets placed between these calls will be arranged horizontally. It emphasizes the need to call `endRow()`. ```cpp void build(gh::Builder& b) { b.beginRow(); // начать контейнер b.Button(); b.Button(); b.endRow(); // ВАЖНО НЕ ЗАБЫТЬ ЕГО ЗАВЕРШИТЬ } ``` -------------------------------- ### Naming Dynamic Switches with String Concatenation (Discouraged) C++ Source: https://github.com/gyverlibs/gyverhub/blob/main/docs/4.widgets.md Shows how to dynamically name switch widgets using string concatenation with a loop. This method is mentioned as not recommended for dynamic widgets in GyverHub due to potential naming conflicts. ```cpp for (int i = 0; i < 5; i++) { b.Switch_(String(F("sw")) + i); } ``` -------------------------------- ### gh::CMD Enum (C++) Source: https://github.com/gyverlibs/gyverhub/blob/main/docs/1.main.md Defines the gh::CMD enumeration, representing a comprehensive list of commands or message types used for communication within the GyverHub system. ```cpp UI Ping Unfocus Info Files Format Reboot FetchNext Data Set Get Read CLI Delete Rename Create FsAbort Fetch Upload UploadChunk Ota OtaChunk OtaUrl Unix Search Discover Unknown ``` -------------------------------- ### Handling File Upload Completion with GyverHub onUpload (C++) Source: https://github.com/gyverlibs/gyverhub/blob/main/docs/8.advanced.md Explains how to use the `onUpload` handler to receive notifications when a file upload from the GyverHub application to the device's memory is completed. The handler function is called with the path where the uploaded file was saved on the device. ```cpp void upl(String& path) { Serial.print("Uploaded: "); Serial.println(path); } void setup() { hub.onUpload(upl); } ``` -------------------------------- ### gh::Request Class Definition (C++) Source: https://github.com/gyverlibs/gyverhub/blob/main/docs/1.main.md Defines the gh::Request class, representing a request received from a client. It contains information about the client, the command type (CMD), and the name and value associated with the request. ```cpp Client& client; // клиент const CMD cmd; // событие AnyText name; // имя AnyText value; // значение ``` -------------------------------- ### gh::Client Class Definition (C++) Source: https://github.com/gyverlibs/gyverhub/blob/main/docs/1.main.md Defines the gh::Client class, representing a connected client in GyverHub. It stores the connection type and a unique client ID. ```cpp // тип подключения Connection connection(); // id клиента AnyText id; ``` -------------------------------- ### gh::Bridge Class Definition (C++) Source: https://github.com/gyverlibs/gyverhub/blob/main/docs/1.main.md Defines the gh::Bridge class used for managing connections and parsing data within GyverHub. It includes methods for configuration, parsing incoming data, handling connection lifecycle (begin, end, tick), sending data, and managing connection state and focus. ```cpp Bridge(void* hub, Connection conn, ghc::ParseHook parse); // настроить void config(void* hub, Connection conn, ghc::ParseHook parse); // парсить url=data или url + data отдельно void parse(AnyText url, AnyText data); virtual void begin(){}; virtual void end(){}; virtual void tick(){}; virtual void send(BridgeData& data){}; Connection connection(); // тип подключения void enable(); // включить void disable(); // выключить bool state(); // статус включен или выключен void setFocus(); // установить focus void clearFocus(); // снять focus bool getFocus(); // получить focus ``` -------------------------------- ### Checking Button Click with GyverHub C++ Source: https://github.com/gyverlibs/gyverhub/blob/main/docs/4.widgets.md Demonstrates how to check if a button widget was clicked using the `click()` method. This method returns `true` when the button is activated and should be the last call in a chain as it returns a boolean. ```cpp if (b.Button().click()) Serial.println("click 1"); ``` -------------------------------- ### Setting Container Width with gh::Row Constructor in GyverHub C++ Source: https://github.com/gyverlibs/gyverhub/blob/main/docs/4.widgets.md Illustrates how to set the relative width of nested horizontal containers by passing a width parameter to the `gh::Row` constructor. Containers distribute space proportionally based on their specified widths. ```cpp void build(gh::Builder& b) { { gh::Row r(b); { // этот контейнер будет в 2 раза шире... gh::Row r(b, 2); b.Button(); b.Button(); } { // ...чем этот gh::Row r(b, 1); b.Button(); b.Button(); } } } ``` -------------------------------- ### Creating Horizontal Row with beginRow/endRow in If Block in GyverHub C++ Source: https://github.com/gyverlibs/gyverhub/blob/main/docs/4.widgets.md Presents an alternative pattern for creating a horizontal container using `beginRow()` within an `if` statement. This provides a clear scope for the row's contents and ensures `endRow()` is called upon exiting the block. ```cpp void build(gh::Builder& b) { // для удобства можно обернуть контейнер в блок {} // функции beginRow() и beginCol() всегда возвращают true if (b.beginRow()) { b.Button(); b.Button(); b.endRow(); // завершить } } ```