### DXUI Page Navigation Example Source: https://dejaos.com/docs/ui/dxuipage This example demonstrates creating two main pages with buttons for navigation and a persistent top bar displaying the time. It utilizes `dxui.loadMain` to switch between pages on the Main layer while the Top layer remains visible. Ensure `dxui`, `dxstd`, and `dxlogger` modules are imported. ```javascript import dxui from "../dxmodules/dxUi.js"; import std from "../dxmodules/dxStd.js"; import logger from "../dxmodules/dxLogger.js"; dxui.init({ orientation: 1 }); const page1 = dxui.View.build("page1", dxui.Utils.LAYER.MAIN); const button1 = dxui.Button.build("page1button", page1); button1.setPos(100, 100); button1.setSize(200, 200); const buttonLabel1 = dxui.Label.build("page1label", button1); buttonLabel1.text("Open Page2"); buttonLabel1.setPos(10, 20); const page2 = dxui.View.build("page2", dxui.Utils.LAYER.MAIN); const button2 = dxui.Button.build("page2button", page2); button2.setPos(100, 100); button2.setSize(200, 200); button2.bgColor(0xff0000); const buttonLabel2 = dxui.Label.build("page2label", button2); buttonLabel2.text("Back Page1"); buttonLabel2.setPos(10, 20); button1.on(dxui.Utils.EVENT.CLICK, () => { dxui.loadMain(page2); }); button2.on(dxui.Utils.EVENT.CLICK, () => { dxui.loadMain(page1); }); page1.on(dxui.Utils.ENUM.LV_EVENT_SCREEN_LOADED, () => { logger.info("page1 loaded"); }); page1.on(dxui.Utils.ENUM.LV_EVENT_SCREEN_UNLOADED, () => { logger.info("page1 unloaded"); }); page2.on(dxui.Utils.ENUM.LV_EVENT_SCREEN_LOADED, () => { logger.info("page2 loaded"); }); page2.on(dxui.Utils.ENUM.LV_EVENT_SCREEN_UNLOADED, () => { logger.info("page2 unloaded"); }); const topview = dxui.View.build("topview", dxui.Utils.LAYER.TOP); topview.setPos(0, 0); topview.setSize(200, 30); topview.bgColor(0xcccccc); const topviewlabel = dxui.Label.build("topviewlabel", topview); topviewlabel.text("time"); dxui.loadMain(page1); std.setInterval(() => { topviewlabel.text(new Date().toLocaleTimeString()); }, 1000); std.setInterval(() => { dxui.handler(); }, 10); ``` -------------------------------- ### Complete Registration Flow Source: https://dejaos.com/docs/finger/dxFingerMz An example demonstrating the complete registration process, including initialization, auto-registration, and manual registration steps. ```javascript import dxFingerMz from './dxFingerMz.js'; // 1. Initialize dxFingerMz.init({ id: 'fingerUart', path: '/dev/ttySLB0', baudrate: '57600-8-N-2' }); // 2. Method 1: Auto registration (recommended) function autoEnroll(pageIndex) { const result = dxFingerMz.autoRegister(pageIndex, 2, 60, 0); if (result) { console.log('Auto registration successful'); return true; } else { console.log('Auto registration failed'); return false; } } // 3. Method 2: Manual registration function manualEnroll(pageIndex) { // First capture if (dxFingerMz.getEnrollImage() !== 0) { console.log('First capture failed'); return false; } if (dxFingerMz.genChar(1) !== 0) { console.log('First feature generation failed'); return false; } // Second capture if (dxFingerMz.getEnrollImage() !== 0) { console.log('Second capture failed'); return false; } if (dxFingerMz.genChar(2) !== 0) { console.log('Second feature generation failed'); return false; } // Merge features and store if (dxFingerMz.regModel() !== 0) { console.log('Template generation failed'); return false; } if (dxFingerMz.storeChar(1, pageIndex) !== 0) { console.log('Template storage failed'); return false; } console.log('Manual registration successful'); return true; } // Usage example autoEnroll(1); // Register to index 1 ``` -------------------------------- ### Image Transformation Example in dxUi Source: https://dejaos.com/docs/ui/lvglfunc Demonstrates creating and manipulating images using dxUi, including native LVGL function calls for rotation and scaling. ```javascript import dxui from "../dxmodules/dxUi.js"; import std from "../dxmodules/dxStd.js"; import logger from "../dxmodules/dxLogger.js"; dxui.init({ orientation: 1 }); const screenMain = dxui.View.build("pwdView", dxui.Utils.LAYER.MAIN); const image1 = dxui.Image.build("image1", screenMain); image1.source("/app/code/src/logo.png"); image1.setPos(10, 10); const image2 = dxui.Image.build("image2", screenMain); image2.source("/app/code/src/logo.png"); image2.setPos(300, 10); image2.obj.lvImgSetAngle(900); // 900 = 90 degrees const image3 = dxui.Image.build("image3", screenMain); image3.source("/app/code/src/logo.png"); image3.setPos(100, 400); image3.obj.lvImgSetZoom(512); // 256=100%, 512=200% dxui.loadMain(screenMain); std.setInterval(() => { dxui.handler(); }, 10); ``` -------------------------------- ### Complete dxUi Hello World Example Source: https://dejaos.com/docs/ui/getstart This snippet initializes dxUi, creates a main view, adds a button with a label, and sets up a click event handler. It also includes the necessary UI refresh loop. ```javascript import dxui from "../dxmodules/dxUi.js"; import std from "../dxmodules/dxStd.js"; import logger from "../dxmodules/dxLogger.js"; dxui.init({ orientation: 1 }); const screenMain = dxui.View.build("mainid", dxui.Utils.LAYER.MAIN); const button = dxui.Button.build("buttonid", screenMain); button.setPos(100, 400); button.setSize(400, 400); const buttonLabel = dxui.Label.build("buttonLabelid", button); buttonLabel.text("Click me"); buttonLabel.setPos(150, 200); button.on(dxui.Utils.EVENT.CLICK, () => { logger.info("Button clicked"); }); dxui.loadMain(screenMain); std.setInterval(() => { dxui.handler(); }, 10); ``` -------------------------------- ### Relative Layout Example with Alignment Source: https://dejaos.com/docs/ui/layout Demonstrates how to use relative layout to position a button in the center and then arrange labels around it using various alignment options. Ensure dxui modules are imported and initialized. ```javascript import dxui from "../dxmodules/dxUi.js"; import std from "../dxmodules/dxStd.js"; import logger from "../dxmodules/dxLogger.js"; dxui.init({ orientation: 1 }); const page1 = dxui.View.build("page1", dxui.Utils.LAYER.MAIN); const button1 = dxui.Button.build("page1button", page1); button1.align(dxui.Utils.ALIGN.CENTER, 0, 0); button1.setSize(200, 200); // All alignment enums const aligns = { OUT_TOP_LEFT: dxui.Utils.ALIGN.OUT_TOP_LEFT, OUT_TOP_MID: dxui.Utils.ALIGN.OUT_TOP_MID, OUT_TOP_RIGHT: dxui.Utils.ALIGN.OUT_TOP_RIGHT, OUT_BOTTOM_LEFT: dxui.Utils.ALIGN.OUT_BOTTOM_LEFT, OUT_BOTTOM_MID: dxui.Utils.ALIGN.OUT_BOTTOM_MID, OUT_BOTTOM_RIGHT: dxui.Utils.ALIGN.OUT_BOTTOM_RIGHT, OUT_LEFT_TOP: dxui.Utils.ALIGN.OUT_LEFT_TOP, OUT_LEFT_MID: dxui.Utils.ALIGN.OUT_LEFT_MID, OUT_LEFT_BOTTOM: dxui.Utils.ALIGN.OUT_LEFT_BOTTOM, OUT_RIGHT_TOP: dxui.Utils.ALIGN.OUT_RIGHT_TOP, OUT_RIGHT_MID: dxui.Utils.ALIGN.OUT_RIGHT_MID, OUT_RIGHT_BOTTOM: dxui.Utils.ALIGN.OUT_RIGHT_BOTTOM, TOP_LEFT: dxui.Utils.ALIGN.TOP_LEFT, TOP_MID: dxui.Utils.ALIGN.TOP_MID, TOP_RIGHT: dxui.Utils.ALIGN.TOP_RIGHT, BOTTOM_LEFT: dxui.Utils.ALIGN.BOTTOM_LEFT, BOTTOM_MID: dxui.Utils.ALIGN.BOTTOM_MID, BOTTOM_RIGHT: dxui.Utils.ALIGN.BOTTOM_RIGHT, LEFT_MID: dxui.Utils.ALIGN.LEFT_MID, RIGHT_MID: dxui.Utils.ALIGN.RIGHT_MID, CENTER: dxui.Utils.ALIGN.CENTER, DEFAULT: dxui.Utils.ALIGN.DEFAULT, }; // Convert name to acronym, e.g., OUT_RIGHT_TOP → ORT function getShortName(name) { return name .split("_") .map((word) => word[0]) .join(""); } // Create labels and arrange them around button1 let idx = 0; for (const [name, align] of Object.entries(aligns)) { const label = dxui.Label.build(`label_${idx++}`, page1); label.text(getShortName(name)); // Place "OUT_" ones outside, others inside or on the edge label.alignTo(button1, align, 0, 0); } dxui.loadMain(page1); std.setInterval(() => { dxui.handler(); }, 10); ``` -------------------------------- ### Initiate Video Call from H5 Client Source: https://dejaos.com/docs/videointercom/device This snippet shows how to start a video call from the H5 client by providing the host and a client ID. Ensure the host and toclientid are correctly configured for your environment. ```javascript var toclientid = "KDZN-00-1K4V-HBNJ-00000004"; var host = "webrtc.dxiot.com:8443"; RHRTCStart(host, toclientid, remoteVideoview, "live", "MainStream", true, true); ``` -------------------------------- ### pool.init Source: https://dejaos.com/docs/worker/pool Initializes and starts the thread pool. This is the first step in using the thread pool and can only be called once. It is intended for use only in the main thread. ```APIDOC ## pool.init(file, bus, topics, [count], [maxsize]) ### Description (Main thread only) Initializes and starts the thread pool. This is the first step in using the thread pool and can only be called once. ### Parameters #### Path Parameters * **file** (string) - Required - The **absolute path** to the Worker script. * **bus** (object) - Required - The instance of `dxEventBus` that the thread pool will use to listen for tasks. * **topics** (string[]) - Required - An array of strings that defines all the `dxEventBus` topics the thread pool should listen to. Any event sent to these topics will be treated as a task. * **count** (number) - Optional - The number of `Worker`s in the thread pool, defaults to 2. * **maxsize** (number) - Optional - The maximum length of the internal task queue, defaults to 100. If the queue is full, the newest task will replace the oldest one. ``` -------------------------------- ### Initialize and Share State with dxMap Source: https://dejaos.com/docs/worker/mapqueue Main thread initializes shared state using dxMap, starts a worker, and verifies changes after the worker completes. Requires dxEventBus, dxMap, and dxLogger modules. ```javascript import bus from "./dxmodules/dxEventBus.js"; import map from "./dxmodules/dxMap.js"; import log from "./dxmodules/dxLogger.js"; // 1. Get a map instance for inter-thread sharing const sharedMap = map.get("app_status"); // 2. Main thread sets the initial state log.info("[Main] Setting initial status..."); sharedMap.put("isRunning", true); sharedMap.put("mode", "idle"); sharedMap.put("config", { version: "1.0.2" }); // 3. Start the Worker bus.newWorker("status_worker", "/app/code/worker.js"); // 4. Listen for the worker's completion event and verify the final state of the map bus.on("worker_finished", () => { log.info("[Main] Worker finished. Verifying final status:"); log.info(`- isRunning: ${sharedMap.get("isRunning")}`); // Expected: false log.info(`- mode: ${sharedMap.get("mode")}`); // Expected: 'finished' log.info(`- workerId: ${sharedMap.get("workerId")}`); // Expected: 'status_worker' sharedMap.destroy(); // Clean up }); ``` -------------------------------- ### LVGL C Code for Image Transformation Source: https://dejaos.com/docs/ui/lvglfunc Provides the equivalent LVGL C code for the JavaScript image transformation example, showing direct C function calls. ```c void lv_example_image_transform(void) { lv_obj_t * scr = lv_scr_act(); // Image 1: Original lv_obj_t * img1 = lv_img_create(scr); lv_img_set_src(img1, "/app/code/src/logo.png"); lv_obj_set_pos(img1, 10, 10); // Image 2: Rotated lv_obj_t * img2 = lv_img_create(scr); lv_img_set_src(img2, "/app/code/src/logo.png"); lv_obj_set_pos(img2, 300, 10); lv_img_set_angle(img2, 900); // 90.0 degrees // Image 3: Zoomed lv_obj_t * img3 = lv_img_create(scr); lv_img_set_src(img3, "/app/code/src/logo.png"); lv_obj_set_pos(img3, 100, 400); lv_img_set_zoom(img3, 512); // 256 = 100%, 512 = 200% } ``` -------------------------------- ### Server Create Result (_create) Source: https://dejaos.com/docs/videointercom/android This JSON object is the server's response to a session creation request. It confirms the session state and provides ICE servers for PeerConnection setup. The 'state' field indicates 'online' or 'offline'. ```json { "eventName": "_create", "data": { "sessionId": "xxx", "sessionType": "IE", "messageId": "xxx", "from": "meid", "to": "peerid", "state": "online", "iceServers": [] } } ``` -------------------------------- ### Main Thread and Worker Communication Example Source: https://dejaos.com/docs/worker/eventbus Demonstrates how the main thread can dispatch tasks to a worker and receive completion notifications. The main thread creates the worker, listens for completion events, and fires task events. The worker listens for tasks, simulates work, and fires completion events. ```javascript import bus from "./dxmodules/dxEventBus.js"; import log from "./dxmodules/dxLogger.js"; log.info("Main thread started."); // 1. Create and start a worker using bus.newWorker bus.newWorker("task-worker", "/app/code/worker.js"); // 2. Listen for the completion event from the worker bus.on("task-complete", (result) => { log.info("[Main] Received result from worker:", result); // You can update the UI or perform other actions here }); // 3. Dispatch a task to the worker after 200ms setTimeout(() => { log.info("[Main] Firing start-task event to worker..."); bus.fire("start-task", { seconds: 5 }); }, 200); ``` ```javascript import bus from "./dxmodules/dxEventBus.js"; import log from "./dxmodules/dxLogger.js"; log.info(`[Worker ${bus.id}] started and is ready.`); // 1. Listen for the task event from the main thread bus.on("start-task", (task) => { log.info(`[Worker] Received task: wait for ${task.seconds} seconds.`); // Simulate a time-consuming operation setTimeout(() => { const result = { status: "done", processedIn: bus.id }; log.info("[Worker] Task finished, firing task-complete event..."); // 2. Task completed, fire an event to notify the main thread bus.fire("task-complete", result); }, task.seconds * 1000); }); ``` -------------------------------- ### Initialize dxWorkerPool in Main Thread Source: https://dejaos.com/docs/worker/pool Initializes and starts the thread pool. This function should be called only once in the main thread. It requires the absolute path to the worker script, the dxEventBus instance, and a list of topics to listen to. Optional parameters control the number of workers and the maximum queue size. ```javascript pool.init('/path/to/worker.js', bus, ['topic1', 'topic2'], 4, 50); ``` -------------------------------- ### Standard UI Page with UIManager Source: https://dejaos.com/docs/vibecoding/prompts Defines a standard UI page structure using UIManager for managing UI elements and events. Includes initialization, view setup with buttons, labels, and images, and lifecycle methods. ```javascript import dxui from "../../dxmodules/dxUi.js"; import log from "../../dxmodules/dxLogger.js"; import dxDriver from "../../dxmodules/dxDriver.js"; import utils from "../../dxmodules/dxCommonUtils.js"; import UIManager from "../UIManager.js"; // assume UIManager in src const MyPage = { id: "myhomePage", init: function () { const parent = UIManager.getRoot(); this.root = dxui.View.build(this.id, parent); this.root.setSize(dxDriver.DISPLAY.WIDTH, dxDriver.DISPLAY.HEIGHT); this.root.radius(0); this.root.borderWidth(0); this.root.padAll(0); this.root.bgColor(0x000000); this.initView(); return this.root; }, initView: function () { this.btn = dxui.Button.build(this.id + "_btn", this.root); this.btn.setSize(100, 50); this.btn.align(dxui.Utils.ALIGN.CENTER, 0, 0); this.btnLabel = dxui.Label.build(this.id + "_btn_label", this.btn); this.btnLabel.textFont(UIManager.font(16, dxui.Utils.FONT_STYLE.BOLD)); this.btnLabel.text("Click me"); this.btnLabel.align(dxui.Utils.ALIGN.CENTER, 0, 0); this.btn.on(dxui.Utils.EVENT.CLICK, () => { log.info("Button clicked"); }); this.iconArea = dxui.View.build(this.id + "_icon_area", this.root); this.iconArea.setSize(48, 48); this.iconArea.bgOpa(0); this.iconArea.radius(0); this.iconArea.borderWidth(0); this.iconArea.padAll(0); this.iconArea.setPos(dxDriver.DISPLAY.WIDTH - 48 - 16, 16); this.iconImage = dxui.Image.build(this.id + "_icon", this.iconArea); this.iconImage.source("/app/code/resource/image/icon_admin.png"); this.iconImage.align(dxui.Utils.ALIGN.CENTER, 0, 0); this.iconLabel = dxui.Label.build(this.id + "_icon_label", this.iconArea); this.iconLabel.text("Admin"); this.iconLabel.textFont(UIManager.font(14, dxui.Utils.FONT_STYLE.NORMAL)); this.iconLabel.alignTo(this.iconImage, dxui.Utils.ALIGN.BOTTOM_MID, 0, 4); this.iconArea.on(dxui.Utils.EVENT.CLICK, () => { log.info("Click admin icon"); }); }, onShow: function (data) { if (data) log.info("Received data:", data); }, onHide: function () {}, }; export default MyPage; ``` -------------------------------- ### Get Environment Brightness Source: https://dejaos.com/docs/face/overview Gets the current environment brightness level. This can be used to prompt the user if the lighting conditions are too dim or too bright for optimal face capture. ```javascript dxFacial.getEnvBrightness() ``` -------------------------------- ### Get Status Source: https://dejaos.com/docs/finger/dxFingerZaz Queries the enrollment status of a specific fingerprint ID. ```APIDOC ## getStatus(keyId) ### Description Query the fingerprint enrollment status of the specified ID. ### Parameters #### Path Parameters - **keyId** (number) - Required - Fingerprint ID to query ### Return Value - `0` - Not enrolled - `1` - Enrolled - `false` - Operation failed ### Request Example ```javascript const status = dxFingerZaz.getStatus(100); if (status === 1) { console.log("This ID has enrolled fingerprint"); } else if (status === 0) { console.log("This ID has not enrolled fingerprint"); } ``` ``` -------------------------------- ### Get Enrolled ID List Source: https://dejaos.com/docs/finger/dxFingerZaz Retrieves a list of all fingerprint IDs that are currently enrolled in the module. ```APIDOC ## getEnrolledIdList() ### Description Get the list of all enrolled fingerprint IDs. ### Parameters None ### Return Value - `Array` - Data array of enrolled IDs - `false` - Operation failed ### Request Example ```javascript const idList = dxFingerZaz.getEnrolledIdList(); if (idList) { console.log("List of enrolled IDs:", idList); } ``` ``` -------------------------------- ### UI Worker Entry Point Source: https://dejaos.com/docs/vibecoding/prompts Initializes the UI system, UIManager, registers the home page, and opens it. It also sets up a periodic handler for UI events. ```javascript import dxui from "../dxmodules/dxUi.js"; import log from "../dxmodules/dxLogger.js"; import std from "../dxmodules/dxStd.js"; import UIManager from "./UIManager.js"; import HomePage from "./pages/HomePage.js"; try { dxui.init({ orientation: 1 }); UIManager.init(); UIManager.register("home", HomePage); UIManager.open("home"); std.setInterval(() => { dxui.handler(); }, 20); } catch (error) { log.error(error); } ``` -------------------------------- ### Get Enroll Count Source: https://dejaos.com/docs/finger/dxFingerZaz Retrieves the count of enrolled fingerprints within a specified ID range. ```APIDOC ## getEnrollCount(startId, endId) ### Description Get the number of enrolled fingerprints within the specified range. ### Parameters #### Path Parameters - **startId** (number) - Required - Start ID (1 to total) - **endId** (number) - Required - End ID (1 to total) ### Return Value - `number` - Number of enrolled fingerprints - `false` - Operation failed ### Request Example ```javascript const count = dxFingerZaz.getEnrollCount(1, 5000); if (count !== false) { console.log(`Number of enrolled fingerprints: ${count}`); } ``` ``` -------------------------------- ### Get dxFacial Engine Configuration Source: https://dejaos.com/docs/face/overview Retrieves the current configuration parameters of the facial recognition engine. ```javascript dxFacial.getConfig() ``` -------------------------------- ### Initialize dxFingerMz with Custom Parameters Source: https://dejaos.com/docs/finger/dxFingerMz Initialize the fingerprint recognition module, specifying custom connection ID, UART path, and baud rate. Other parameters will use their default values. ```javascript dxFingerMz.init({ id: 'fingerUart', path: '/dev/ttySLB0', baudrate: '57600-8-N-2' }); ``` -------------------------------- ### deletChar Source: https://dejaos.com/docs/finger/dxFingerMz Deletes a specified number of fingerprint templates starting from a given page index in the flash database. ```APIDOC ## deletChar(pageIndex, num) ### Description Deletes N fingerprint templates starting from the specified page index in the flash database. ### Parameters #### Path Parameters * `pageIndex` (number) - Required - Starting index * `num` (number) - Required - Number of templates to delete ### Returns * `number` - Confirmation code * `0`: Success * Other values: Failure * `-1`: Communication failure or timeout ### Request Example ```javascript // Delete 3 templates starting from index 5 const result = dxFingerMz.deletChar(5, 3); if (result === 0) { console.log('Templates deleted successfully'); } ``` ``` -------------------------------- ### Get Empty ID Source: https://dejaos.com/docs/finger/dxFingerZaz Retrieves the first available fingerprint ID within a specified range, useful for enrollment. ```APIDOC ## getEmptyId(startId, endId) ### Description Get the first empty fingerprint ID within the specified range. ### Parameters #### Path Parameters - **startId** (number) - Required - Start ID (1 to total) - **endId** (number) - Required - End ID (1 to total) ### Return Value - `number` - First empty fingerprint ID - `false` - Operation failed ### Request Example ```javascript const emptyId = dxFingerZaz.getEmptyId(1, 5000); if (emptyId) { console.log(`Found empty ID: ${emptyId}`); } ``` ``` -------------------------------- ### Initialization Source: https://dejaos.com/docs/finger/dxFingerZaz Initializes the fingerprint module and configures serial port connection parameters. ```APIDOC ## init(params) ### Description Initialize the fingerprint module and configure serial port connection parameters. ### Parameters #### Path Parameters - **params.id** (string) - Optional - Connection ID identifier. Default: `'fingerUart'` - **params.type** (string) - Optional - UART type. Default: `'3'` - **params.path** (string) - Optional - Serial port device path. Default: `'/dev/ttySLB1'` - **params.baudrate** (string) - Optional - Baud rate configuration. Default: `'115200-8-N-1'` - **params.total** (number) - Optional - Total fingerprint capacity. Default: `5000` - **params.timeout** (number) - Optional - Timeout in milliseconds. Default: `500` ### Return Value None ### Request Example ```javascript dxFingerZaz.init({ path: '/dev/USB0', baudrate: '9600-8-N-1', timeout: 1000 }); ``` ``` -------------------------------- ### Get Device Information Source: https://dejaos.com/docs/finger/dxFingerZaz Retrieves a string containing the device's information. Check this to confirm device identity or version. ```javascript const deviceInfo = dxFingerZaz.getDeviceInfo(); if (deviceInfo) { console.log("Device information:", deviceInfo); } ``` -------------------------------- ### Basic Fingerprint Workflow Source: https://dejaos.com/docs/finger/dxFingerMz Demonstrates a basic workflow: capturing a fingerprint image, generating a feature file, and searching the fingerprint library. Ensure successful capture and generation before proceeding. ```javascript // 1. Capture fingerprint image const result = dxFingerMz.getImage(); if (result === 0) { console.log('Fingerprint image captured successfully'); } // 2. Generate feature file const genResult = dxFingerMz.genChar(1); if (genResult === 0) { console.log('Feature file generated successfully'); } // 3. Search fingerprint library const searchResult = dxFingerMz.search(1, 0, 100); if (searchResult && searchResult.code === 0) { console.log(`Match found, index: ${searchResult.pageIndex}, score: ${searchResult.score}`); } ``` -------------------------------- ### Import dxFingerZaz Module Source: https://dejaos.com/docs/finger/dxFingerZaz Import the dxFingerZaz module to begin using its functionalities. Ensure the path to the module is correct. ```javascript import dxFingerZaz from './js/dxFingerZaz.js'; ``` -------------------------------- ### Initialize dxUi Source: https://dejaos.com/docs/ui/getstart Initialize the dxUi library. This must be called once before any other UI operations. ```javascript dxui.init({ orientation: 1 }); ``` -------------------------------- ### Get Chip Serial Number Source: https://dejaos.com/docs/finger/dxFingerMz Retrieves the unique serial number of the fingerprint sensor chip. Use for device identification or inventory purposes. ```javascript const result = dxFingerMz.getChipSN(); if (result && result.code === 0) { console.log('Chip serial number:', result.sn); } ``` -------------------------------- ### Get Valid Template Count Source: https://dejaos.com/docs/finger/dxFingerMz Retrieves the number of registered valid fingerprint templates. Useful for monitoring storage or before enrolling new templates. ```javascript const result = dxFingerMz.getValidTemplateNum(); if (result && result.code === 0) { console.log(`Current valid template count: ${result.validNum}`); } ``` -------------------------------- ### Register and Launch Views Source: https://dejaos.com/docs/bestpractice/uimanager Registers view components with the UIManager and launches the initial view. Ensure all views are registered before opening. ```javascript import uiManager from './ui/UIManager.js'; import HomeView from './ui/HomeView.js'; import DetailView from './ui/DetailView.js'; // 1. Register Pages uiManager.register('home', HomeView); uiManager.register('detail', DetailView); // 2. Launch Home uiManager.open('home'); ``` -------------------------------- ### Main Thread Initialization Source: https://dejaos.com/docs/vibecoding/prompts Sets up basic initialization for the main thread and creates a new UI worker. This script is responsible for bootstrapping the application's main process. ```javascript import bus from "../dxmodules/dxEventBus.js"; import log from "../dxmodules/dxLogger.js"; function init() {} try { init(); } catch (e) { log.error("init error", e); } const uiWorker = bus.newWorker("uiWorker", "/app/code/src/uiWorker.js"); ``` -------------------------------- ### Get List of Enrolled Fingerprint IDs Source: https://dejaos.com/docs/finger/dxFingerZaz Fetches an array containing the IDs of all currently enrolled fingerprints. Returns false if the operation fails. ```javascript const idList = dxFingerZaz.getEnrolledIdList(); if (idList) { console.log("List of enrolled IDs:", idList); } ``` -------------------------------- ### Main Script (Task Publisher) Source: https://dejaos.com/docs/worker/pool This script initializes the worker pool with a specified worker file, event bus, topics, and worker count. It then dispatches multiple tasks to the event bus, which are automatically picked up and processed by the workers. ```javascript import pool from "../dxmodules/dxWorkerPool.js"; import eventBus from "../dxmodules/dxEventBus.js"; import log from "../dxmodules/dxLogger.js"; import std from "../dxmodules/dxStd.js"; log.info("----------- dxWorkerPool Example ----------- "); // 1. Define the thread pool configuration const workerFile = "/app/code/src/worker.js"; const topicsToProcess = ["image.resize", "log.upload"]; const workerCount = 3; const queueSize = 10; // 2. Initialize the thread pool log.info( `Initializing ${workerCount} Workers to handle tasks from [${topicsToProcess.join( ", " )}] topics` ); pool.init(workerFile, eventBus, topicsToProcess, workerCount, queueSize); log.info("Thread pool initialized successfully."); // 3. Fire a series of events via dxEventBus, which will be automatically handled by the thread pool const taskCount = 8; log.info(`\n--- Dispatching ${taskCount} tasks to the event bus... ---`); for (let i = 1; i <= taskCount; i++) { // Alternate sending tasks to different topics const topic = i % 2 === 0 ? topicsToProcess[0] : topicsToProcess[1]; const payload = { taskId: i, message: `Task details #${i}` }; log.info(`-> [Main] Firing event to '${topic}'`); eventBus.fire(topic, payload); std.sleep(50); // A short sleep to make the logs clearer } log.info( `\n--- All ${taskCount} tasks have been dispatched. Observe the Worker logs to see the task distribution. ---` ); ``` -------------------------------- ### Get Module Parameter Source: https://dejaos.com/docs/finger/dxFingerZaz Retrieves the value of a specific module parameter. Use this to check current settings like security level or baud rate. ```javascript // Get security level const securityLevel = dxFingerZaz.getParam(1); if (securityLevel !== false) { console.log(`Security level: ${securityLevel}`); } ``` -------------------------------- ### Get Count of Enrolled Fingerprints Source: https://dejaos.com/docs/finger/dxFingerZaz Retrieves the number of fingerprints enrolled within a given ID range. Returns the count or false if the operation fails. ```javascript const count = dxFingerZaz.getEnrollCount(1, 5000); if (count !== false) { console.log(`Number of enrolled fingerprints: ${count}`); } ``` -------------------------------- ### Create and Configure a Button with JavaScript Source: https://dejaos.com/docs/basics/gui-engine This snippet demonstrates how to create a button using the dxui module in DejaOS, set its size and background properties, and attach a click event listener. It requires importing the dxui module. ```javascript import dxui from "../dxmodules/dxUi.js"; let button1 = dxui.Button.build("button1", screen_main); button1.setSize(120, 50); button1.bgColor(0x000000); button1.bgOpa(30); button1.on(dxui.Utils.EVENT.CLICK, () => { // }); ``` -------------------------------- ### Watchdog Initialization and Channel Enabling Source: https://dejaos.com/docs/vibecoding/prompts Initialize the watchdog component and enable specific channels for monitoring. This should be done in main.js. ```javascript import watchdog from "dxmodules/dxWatchdog.js"; watchdog.init(); watchdog.enable(channel, true); watchdog.start(timeout_ms); ``` -------------------------------- ### Bind Click Event to Button Source: https://dejaos.com/docs/ui/getstart Use the `on()` method to bind an event handler to a button. This example specifically binds a click event that logs a message. ```javascript button.on(dxui.Utils.EVENT.CLICK, () => { logger.info("Button clicked"); }); ``` -------------------------------- ### Initialize dxFingerMz Module Source: https://dejaos.com/docs/finger/dxFingerMz Initialize the fingerprint recognition module with specific UART connection parameters. This sets up the communication channel and library capacity. ```javascript dxFingerMz.init({ id: 'fingerUart', path: '/dev/ttySLB0', baudrate: '57600-8-N-2', timeout: 500, total: 5000, type: '3' }); ``` -------------------------------- ### Control dxFacial Engine Running State Source: https://dejaos.com/docs/face/overview Dynamically controls the engine's running state. Pass `true` to start recognition and `false` to pause. ```javascript dxFacial.setStatus(isRunning) ``` -------------------------------- ### Initialize dxFingerZaz Module Source: https://dejaos.com/docs/finger/dxFingerZaz Initialize the module with specific serial port parameters before any other operations. Configure connection ID, UART type, serial port path, baud rate, fingerprint capacity, and timeout. ```javascript dxFingerZaz.init({ id: 'fingerUart', type: '3', path: '/dev/ttySLB1', baudrate: '115200-8-N-1', total: 5000, timeout: 500 }); ``` -------------------------------- ### Initialize Fingerprint Module Source: https://dejaos.com/docs/finger/dxFingerZaz Initializes the fingerprint module and configures serial port parameters. Customize path, baudrate, and timeout as needed for your environment. ```javascript dxFingerZaz.init({ path: '/dev/ttyUSB0', baudrate: '9600-8-N-1', timeout: 1000 }); ``` -------------------------------- ### Get First Empty Fingerprint ID Source: https://dejaos.com/docs/finger/dxFingerZaz Retrieves the first available fingerprint ID within a specified range. Useful for determining where to enroll a new fingerprint. ```javascript const emptyId = dxFingerZaz.getEmptyId(1, 5000); if (emptyId) { console.log(`Found empty ID: ${emptyId}`); } ``` -------------------------------- ### pool.getWorkerId Source: https://dejaos.com/docs/worker/pool Gets the ID of the current thread. Returns 'main' in the main thread, and a unique ID assigned by the thread pool (e.g., 'pool__id0') in a Worker thread. ```APIDOC ## pool.getWorkerId() ### Description (Available in both Main and Worker threads) Gets the ID of the current thread. Returns `'main'` in the main thread, and returns a unique ID assigned by the thread pool (e.g., `'pool__id0'`) in a Worker thread. ``` -------------------------------- ### Verify Fingerprint Workflow Source: https://dejaos.com/docs/finger/dxFingerZaz This snippet outlines the steps to detect, capture, generate a template from, and search for a fingerprint. Ensure the module is initialized and connected before use. ```javascript if (!dxFingerZaz.fingerDetect()) { console.log("Please place your finger"); return; } if (!dxFingerZaz.getImage()) { console.error("Failed to capture fingerprint image"); return; } if (!dxFingerZaz.generate(0)) { console.error("Failed to generate template"); return; } const matchedId = dxFingerZaz.search(0, 1, 5000); if (matchedId) { console.log(`Fingerprint matched successfully, ID: ${matchedId}`); } else { console.log("No matching fingerprint found"); } ``` -------------------------------- ### Main Thread RPC Communication Source: https://dejaos.com/docs/worker/rpc Initiates a worker and demonstrates both one-way notification and request/response RPC calls. Ensure the worker has time to start before making calls. ```javascript import bus from "./dxmodules/dxEventBus.js"; import log from "./dxmodules/dxLogger.js"; const WORKER_ID = "calculator"; // Start the Worker bus.newWorker(WORKER_ID, "/app/code/worker.js"); async function runRpcDemo() { log.info("[Main] ---- Running RPC Demo ----"); // Demonstrate notify (fire-and-forget) log.info('[Main] Sending a "notify" call to worker...'); bus.rpc.notify(WORKER_ID, "logMessage", { text: "Hello from main!" }); // Demonstrate call (request/response) using async/await try { log.info('[Main] Sending a "call" request to worker...'); const response = await bus.rpc.call(WORKER_ID, "calculate", { count: 100000, }); log.info("---------------------------------"); log.info("[Main] ✅ RPC call successful!"); log.info("[Main] Response from worker:", response); log.info("---------------------------------"); } catch (error) { log.error("---------------------------------"); log.error("[Main] ❌ RPC call failed:", error.message); log.info("---------------------------------"); } log.info("[Main] ---- RPC Demo Finished ----"); } // Delay execution to ensure the Worker has enough time to start up and register its functions setTimeout(runRpcDemo, 2500); ``` -------------------------------- ### Import dxFingerMz Module Source: https://dejaos.com/docs/finger/dxFingerMz Import the dxFingerMz module to begin using its functionalities. ```javascript import dxFingerMz from './dxFingerMz.js'; ``` -------------------------------- ### Get Current Thread ID Source: https://dejaos.com/docs/worker/pool Retrieves the ID of the current thread. Returns 'main' for the main thread and a unique pool-assigned ID (e.g., 'pool__id0') for worker threads. ```javascript const workerId = pool.getWorkerId(); console.log('Current thread ID:', workerId); ``` -------------------------------- ### Importing the dxUi Module Source: https://dejaos.com/docs/ui/dxui This is the primary way to import the dxUi module into your project. It serves as the unified entry point for accessing all UI functionalities. ```javascript import dxui from "../dxmodules/dxUi.js"; ``` -------------------------------- ### Delete Fingerprint Templates Source: https://dejaos.com/docs/finger/dxFingerMz Deletes a specified number of fingerprint templates starting from a given index in the flash database. Use with caution to avoid accidental data loss. ```javascript // Delete 3 templates starting from index 5 const result = dxFingerMz.deletChar(5, 3); if (result === 0) { console.log('Templates deleted successfully'); } ``` -------------------------------- ### QR Code Recognition and Logging Source: https://dejaos.com/docs/basics/dejaos-arch This snippet demonstrates how to initialize QR code scanning, subscribe to recognition events, and log the decoded content. It utilizes several DejaOS modules for logging, system functions, event handling, and camera/code recognition. ```javascript import log from "../dxmodules/dxLogger.js"; import std from "../dxmodules/dxStd.js"; import bus from "../dxmodules/dxEventBus.js"; import code from "../dxmodules/dxCode.js"; import common from "../dxmodules/dxCommon.js"; // 1. Initialize QR code scanning module code.worker.beforeLoop( { id: "capturer1", path: "/dev/video11" }, { id: "decoder1", name: "decoder v4", width: 800, height: 600 } ); // 2. Subscribe to QR code recognition events bus.on(code.RECEIVE_MSG, function (data) { let str = common.utf8HexToStr(common.arrayBufferToHexString(data)); log.info(str); // Print QR code content }); // 3. Poll scan results every 50ms std.setInterval(() => { try { code.worker.loop(); } catch (error) { log.error(error); } }, 50); ``` -------------------------------- ### Load and Display Interface Source: https://dejaos.com/docs/ui/getstart Call `loadMain()` to render UI objects from memory to the screen. This is essential for displaying the user interface and is the basic principle for page navigation. ```javascript dxui.loadMain(screenMain); ``` -------------------------------- ### Capture Face Feature for Registration Source: https://dejaos.com/docs/face/overview Starts the camera to capture a face within a specified timeout and returns a high-quality facial feature vector. This is the core function for live, on-site registration. ```javascript dxFacial.getFeaByCap(timeout) ``` -------------------------------- ### Initialize dxFacial Component Source: https://dejaos.com/docs/face/overview Initializes the facial recognition engine and cameras. Configuration options include camera parameters, database path and capacity, detection distance, recognition timeout, liveness detection, and comparison thresholds. ```javascript dxFacial.init(config) ``` -------------------------------- ### Get Real-time Face Detection Data Source: https://dejaos.com/docs/face/overview Retrieves high-frequency real-time face detection information, such as bounding box coordinates. Use this in the UI refresh loop to draw face tracking boxes. ```javascript dxFacial.getDetectionData() ``` -------------------------------- ### Cloud Dispatch (MQTT) Data Flow Source: https://dejaos.com/docs/bestpractice/access Illustrates the data flow for cloud dispatch using MQTT, where a backend system pushes commands to devices via an MQTT broker. This is suitable for large-scale deployments requiring centralized management. ```mermaid +------------+ +------------+ +----------+ | Backend Mgt| | MQTT Broker| | Device App | +------------+ +------------+ +----------+ | | | | 1. Admin enters Person/Perm | | |----------------------------->| | | | | | 2. Publish Update Command | | |----------------------------->| | | | 3. Push Message | | |------------------------------>| | | | | | 4. Parse msg & write DB | | | | | | 5. Return Result (Ack) | |<-----------------------------+-------------------------------| | | | ```