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).


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 wherekiosk_active = 1and their bound devices into RAM (KioskCacheandDeviceCache). 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
| Field | Type / Options | Engineering Behavior & Constraints |
|---|---|---|
| Location Name | Text | Human-readable identifier displayed in registries and dropdowns. |
| API Key | String | Unique authentication token (kiosk_api_key) required by the frontend UI when posting HTMX requests to /kiosk/api. |
| Display Type | 0 or 1 |
|
| Default Language | EN, DE, FR, IT, ES, RO, BG | Base UI language. If a user switches languages on the top bar, the UI automatically reverts to this language after the idle timeout expires. |
| Category Columns | Integer | Sets the CSS grid column count (--cols) on the category selection screen. |
| Product Columns | Integer | Sets the CSS grid column count (--cols) on the product selection screen. |
| Timeout (Sec) | Integer | Idle 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) | Integer | Duration (kiosk_rfid_display_sec) that an RFID card's credit balance or the hardware IP info overlay remains visible before returning to idle. |
| Active Status | Active / Inactive | Only kiosks set to Active (1) are loaded into memory during engine boot. |
| Location Description | Textarea | Optional 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 whenSalePerformed == 1andAccumulatedCreditCents > 0.max_change(Integer, in cents): Upper safety limit for coin dispensing. IfAccumulatedCreditCentsexceedsmax_change(e.g.,250=2.50 EUR), automated change payout is inhibited and logged. Set to0for unlimited change.mode(String): Operational profile identifier (e.g.,"modular_mall").default_selection_number(Integer): Maps physical hardware payment buttons (PAYCASHPRESSEDorPAYCARDPRESSED) on the idle screen directly to a default product selection number (e.g.,40). Set to-1to 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
endStage Execution Breakdown
- Stage
1(Payout Command): DispatchesCOINAP(<accumulated_credit>)to controller6825ddd01ce0and renders the localizeddispensing_changemessage on screen.- On
COINAPOK→ transitions to Stage10. - On
COINAPFAILor a10000ms (10s) timeout (tmt) → transitions to Stage990.
- On
- Stage
10(Payout Confirmed): Displayschange_dispensedfor3000ms (aftersleep), resets$ACCUMULATED_CREDIT$and$SALE_PERFORMED$to0, and jumps (gotostage) to Stage999. - Stage
990(Payout Failed / Timeout): Displayschange_failedfor3000ms without clearing the customer's remaining credit balance, then jumps to Stage999. - Stage
999(Workflow Exit): Loadsmain.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:


- ID: Auto-incremented internal database primary key.
- Serial Number: Unique hardware identifier (typically the controller's lowercase MAC address, such as
6825ddd01ce0orb0cbd8d2ac94, or an identifier likedevelopment). - Assigned Kiosk: Displays a badge linking the board to its parent Kiosk (
#2 - Lab Testing Laundry), orUnassignedif not yet mapped. - Status: Indicates whether the controller is
ActiveorInactive. - 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:
| Field | Format / Type | Engineering 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 SN | String (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 Key | String (Required) | Hardware authentication token (api_key) assigned to the controller board. |
| Assigned Kiosk | Dropdown | Maps 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. |
| Status | Active / Inactive | Controls 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:
- MQTT Mode (
--serial_port=none):- Inbound: Subscribes to
<mqtt_topic>in/+/+(defaultvaas/in/+/+), extractingCustomerSNfrom topic segment 2 andDeviceSNfrom topic segment 3. - Outbound: Publishes ASCII commands to
<mqtt_topic>out/<CustomerSN>/<DeviceSN>(withDeviceSNforced to lowercase). This allows one kiosk server to address multiple independent boards by specifying differentdevicesnvalues in Lua workflow stages.
- Inbound: Subscribes to
- 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.
- Communicates over UART at 115200 baud (8N1), framing messages with
Operational Note: Just like Kiosk settings, device bindings and
is_activeflags are cached in RAM on boot. After adding a new board, changing its serial number, or toggling its status betweenActiveandInactive, restart the core service (or cycle Service Mode) soDeviceCachereloads 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):


- ID: Internal auto-incremented database primary key (
category_id). - POS ID: External Point-of-Sale mapping identifier (
category_pos_id, defaults to-1when 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
ActiveorInactive. Only categories set toActive(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:
| Field | Format / Constraints | Engineering Behavior & UI Rendering |
|---|---|---|
| Assigned Kiosk | Dropdown (Required) | Binds the category to a specific kiosk_id. The customer UI filters categories strictly by the active Kiosk's ID. |
| Category POS ID | String (Required) | External integration or ERP/POS reference ID (default -1). |
| Active Status | Active / Inactive | Toggles storefront visibility (category_active: 1 = visible, 0 = hidden) without deleting historical product associations. |
| Category Image | Image 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) | String | Localized 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) | Textarea | Localized 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>withContent-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 toassets/fa/svgs/solid/folder-open.svgso 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):


- 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_numbertriggers, 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.,250cents displays as2.5). - Stock: Current inventory count (
product_current_stock). - Status:
Activeitems appear on the customer storefront;Inactiveitems 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:
| Field | Format / Type | Engineering Behavior & Constraints |
|---|---|---|
| Assigned Kiosk | Dropdown (Required) | Maps the product to product_kiosk_id. |
| Category | Dropdown (Required) | Assigns the product to category_id when the kiosk uses Display Type = 1 (Categories First). |
| POS ID | String | External ERP/POS reference identifier (product_pos_id). |
| Selection Number | Integer | Unique selection index (product_selection_number, e.g., 20). Physical keypad buttons map automatically to 101–108 (101 + BtnIdx for 0..7). |
| Price (Cents) | Integer | Product price stored in integer minor units (e.g., 250 = 2.50 EUR). |
| Stock | Integer | Current inventory counter (product_current_stock). |
| Active Status | Active / Inactive | Controls storefront visibility (product_active = 1 or 0). |
| Product Image | File (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) | String | Localized product titles across all 7 supported languages. |
Details (EN–BG) | Textarea | Extended product descriptions displayed when a customer taps the Details button on a product card. |
| Product Workflow (Lua) | Lua Script | Raw 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):
CASHpayment starts atstage == 1.CARDpayment starts atstage == 2.XVENDpayment starts atstage == 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
endExecution Flow & Engine Mechanics
- Pre-Flight Hardware & Stock Verification (
Stages 1, 2, 5, 6):- Both payment paths first verify that ccTalk hopper
3is enabled (CCTHENABLED(3)expectingCCTHENABLED(3,1)) and has physical inventory (CCTHSTOCK(3)expectingCCTHSTOCK(3,1)), routing immediately toStage 994(product_not_available) if the peripheral is offline, empty, or times out after5000 ms.
- Both payment paths first verify that ccTalk hopper
- Cash Branch (
Stages 10 → 11 → 20 → 30 → 40):- Credit Calculation (
Stage 10): SendsGETCASH($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 toposstage(Stage 11) without waiting for new bill/coin insertion. - Dispensing & Settlement (
Stages 20, 30, 40): OnceGETCASHFULLYRECEIVEDarrives (Stage 11),CCTHDISPENSE(3,1,2)triggers the hopper. UponCCTHFULLPAID,Stage 40emitsCSLS1CASHSALE(recording aCASHSALEevent 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.
- Credit Calculation (
- Card / Cashless Branch (
Stages 12 → 13 → 22 → 32 → 50 → 51):- POS Authorization (
Stages 12, 13): SendsCSLS1VNDREQ($PRODUCT_PRICE$, $SELECTION_NUMBER$)to the MDB/cashless terminal and displayspresent_cardfor up to60000 ms. - Vending Confirmation / Reversal (
Stages 22, 32, 50, 52): IfCSLS1VNDAPPapproves the charge, the hopper dispenses. OnCCTHFULLPAID,Stage 50sendsCSLS1VNDSUCC($SELECTION_NUMBER$)to finalize the card settlement (CARDSALE). If the hopper fails (CCTHDISPENSEFAILorCCTHPARTPAID),Stage 52transmitsCSLS1VNDFAILto void/cancel the cashless session on the reader before displayingdispensing_failed(Stage 991).
- POS Authorization (
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$:1if a sale completed in the current session, otherwise0.
- State Actions (
actionsarray):- Arithmetic assignments using
+,-,*,/on$ACCUMULATED_CREDIT$,$PRODUCT_PRICE$, and$SALE_PERFORMED$(e.g.,"$ACCUMULATED_CREDIT$ = $ACCUMULATED_CREDIT$ - $PRODUCT_PRICE$"). "$RECHARGE_RFID$"(or"$RECHARGE_CARD$"): CreditsAccumulatedCreditCentsonto the last scanned RFID card UID (LastScannedTagSn) in therfid_cardstable.
- Arithmetic assignments using
- Special Timed Relay Opcode (
RELAY):- Sending
opcode = "RELAY"withparams = {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 liveMM:SScountdown timer (ActiveRelayTimers), dispatches the command to hardware, and returns the kiosk immediately to the idle screen.
- Sending
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):


- 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_atandupdated_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:
| Field | Format / Type | Engineering 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 Balance | Decimal (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:
- Idle Balance Check & Auto-Registration (
RDRBEGIN(<tag_sn>)):- When a customer taps a tag while the kiosk is idle (
CurrentStageID == -1), the engine queriesrfid_cardsfortag_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 localizedcurrent_rfid_available_creditbanner for the duration configured in RFID Display (Sec) (kiosk_rfid_display_sec), and logsRDRBEGINboth locally and to the cloud WebSocket (SendSaleStat2). - When the card leaves the field (
RDRLEAVING), active RFID session registers clear.
- When a customer taps a tag while the kiosk is idle (
- Kiosk Top-Up / Recharge (
$RECHARGE_RFID$):- When a product workflow executes
"$RECHARGE_RFID$"(or"$RECHARGE_CARD$") in itsactionsarray, the engine addsAccumulatedCreditCentsontoLastScannedTagSninrfid_cards(or creates the record if missing).
- When a product workflow executes
- 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_centsis greater than0and>= RequestedAmountCents, the core immediately responds to the requesting board withRDRSUBCREDITOK(<tag_sn>,<amount_cents>)\r\n. If funds are insufficient, no approval frame is sent.
- Peripheral controllers (such as standalone washers, dryers, or vending slaves) can request closed-loop debit authorization by sending
- 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 executeUPDATE rfid_cards SET credit_cents = MAX(0, credit_cents - ?), updated_at = CURRENT_TIMESTAMP WHERE tag_sn = ?.
- Once the peripheral board confirms physical pulse or service delivery, it transmits
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.

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) covering00:00:00.000through23:59:59.999. - Filter: Executes an HTMX POST request to
/admin/api/telemetry/listand 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:
| Column | Database Field | Format & Engineering Details |
|---|---|---|
| ID | event_id | Auto-incremented primary key. |
| Device SN | device_sn | Lowercase serial number of the originating or target peripheral controller (e.g., 6825ddd01ce0). |
| Timestamp | event_timestamp | Epoch milliseconds formatted as yyyy-MM-dd HH:mm:ss. |
| Command | command | Uppercase root opcode extracted prior to any parameter parentheses (e.g., RDRBEGIN, BILLSTACKED, CASHSALE). |
| Amount | amount_cents | Raw integer value in minor currency units (cents). Non-monetary events such as RDRBEGIN record -1, while status frames like CREDITS record 0. |
| Payload | raw_payload | Complete 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)logsamount_cents = 1000(10.00major units) alongside the bill validator's internal cumulative counters.
- Example from log:
- 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(logsamount_cents = -1andselection_number = -1, preserving the tag UID inraw_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(orCSLS2...) → generatesCASHSALE(<amount_cents>,<selection_number>)(e.g.,CASHSALE(5000,32)).CSLS1VNDSUCC/CSLS1VNDSUCCOK(orCSLS2...) → generatesCARDSALE(<amount_cents>,<selection_number>).COINAP/COINAPOK→ generatesCOINAPDONE(<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.

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), spanning00:00:00.000on the start date through23:59:59.999on the end date. - Operation (
operation): Filters the transaction table by settlement type:All Operations(all): DisplaysCASHSALE,CARDSALE, andCOINAPDONErecords combined.Cash Sales(cash): Displays onlyCASHSALEtransactions.Card Sales(card): Displays onlyCARDSALEtransactions.Change(change): Displays onlyCOINAPDONEcoin-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
CASHSALEevents in the interval (e.g.,50.00). - Total Card Sales: Sum of all
CARDSALEevents in the interval (e.g.,2.50). - Total Change: Sum of all
COINAPDONEcoin 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:
| Column | Format / Badge | Engineering Details |
|---|---|---|
| ID | Integer (event_id) | Database primary key in mall_payment_telemetry. |
| Device SN | Monospace String | Lowercase serial number of the controller board that executed the transaction (e.g., 6825ddd01ce0). |
| Timestamp | yyyy-MM-dd HH:mm:ss | Local event timestamp (event_timestamp). |
| Command | Color-Coded Badge | CASHSALE (Green), CARDSALE (Blue), or COINAPDONE (Amber). |
| Amount | Decimal (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.