Engineering manual

Section 1: System Architecture & Kiosk Management

The VendoFlex / GalaxyVend Monolithic Core is a self-contained, single-instance Java server. It bridges the customer-facing HTMX kiosk interface (/kiosk), the local administration web panel (/admin), a MySQL persistence layer, and hardware peripheral controllers (MDB/Pulse/Keypress boards) over either local Serial (/dev/ttyUSB0 at 115200 baud) or MQTT (vaas/in/... and vaas/out/...). It also maintains a secure outbound WebSocket (wss://) connection to the central cloud gateway for real-time telemetry and daily/lifetime financial counter synchronization.

1. Admin Dashboard Navigation & Overview

Accessing http://<kiosk-ip>:9191/admin loads the GalaxyVend Admin interface. The top of the left navigation sidebar displays the active MySQL database schema currently bound to the instance (e.g., self_001).

 

Kiosk dashboard (click to enlarge)

 

Kiosk configuration (click to enlarge)

The sidebar provides direct access to seven operational modules:

  • Kiosks: Configure virtual/physical kiosk terminals, UI layouts, idle timeouts, JSON parameters, and Lua coin-return workflows.
  • Devices: Register hardware controller boards (by MAC/Hardware Serial Number) and bind them to specific Kiosk IDs.
  • Categories: Manage product groupings with multi-language labels and JPEG/PNG icons (up to 256 KB).
  • Products: Define items, prices (in cents), selection numbers, stock levels, and custom Lua dispensing/payment state machines.
  • RFID Cards: Manage pre-paid NFC/RFID tag balances and UIDs.
  • Telemetry: Inspect raw inbound and outbound hardware commands (COININ, BILLSTACKED, VNDREQ, etc.).b4j
  • Sales: Filter and audit completed financial events (CASHSALE, CARDSALE, COINAPDONE) with interval totals.

2. Kiosks Registry & Configuration

The Kiosks Registry (Kiosks tab) lists all configured kiosk instances alongside their ID, Location Name, Default Language, and Active Status.

  • Click + New Kiosk to provision a new terminal, or click the Edit (pencil) icon next to an existing entry (such as Kiosk #2 — Lab Testing Laundry) to modify its parameters.

Important Note on RAM Caching: At startup (BootstrapActiveEcosystem), the server loads all kiosks where kiosk_active = 1 and their bound devices into RAM (KioskCache and DeviceCache). Any changes saved in the Kiosk or Device editors are written directly to MySQL and require a service restart (or toggling Service Mode) to refresh the active in-memory state machines.2

Core Kiosk Fields

FieldType / OptionsEngineering Behavior & Constraints
Location NameTextHuman-readable identifier displayed in registries and dropdowns.
API KeyStringUnique authentication token (kiosk_api_key) required by the frontend UI when posting HTMX requests to /kiosk/api.
Display Type0 or 1

0 - Direct Products: Boots straight into the product grid.

1 - Categories First: Displays active categories first; selecting a category filters the product grid.

Default LanguageEN, DE, FR, IT, ES, RO, BGBase UI language. If a user switches languages on the top bar, the UI automatically reverts to this language after the idle timeout expires.
Category ColumnsIntegerSets the CSS grid column count (--cols) on the category selection screen.
Product ColumnsIntegerSets the CSS grid column count (--cols) on the product selection screen.
Timeout (Sec)IntegerIdle inactivity timer (kiosk_timeout_sec). When reached, any open sub-view resets to the main idle screen and reverts to the default language.
RFID Display (Sec)IntegerDuration (kiosk_rfid_display_sec) that an RFID card's credit balance or the hardware IP info overlay remains visible before returning to idle.
Active StatusActive / InactiveOnly kiosks set to Active (1) are loaded into memory during engine boot.
Location DescriptionTextareaOptional administrative notes or physical installation details.

3. Kiosk Config (JSON)

Expanding the Kiosk Config (JSON) drawer inside the Kiosk Edit modal exposes advanced runtime parameters parsed during system boot:

{
    "currency": "EUR",
    "has_change": 1,
    "max_change": 250,
    "mode": "modular_mall",
    "default_selection_number": 40
}
  • currency (String): Currency code or symbol appended to all formatted prices on the UI (e.g., "EUR", "RON", "$"). Leave empty ("") for unitless display.
  • has_change (0 or 1): Enables (1) or disables (0) coin changer payout capability. When enabled, the Change button appears on the bottom bar—and physical change-return signals (COINCHGREQ, CHANGEPRESSED) are accepted—only when SalePerformed == 1 and AccumulatedCreditCents > 0.
  • max_change (Integer, in cents): Upper safety limit for coin dispensing. If AccumulatedCreditCents exceeds max_change (e.g., 250 = 2.50 EUR), automated change payout is inhibited and logged. Set to 0 for unlimited change.
  • mode (String): Operational profile identifier (e.g., "modular_mall").
  • default_selection_number (Integer): Maps physical hardware payment buttons (PAYCASHPRESSED or PAYCARDPRESSED) on the idle screen directly to a default product selection number (e.g., 40). Set to -1 to ignore standalone physical payment button presses.

4. Change Workflow (Lua State Machine)

Expanding Change Workflow (Lua) lets you define the hardware execution sequence triggered when a customer requests change. The engine uses Luaj to execute execute_stage(stage), starting at stage = 1.

function execute_stage(stage)
    if stage == 1 then
        return {
            execstage = 1,
            kioskid = 2,
            devicesn = "6825ddd01ce0",
            opcode = "COINAP",
            params = {"$ACCUMULATED_CREDIT$"},
            posans = "COINAPOK",
            posstage = 10,
            negans = "COINAPFAIL",
            negstage = 990,
            tmt = 10000,
            tmtstage = 990,
            loadpage = "messages.html",
            pagemsg = "dispensing_change",
            pageparams = {"$ACCUMULATED_CREDIT$"},
            actions = {}
        }
    elseif stage == 10 then
        return {
            execstage = 10,
            kioskid = 2,
            devicesn = "6825ddd01ce0",
            opcode = "",
            params = {},
            gotostage = 999,
            aftersleep = 3000,
            loadpage = "messages.html",
            pagemsg = "change_dispensed",
            pageparams = {},
            actions = {
                "$ACCUMULATED_CREDIT$ = 0",
                "$SALE_PERFORMED$ = 0"
            }
        }
    elseif stage == 990 then
        return {
            execstage = 990,
            kioskid = 2,
            devicesn = "6825ddd01ce0",
            opcode = "",
            params = {},
            gotostage = 999,
            aftersleep = 3000,
            loadpage = "messages.html",
            pagemsg = "change_failed",
            pageparams = {},
            actions = {}
        }
    elseif stage == 999 then
        return {
            execstage = 999,
            kioskid = 2,
            devicesn = "6825ddd01ce0",
            opcode = "",
            params = {},
            loadpage = "main.html",
            pagemsg = "",
            pageparams = {},
            actions = {}
        }
    end
end

Stage Execution Breakdown

  1. Stage 1 (Payout Command): Dispatches COINAP(<accumulated_credit>) to controller 6825ddd01ce0 and renders the localized dispensing_change message on screen.
    • On COINAPOK → transitions to Stage 10.
    • On COINAPFAIL or a 10000 ms (10s) timeout (tmt) → transitions to Stage 990.
  2. Stage 10 (Payout Confirmed): Displays change_dispensed for 3000 ms (aftersleep), resets $ACCUMULATED_CREDIT$ and $SALE_PERFORMED$ to 0, and jumps (gotostage) to Stage 999.
  3. Stage 990 (Payout Failed / Timeout): Displays change_failed for 3000 ms without clearing the customer's remaining credit balance, then jumps to Stage 999.
  4. Stage 999 (Workflow Exit): Loads main.html, resetting the state machine (CurrentStageID = -1) and returning the terminal to the idle product/category screen.

Section 2: Peripheral Devices Registry & Hardware Binding

The Devices Registry (Devices tab in the left navigation bar) manages the physical controller boards (ESP32 / MDB / Pulse / Keypress interfaces) that execute hardware commands and report peripheral telemetry back to the VendoFlex core.

Because a single Kiosk terminal can orchestrate multiple vending machines or payment peripherals simultaneously (such as a multi-machine modular mall), each controller board is registered individually and bound to a parent Kiosk ID.

1. Devices Registry Overview

Navigating to Devices opens the registry table displaying all provisioned hardware controllers sorted by descending database ID:

Devices dashboard (click to enlarge)
Devices details edit (click to enlarge)
  • ID: Auto-incremented internal database primary key.
  • Serial Number: Unique hardware identifier (typically the controller's lowercase MAC address, such as 6825ddd01ce0 or b0cbd8d2ac94, or an identifier like development).
  • Assigned Kiosk: Displays a badge linking the board to its parent Kiosk (#2 - Lab Testing Laundry), or Unassigned if not yet mapped.
  • Status: Indicates whether the controller is Active or Inactive.
  • Actions: Click the Edit (pencil) button to modify device credentials and kiosk bindings, or click the Delete (trash) icon to remove the record after confirmation. Click + New Device in the top-right corner to register a new board.

2. Device Configuration & Credentials

Clicking + New Device or editing an existing entry (such as Edit Device #17) opens the device configuration modal:

FieldFormat / TypeEngineering Behavior & Constraints
Device Serial (MAC/Hardware SN)String (Required)The exact hardware serial number (serial_number) used for MQTT topic routing (vaas/out/<customer_sn>/<serial_number>) and referenced by devicesn inside Lua workflow scripts. During bootstrap, the engine normalizes this value to lowercase and trims whitespace.
Customer SNString (Required)Tenant/customer account identifier (customer_sn, e.g., Bpj59JBtkW2zx5M0). Used as the first routing segment on outbound MQTT topics and recorded in all mall_payment_telemetry database entries.
API KeyString (Required)Hardware authentication token (api_key) assigned to the controller board.
Assigned KioskDropdownMaps the board to a target kiosk_id (e.g., #2 - Lab Testing Laundry) or -- Unassigned -- (NULL). When inbound telemetry arrives from this serial number, the engine routes events directly to the assigned Kiosk's state machine.
StatusActive / InactiveControls whether the device is loaded into RAM at boot (is_active = 1).

3. Communication Modes & Routing Architecture

During startup (BootstrapActiveEcosystem), the core queries all devices where is_active = 1 that are assigned to an active kiosk, instantiating a clsDeviceInstance object in DeviceCache for each board.

The engine routes outbound commands (CmdRoot(param1,param2)\r\n) and inbound telemetry across two transport modes depending on the --serial_port startup argument:

  1. MQTT Mode (--serial_port=none):
    • Inbound: Subscribes to <mqtt_topic>in/+/+ (default vaas/in/+/+), extracting CustomerSN from topic segment 2 and DeviceSN from topic segment 3.
    • Outbound: Publishes ASCII commands to <mqtt_topic>out/<CustomerSN>/<DeviceSN> (with DeviceSN forced to lowercase). This allows one kiosk server to address multiple independent boards by specifying different devicesn values in Lua workflow stages.
  2. Direct Serial Mode (e.g., --serial_port=/dev/ttyUSB0):
    • Communicates over UART at 115200 baud (8N1), framing messages with CRLF (\r\n).
    • Because a serial link does not carry topic headers, incoming messages with an empty device serial automatically resolve to the first cached device in DeviceCache.

Operational Note: Just like Kiosk settings, device bindings and is_active flags are cached in RAM on boot. After adding a new board, changing its serial number, or toggling its status between Active and Inactive, restart the core service (or cycle Service Mode) so DeviceCache reloads the updated hardware topology.


Section 3: Product Categories & Localization

The Categories Registry (Categories tab in the left navigation bar) organizes products into navigable storefront groups. When a Kiosk is configured with Display Type = 1 - Categories First, the customer-facing touchscreen renders active categories as the initial entry grid before revealing the products assigned to each category.

1. Categories Registry Overview

Opening the Categories view displays all configured product groups sorted alphabetically by their English name (category_name_en):

Categories dashboard (click to enlarge)
Categories edit (click to enlarge)
  • ID: Internal auto-incremented database primary key (category_id).
  • POS ID: External Point-of-Sale mapping identifier (category_pos_id, defaults to -1 when unused).
  • Name (EN / RO): Displays the primary English title in bold with the Romanian translation underneath for rapid bilingual verification.
  • Assigned Kiosk: Indicates which Kiosk terminal displays this category (#2 - Lab Testing Laundry).
  • Status: Shows whether the category is Active or Inactive. Only categories set to Active (1) are queried and rendered on the customer UI.
  • Actions: Click the Edit (pencil) button to modify labels, translations, or artwork, or click the Delete (trash) icon to remove the category after SweetAlert2 confirmation. Click + New Category to create a new grouping.

Grid Sorting Tip: On the customer kiosk screen, categories are ordered alphabetically (ORDER BY cat_name ASC) according to the currently selected UI language. Prefixing category names with numbers (e.g., 1. Regular tokens, 2. Buy subscription card, 3. Subscription recharge) enforces a deterministic visual order across all languages.

2. Category Configuration & Multi-Language Fields

Clicking + New Category or editing an existing record (such as Edit Category #1) opens the category editor modal:

FieldFormat / ConstraintsEngineering Behavior & UI Rendering
Assigned KioskDropdown (Required)Binds the category to a specific kiosk_id. The customer UI filters categories strictly by the active Kiosk's ID.
Category POS IDString (Required)External integration or ERP/POS reference ID (default -1).
Active StatusActive / InactiveToggles storefront visibility (category_active: 1 = visible, 0 = hidden) without deleting historical product associations.
Category ImageImage File (Max: 256 KB)Uploaded via the browser file picker, validated client-side against the 256 KB limit, Base64-encoded, and stored directly in MySQL as a BLOB (category_image). Leave empty during edits to preserve the existing image.
Name (EN, RO, DE, FR, IT, ES, BG)StringLocalized category titles rendered on the storefront cards when a user selects the corresponding flag in the top bar.
Description (EN, RO, DE, FR, IT, ES, BG)TextareaLocalized descriptive metadata stored per language (category_description_<lang>).

3. Image Streaming & Fallback Behavior

Unlike Kiosk and Device settings—which are cached in RAM at boot—categories are queried live from MySQL (RenderCategoriesGrid) whenever the kiosk renders its main screen, meaning category edits and status toggles take effect immediately on the next UI refresh.

  • Direct BLOB Streaming: Category thumbnails are served dynamically by the core HTTP engine at /kiosk/api/image?type=category&id=<category_id>&kiosk_api_key=<key> with Content-Type: image/jpeg.
  • Automatic Icon Fallback: If a category has no uploaded image BLOB (or the endpoint returns 404), the frontend <img> tag automatically falls back to assets/fa/svgs/solid/folder-open.svg so the grid layout never breaks.

Section 4: Products Registry & Lua Transaction Workflows

The Products Registry (Products tab in the left navigation bar) defines every purchasable item, service, token bundle, RFID card top-up, or timed relay output available on a kiosk. Each product binds storefront metadata (pricing, multi-language descriptions, images) to an executable Lua State Machine (product_workflow) that orchestrates hardware checks, payment collection, dispensing, and telemetry logging.

1. Products Registry Overview

Opening Products displays all configured items sorted alphabetically by English name (product_name_en):

Products dashboard (click to enlarge)
Products edit (click to enlarge)
  • ID / POS ID: Internal database primary key (product_id) and external Point-of-Sale mapping ID (product_pos_id).
  • Name (EN / RO): Primary English title in bold with the Romanian translation below.
  • Sel #: The unique Selection Number (product_selection_number) per kiosk. Selection numbers link touchscreen buttons, physical keypad buttons (101 + BtnIdx), default_selection_number triggers, and outbound vending requests (CSLS1VNDREQ, CSLS1CASHSALE, CSLS1VNDSUCC) to the specific product record.
  • Price: Displayed in major currency units in the registry table (product_price / 100.0, e.g., 250 cents displays as 2.5).
  • Stock: Current inventory count (product_current_stock).
  • Status: Active items appear on the customer storefront; Inactive items are hidden.
  • Actions: Click the Edit (pencil) icon to open the product configuration modal, or click Delete (trash) to remove the item. Click + New Product to create a new entry.

2. Product Configuration Fields

Clicking + New Product or editing an existing item (such as Edit Product #16 — 1 Token EN) opens the product editor:

FieldFormat / TypeEngineering Behavior & Constraints
Assigned KioskDropdown (Required)Maps the product to product_kiosk_id.
CategoryDropdown (Required)Assigns the product to category_id when the kiosk uses Display Type = 1 (Categories First).
POS IDStringExternal ERP/POS reference identifier (product_pos_id).
Selection NumberIntegerUnique selection index (product_selection_number, e.g., 20). Physical keypad buttons map automatically to 101–108 (101 + BtnIdx for 0..7).
Price (Cents)IntegerProduct price stored in integer minor units (e.g., 250 = 2.50 EUR).
StockIntegerCurrent inventory counter (product_current_stock).
Active StatusActive / InactiveControls storefront visibility (product_active = 1 or 0).
Product ImageFile (Max: 256 KB)Stored as a BLOB in MySQL and streamed via /kiosk/api/image?type=product&id=<product_id>. Falls back to assets/fa/svgs/solid/box.svg if empty.
Name (EN–BG)StringLocalized product titles across all 7 supported languages.
Details (EN–BG)TextareaExtended product descriptions displayed when a customer taps the Details button on a product card.
Product Workflow (Lua)Lua ScriptRaw Lua state machine script (product_workflow) loaded dynamically into Luaj when a transaction starts.

3. Product Lua Workflow Architecture

When a customer selects a product and chooses a payment method on the kiosk UI (or triggers a physical payment button), HandleTransactionStart loads the product's product_workflow Lua script and invokes execute_stage(StartStage):

  • CASH payment starts at stage == 1.
  • CARD payment starts at stage == 2.
  • XVEND payment starts at stage == 3.

Reference Implementation: Multi-Payment Token Dispenser (Product #16)

Below is a complete production workflow for dispensing 2 tokens from ccTalk hopper channel 3 using controller 6825ddd01ce0, supporting both Cash (stage 1) and Cashless/Card (stage 2) paths with hardware health checks and telemetry reporting:

function execute_stage(stage)
    if stage == 1 then
        return {
            execstage = 1,
            kioskid = 2,
            devicesn = "6825ddd01ce0",
            opcode = "CCTHENABLED",
            params = {3},
            posans = "CCTHENABLED(3,1)",
            posstage = 5,
            negans = "CCTHENABLED(3,0)",
            negstage = 994,
            tmt = 5000,
            tmtstage = 994,
            loadpage = "messages.html",
            pagemsg = "please_wait",
            pageparams = {},
            actions = {}
        }
    elseif stage == 2 then
        return {
            execstage = 2,
            kioskid = 2,
            devicesn = "6825ddd01ce0",
            opcode = "CCTHENABLED",
            params = {3},
            posans = "CCTHENABLED(3,1)",
            posstage = 6,
            negans = "CCTHENABLED(3,0)",
            negstage = 994,
            tmt = 5000,
            tmtstage = 994,
            loadpage = "messages.html",
            pagemsg = "please_wait",
            pageparams = {},
            actions = {}
        }
    elseif stage == 5 then
        return {
            execstage = 5,
            kioskid = 2,
            devicesn = "6825ddd01ce0",
            opcode = "CCTHSTOCK",
            params = {3},
            posans = "CCTHSTOCK(3,1)",
            posstage = 10,
            negans = "CCTHSTOCK(3,0)",
            negstage = 994,
            tmt = 5000,
            tmtstage = 994,
            loadpage = "messages.html",
            pagemsg = "please_wait",
            pageparams = {},
            actions = {}
        }
    elseif stage == 6 then
        return {
            execstage = 6,
            kioskid = 2,
            devicesn = "6825ddd01ce0",
            opcode = "CCTHSTOCK",
            params = {3},
            posans = "CCTHSTOCK(3,1)",
            posstage = 12,
            negans = "CCTHSTOCK(3,0)",
            negstage = 994,
            tmt = 5000,
            tmtstage = 994,
            loadpage = "messages.html",
            pagemsg = "please_wait",
            pageparams = {},
            actions = {}
        }
    elseif stage == 10 then
        return {
            execstage = 10,
            kioskid = 2,
            devicesn = "6825ddd01ce0",
            opcode = "GETCASH",
            params = {"$REQUIRED_PRICE$", 30},
            posans = "GETCASHOK",
            posstage = 11,
            negans = "GETCASHFAIL",
            negstage = 990,
            tmt = 10000,
            tmtstage = 990,
            loadpage = "messages.html",
            pagemsg = "please_wait",
            pageparams = {},
            actions = {}
        }
    elseif stage == 11 then
        return {
            execstage = 11,
            kioskid = 2,
            devicesn = "6825ddd01ce0",
            opcode = "",
            params = {},
            posans = "GETCASHFULLYRECEIVED",
            posstage = 20,
            negans = "GETCASHTIMEOUT",
            negstage = 990,
            tmt = 30000,
            tmtstage = 990,
            loadpage = "messages.html",
            pagemsg = "insert_cash",
            pageparams = {"$PRODUCT_PRICE$", "$ACCUMULATED_CREDIT$"},
            actions = {}
        }
    elseif stage == 12 then
        return {
            execstage = 12,
            kioskid = 2,
            devicesn = "6825ddd01ce0",
            opcode = "CSLS1VNDREQ",
            params = {"$PRODUCT_PRICE$", "$SELECTION_NUMBER$"},
            posans = "CSLS1VNDREQOK",
            posstage = 13,
            negans = "CSLS1VNDREQFAIL",
            negstage = 993,
            tmt = 10000,
            tmtstage = 993,
            loadpage = "messages.html",
            pagemsg = "please_wait",
            pageparams = {},
            actions = {}
        }
    elseif stage == 13 then
        return {
            execstage = 13,
            kioskid = 2,
            devicesn = "6825ddd01ce0",
            opcode = "",
            params = {},
            posans = "CSLS1VNDAPP",
            posstage = 22,
            negans = "CSLS1VNDDEN",
            negstage = 993,
            tmt = 60000,
            tmtstage = 993,
            loadpage = "messages.html",
            pagemsg = "present_card",
            pageparams = {"$PRODUCT_PRICE$"},
            actions = {}
        }
    elseif stage == 20 then
        return {
            execstage = 20,
            kioskid = 2,
            devicesn = "6825ddd01ce0",
            opcode = "CCTHDISPENSE",
            params = {3, 1, 2},
            posans = "CCTHDISPENSESTART",
            posstage = 30,
            negans = "CCTHDISPENSEFAIL",
            negstage = 991,
            tmt = 5000,
            tmtstage = 991,
            loadpage = "messages.html",
            pagemsg = "payment_successful",
            pageparams = {},
            actions = {}
        }
    elseif stage == 22 then
        return {
            execstage = 22,
            kioskid = 2,
            devicesn = "6825ddd01ce0",
            opcode = "CCTHDISPENSE",
            params = {3, 1, 2},
            posans = "CCTHDISPENSESTART",
            posstage = 32,
            negans = "CCTHDISPENSEFAIL",
            negstage = 52,
            tmt = 5000,
            tmtstage = 52,
            loadpage = "messages.html",
            pagemsg = "payment_successful",
            pageparams = {},
            actions = {}
        }
    elseif stage == 30 then
        return {
            execstage = 30,
            kioskid = 2,
            devicesn = "6825ddd01ce0",
            opcode = "",
            params = {},
            posans = "CCTHFULLPAID",
            posstage = 40,
            negans = "CCTHPARTPAID",
            negstage = 992,
            tmt = 20000,
            tmtstage = 992,
            loadpage = "messages.html",
            pagemsg = "wait_product_dispensing",
            pageparams = {},
            actions = {}
        }
    elseif stage == 32 then
        return {
            execstage = 32,
            kioskid = 2,
            devicesn = "6825ddd01ce0",
            opcode = "",
            params = {},
            posans = "CCTHFULLPAID",
            posstage = 50,
            negans = "CCTHPARTPAID",
            negstage = 52,
            tmt = 20000,
            tmtstage = 52,
            loadpage = "messages.html",
            pagemsg = "wait_product_dispensing",
            pageparams = {},
            actions = {}
        }
    elseif stage == 40 then
        return {
            execstage = 40,
            kioskid = 2,
            devicesn = "6825ddd01ce0",
            opcode = "CSLS1CASHSALE",
            params = {"$PRODUCT_PRICE$", "$SELECTION_NUMBER$"},
            posans = "CSLS1CASHSALEOK",
            posstage = 999,
            negans = "CSLS1CASHSALEFAIL",
            negstage = 999,
            tmt = 3000,
            tmtstage = 999,
            aftersleep = 3000,
            gotostage = 999,
            loadpage = "messages.html",
            pagemsg = "sale_success",
            pageparams = {"$PRODUCT_NAME$", "$ACCUMULATED_CREDIT$"},
            actions = {
                "$ACCUMULATED_CREDIT$ = $ACCUMULATED_CREDIT$ - $PRODUCT_PRICE$",
                "$SALE_PERFORMED$ = 1"
            }
        }
    elseif stage == 50 then
        return {
            execstage = 50,
            kioskid = 2,
            devicesn = "6825ddd01ce0",
            opcode = "CSLS1VNDSUCC",
            params = {"$SELECTION_NUMBER$"},
            posans = "CSLS1VNDSUCCOK",
            posstage = 51,
            negans = "CSLS1VNDSUCCFAIL",
            negstage = 51,
            tmt = 5000,
            tmtstage = 51,
            loadpage = "messages.html",
            pagemsg = "payment_successful",
            pageparams = {},
            actions = {}
        }
    elseif stage == 51 then
        return {
            execstage = 51,
            kioskid = 2,
            devicesn = "6825ddd01ce0",
            opcode = "",
            params = {},
            posans = "",
            posstage = -1,
            negans = "",
            negstage = -1,
            tmt = -1,
            tmtstage = -1,
            aftersleep = 8000,
            gotostage = 999,
            loadpage = "messages.html",
            pagemsg = "sale_success",
            pageparams = {"$PRODUCT_NAME$"},
            actions = {}
        }
    elseif stage == 52 then
        return {
            execstage = 52,
            kioskid = 2,
            devicesn = "6825ddd01ce0",
            opcode = "CSLS1VNDFAIL",
            params = {},
            posans = "CSLS1VNDFAILOK",
            posstage = 991,
            negans = "CSLS1VNDFAILFAIL",
            negstage = 991,
            tmt = 5000,
            tmtstage = 991,
            loadpage = "messages.html",
            pagemsg = "dispensing_failed",
            pageparams = {},
            actions = {}
        }
    elseif stage == 990 then
        return {
            execstage = 990,
            kioskid = 2,
            devicesn = "6825ddd01ce0",
            opcode = "",
            params = {},
            posans = "",
            posstage = -1,
            negans = "",
            negstage = -1,
            tmt = -1,
            tmtstage = -1,
            aftersleep = 3000,
            gotostage = 999,
            loadpage = "messages.html",
            pagemsg = "cash_failed",
            pageparams = {},
            actions = {}
        }
    elseif stage == 991 then
        return {
            execstage = 991,
            kioskid = 2,
            devicesn = "6825ddd01ce0",
            opcode = "",
            params = {},
            posans = "",
            posstage = -1,
            negans = "",
            negstage = -1,
            tmt = -1,
            tmtstage = -1,
            aftersleep = 3000,
            gotostage = 999,
            loadpage = "messages.html",
            pagemsg = "dispensing_failed",
            pageparams = {},
            actions = {}
        }
    elseif stage == 992 then
        return {
            execstage = 992,
            kioskid = 2,
            devicesn = "6825ddd01ce0",
            opcode = "",
            params = {},
            posans = "",
            posstage = -1,
            negans = "",
            negstage = -1,
            tmt = -1,
            tmtstage = -1,
            aftersleep = 3000,
            gotostage = 999,
            loadpage = "messages.html",
            pagemsg = "sale_failed",
            pageparams = {},
            actions = {}
        }
    elseif stage == 993 then
        return {
            execstage = 993,
            kioskid = 2,
            devicesn = "6825ddd01ce0",
            opcode = "",
            params = {},
            posans = "",
            posstage = -1,
            negans = "",
            negstage = -1,
            tmt = -1,
            tmtstage = -1,
            aftersleep = 3000,
            gotostage = 999,
            loadpage = "messages.html",
            pagemsg = "card_payment_fail",
            pageparams = {},
            actions = {}
        }
    elseif stage == 994 then
        return {
            execstage = 994,
            kioskid = 2,
            devicesn = "6825ddd01ce0",
            opcode = "",
            params = {},
            posans = "",
            posstage = -1,
            negans = "",
            negstage = -1,
            tmt = -1,
            tmtstage = -1,
            aftersleep = 3000,
            gotostage = 999,
            loadpage = "messages.html",
            pagemsg = "product_not_available",
            pageparams = {},
            actions = {}
        }
    elseif stage == 999 then
        return {
            execstage = 999,
            kioskid = 2,
            devicesn = "6825ddd01ce0",
            opcode = "",
            params = {},
            posans = "",
            posstage = -1,
            negans = "",
            negstage = -1,
            tmt = -1,
            tmtstage = -1,
            loadpage = "main.html",
            pagemsg = "",
            pageparams = {},
            actions = {}
        }
    end
end

Execution Flow & Engine Mechanics

  1. Pre-Flight Hardware & Stock Verification (Stages 1, 2, 5, 6):
    • Both payment paths first verify that ccTalk hopper 3 is enabled (CCTHENABLED(3) expecting CCTHENABLED(3,1)) and has physical inventory (CCTHSTOCK(3) expecting CCTHSTOCK(3,1)), routing immediately to Stage 994 (product_not_available) if the peripheral is offline, empty, or times out after 5000 ms.
  2. Cash Branch (Stages 10 → 11 → 20 → 30 → 40):
    • Credit Calculation (Stage 10): Sends GETCASH($REQUIRED_PRICE$, 30). The engine dynamically computes $REQUIRED_PRICE$ = max(0, SelectedProductPrice - AccumulatedCreditCents). If the user already holds sufficient credit from a prior overpayment ($REQUIRED_PRICE$ == 0), the engine short-circuits straight to posstage (Stage 11) without waiting for new bill/coin insertion.
    • Dispensing & Settlement (Stages 20, 30, 40): Once GETCASHFULLYRECEIVED arrives (Stage 11), CCTHDISPENSE(3,1,2) triggers the hopper. Upon CCTHFULLPAID, Stage 40 emits CSLS1CASHSALE (recording a CASHSALE event locally and to the cloud WebSocket), deducts the product price from $ACCUMULATED_CREDIT$, and sets $SALE_PERFORMED$ = 1—unlocking the Change button if residual credit remains.
  3. Card / Cashless Branch (Stages 12 → 13 → 22 → 32 → 50 → 51):
    • POS Authorization (Stages 12, 13): Sends CSLS1VNDREQ($PRODUCT_PRICE$, $SELECTION_NUMBER$) to the MDB/cashless terminal and displays present_card for up to 60000 ms.
    • Vending Confirmation / Reversal (Stages 22, 32, 50, 52): If CSLS1VNDAPP approves the charge, the hopper dispenses. On CCTHFULLPAID, Stage 50 sends CSLS1VNDSUCC($SELECTION_NUMBER$) to finalize the card settlement (CARDSALE). If the hopper fails (CCTHDISPENSEFAIL or CCTHPARTPAID), Stage 52 transmits CSLS1VNDFAIL to void/cancel the cashless session on the reader before displaying dispensing_failed (Stage 991).

Supported Workflow Variables, Actions & Built-in Opcodes

  • Runtime Placeholders (params & pageparams):
    • $PRODUCT_PRICE$: Price of the active product in cents.
    • $ACCUMULATED_CREDIT$: Current user credit balance in cents.
    • $REQUIRED_PRICE$ / $PRICE_DUE$: Remaining balance needed (max(0, ProductPrice - AccumulatedCredit)).
    • $SELECTION_NUMBER$: Product's selection index.
    • $PRODUCT_NAME$: Localized product name.
    • $SALE_PERFORMED$: 1 if a sale completed in the current session, otherwise 0.
  • State Actions (actions array):
    • Arithmetic assignments using +, -, *, / on $ACCUMULATED_CREDIT$, $PRODUCT_PRICE$, and $SALE_PERFORMED$ (e.g., "$ACCUMULATED_CREDIT$ = $ACCUMULATED_CREDIT$ - $PRODUCT_PRICE$").
    • "$RECHARGE_RFID$" (or "$RECHARGE_CARD$"): Credits AccumulatedCreditCents onto the last scanned RFID card UID (LastScannedTagSn) in the rfid_cards table.
  • Special Timed Relay Opcode (RELAY):
    • Sending opcode = "RELAY" with params = {ch_a, ch_b, ch_c, ch_d, duration_sec} (e.g., for dryers/washers) validates up to 4 unique relay channels (1..10, 0 = unused), locks the product card on the UI with a live MM:SS countdown timer (ActiveRelayTimers), dispatches the command to hardware, and returns the kiosk immediately to the idle screen.

Section 5: RFID Cards Registry & Closed-Loop Credit Architecture

The RFID Cards Registry (RFID Cards tab in the left navigation bar) manages contactless NFC/RFID loyalty and subscription tags used across the kiosk ecosystem. Unlike external bank cards, RFID tag balances are maintained centrally inside the local MySQL database (rfid_cards), enabling instant balance inquiries, kiosk top-ups, and closed-loop hardware deductions without external payment gateway latency.

1. RFID Cards Registry Overview

Opening RFID Cards lists all registered and auto-discovered contactless tags sorted alphabetically by their hexadecimal Tag Serial (tag_sn):

RFID Subscriptions dashboard (click to enlarge)
RFID Subscriptions edit (click to enlarge)
  • ID: Auto-incremented internal database primary key (card_id).
  • Tag Serial (Hex): The unique hardware UID reported by the RFID reader (e.g., 1aabde29, ae9da89c).
  • Credit Balance: Current stored value formatted in major currency units with two decimal places (credit_cents / 100.0, e.g., 233.00).
  • Created / Last Updated: Automatic SQL timestamps (created_at and updated_at) tracking when the card first entered the registry and when its balance was last modified.
  • Actions: Click the Edit (pencil) button to manually adjust a card's UID or credit balance, or click Delete (trash) to purge the record after confirmation. Click + New Card to pre-register a tag manually.

2. Manual Card Provisioning & Balance Adjustment

Clicking + New Card or editing an existing tag (such as Edit Card #19) opens the card editor modal:

FieldFormat / TypeEngineering Behavior & Database Storage
Tag UID / Serial Number (Hex)String (Required)Hexadecimal tag identifier (tag_sn), automatically trimmed of leading/trailing whitespace on save. Must match the exact string transmitted by the reader firmware in RDRBEGIN(<tag_sn>).
Credit BalanceDecimal (step="0.01")Entered in standard major currency units (e.g., 10.00) and converted automatically on save via Round(creditVal * 100) into integer cents (credit_cents = 1000).

3. Hardware Protocol & Closed-Loop Lifecycle

The core engine interacts directly with peripheral RFID readers across four real-time hardware events:

  1. Idle Balance Check & Auto-Registration (RDRBEGIN(<tag_sn>)):
    • When a customer taps a tag while the kiosk is idle (CurrentStageID == -1), the engine queries rfid_cards for tag_sn.
    • Zero-Touch Provisioning: If the tag UID does not yet exist in the database, the engine automatically inserts a new record with credit_cents = 0.
    • The engine switches the screen to stage 8888, displaying the localized current_rfid_available_credit banner for the duration configured in RFID Display (Sec) (kiosk_rfid_display_sec), and logs RDRBEGIN both locally and to the cloud WebSocket (SendSaleStat2).
    • When the card leaves the field (RDRLEAVING), active RFID session registers clear.
  2. Kiosk Top-Up / Recharge ($RECHARGE_RFID$):
    • When a product workflow executes "$RECHARGE_RFID$" (or "$RECHARGE_CARD$") in its actions array, the engine adds AccumulatedCreditCents onto LastScannedTagSn in rfid_cards (or creates the record if missing).
  3. Pre-Authorization Credit Check (RDRSUBCREDIT(<tag_sn>,<amount_cents>)):
    • Peripheral controllers (such as standalone washers, dryers, or vending slaves) can request closed-loop debit authorization by sending RDRSUBCREDIT.
    • If the tag's credit_cents is greater than 0 and >= RequestedAmountCents, the core immediately responds to the requesting board with RDRSUBCREDITOK(<tag_sn>,<amount_cents>)\r\n. If funds are insufficient, no approval frame is sent.
  4. Confirmed Balance Deduction (RDRPULSEEXECUTED(<tag_sn>,<amount_cents>)):
    • Once the peripheral board confirms physical pulse or service delivery, it transmits RDRPULSEEXECUTED, prompting the core to execute UPDATE rfid_cards SET credit_cents = MAX(0, credit_cents - ?), updated_at = CURRENT_TIMESTAMP WHERE tag_sn = ?.

Section 6: Payment & Event Telemetry Audit Log

The Payment & Event Telemetry view (Telemetry tab in the left navigation bar) provides a chronological, low-level diagnostic log of all inbound and outbound hardware commands recorded in the mall_payment_telemetry MySQL table. Engineers and administrators use this log to trace exact transaction lifecycles, verify cash acceptor pulses, inspect cashless reader handshakes, and debug Lua state-machine transitions.

Telemetry dashboard (click to enlarge)

1. Date Filtering & Query Controls

At the top of the Payment & Event Telemetry card, the filter bar controls the queried timestamp window:

  • From / To (start_date / end_date): Defaults to the current system date (yyyy-MM-dd) covering 00:00:00.000 through 23:59:59.999.
  • Filter: Executes an HTMX POST request to /admin/api/telemetry/list and updates the table in-place.
  • Reset: Clears custom date inputs and reloads today's event stream.
  • Record Limit: Results are sorted newest-first (ORDER BY event_timestamp DESC, event_id DESC) and capped at 30,000 rows per query to protect browser responsiveness.

2. Telemetry Table Schema

Each row corresponds to an atomic hardware or synthesized accounting event stored in mall_payment_telemetry:

ColumnDatabase FieldFormat & Engineering Details
IDevent_idAuto-incremented primary key.
Device SNdevice_snLowercase serial number of the originating or target peripheral controller (e.g., 6825ddd01ce0).
Timestampevent_timestampEpoch milliseconds formatted as yyyy-MM-dd HH:mm:ss.
CommandcommandUppercase root opcode extracted prior to any parameter parentheses (e.g., RDRBEGIN, BILLSTACKED, CASHSALE).
Amountamount_centsRaw integer value in minor currency units (cents). Non-monetary events such as RDRBEGIN record -1, while status frames like CREDITS record 0.
Payloadraw_payloadComplete unparsed ASCII command string received from or transmitted to the peripheral board.

3. Logged Command Categories & Synthetic Accounting Events

The core engine (RecordFinancialEvent and RecordOutboundEvent) selectively persists critical payment, vending, and diagnostic commands to MySQL while filtering out high-frequency polling noise:

  • Cash Acceptance & Escrow: BILLSTACKED, COININ, CASHFULLYRECEIVED, CREDITS, BILLDISABLED, COINDISABLED.
    • Example from log: BILLSTACKED(1000,961,199700) logs amount_cents = 1000 (10.00 major units) alongside the bill validator's internal cumulative counters.
  • Cashless / MDB Reader Handshakes: CSLS1VNDREQ, CSLS2VNDREQ, VNDREQ, CSLS1VNDAPP, CSLS2VNDAPP, CSLS1VNDSUCC, CSLS2VNDSUCC, CSLS1VNDSUCCOK, CSLS2VNDSUCCOK.
  • Cash Sale & Dispenser Confirmations: CSLS1CASHSALE, CSLS2CASHSALE, CSLS1CASHSALEOK, CSLS2CASHSALEOK, VENDSUCCESS, EXEVENDSUCCESS, EXEVENDFAIL.
  • RFID Tag Reads: RDRBEGIN (logs amount_cents = -1 and selection_number = -1, preserving the tag UID in raw_payload, e.g., RDRBEGIN(6025614d)).
  • Coin Changer Payouts: COINAP, COINAPOK.
  • Synthesized Normalized Ledger Records: Whenever the engine receives terminal confirmation opcodes from cashless or coin-changer channels, it automatically inserts a secondary standardized accounting row and forwards it over the cloud WebSocket (BackendWS):
    • CSLS1CASHSALE / CSLS1CASHSALEOK (or CSLS2...) → generates CASHSALE(<amount_cents>,<selection_number>) (e.g., CASHSALE(5000,32)).
    • CSLS1VNDSUCC / CSLS1VNDSUCCOK (or CSLS2...) → generates CARDSALE(<amount_cents>,<selection_number>).
    • COINAP / COINAPOK → generates COINAPDONE(<amount_cents>,-1).

Section 7: Sales & Financial Reconciliation

The Sales & Transactions view (Sales tab in the left navigation bar) provides a filtered financial ledger extracted from mall_payment_telemetry. While the Telemetry tab displays every low-level hardware handshake and pulse frame, the Sales module isolates finalized monetary settlements—cash purchases, card/cashless purchases, and dispensed change—and computes period totals for operator reconciliation.

Sales dashboard (click to enlarge)

1. Filtering & Date Range Controls

The top filter bar queries finalized financial records within a chosen date window:

  • From / To (start_date / end_date): Defaults to the current system date (yyyy-MM-dd), spanning 00:00:00.000 on the start date through 23:59:59.999 on the end date.
  • Operation (operation): Filters the transaction table by settlement type:
    • All Operations (all): Displays CASHSALE, CARDSALE, and COINAPDONE records combined.
    • Cash Sales (cash): Displays only CASHSALE transactions.
    • Card Sales (card): Displays only CARDSALE transactions.
    • Change (change): Displays only COINAPDONE coin-return events.
  • Filter / Reset: Submits the filter parameters via HTMX (POST /admin/api/sales/list) or resets the view back to today's full ledger. Queries return up to 30,000 rows ordered newest-first (ORDER BY event_timestamp DESC, event_id DESC).

2. Summary Totals Banner

Directly beneath the filter bar, three KPI cards display aggregate sums (COALESCE(SUM(amount_cents), 0) / 100.0) across the selected From / To date interval:

  • Total Cash Sales: Sum of all CASHSALE events in the interval (e.g., 50.00).
  • Total Card Sales: Sum of all CARDSALE events in the interval (e.g., 2.50).
  • Total Change: Sum of all COINAPDONE coin payouts dispensed in the interval (e.g., 0.00).

Important Note: The three summary cards always reflect the totals for the entire selected From / To date range, even when the Operation dropdown is narrowed to a single transaction type.

3. Transactions Table & Cloud Counter Synchronization

Each row in the ledger represents a synthesized accounting record generated by RecordFinancialEvent upon confirmed hardware settlement:

ColumnFormat / BadgeEngineering Details
IDInteger (event_id)Database primary key in mall_payment_telemetry.
Device SNMonospace StringLowercase serial number of the controller board that executed the transaction (e.g., 6825ddd01ce0).
Timestampyyyy-MM-dd HH:mm:ssLocal event timestamp (event_timestamp).
CommandColor-Coded BadgeCASHSALE (Green), CARDSALE (Blue), or COINAPDONE (Amber).
AmountDecimal (0.00)Formatted monetary value (amount_cents / 100.0, e.g., 50.00 or 2.50).
Payload<CMD>(<cents>,<sel#>)Normalized payload encoding the amount in cents and the purchased product's selection number (e.g., CASHSALE(5000,32) for Selection #32, CARDSALE(250,50) for Selection #50, or COINAPDONE(<cents>,-1) for change).

Cloud WebSocket Counter Push (PushTelemetryCounters)

In addition to real-time per-sale event forwarding (SendSaleStat), the core engine's clsWebSocketClient periodically computes cumulative daily (since midnight) and lifetime totals directly from these three mall_payment_telemetry commands—transmitting DAYCASHSALES, DAYCARDSALES, LIFECASHSALES, LIFECARDSALES, DAYCHANGE, and LIFECHANGE to the central gateway every counters_push heartbeat cycles.