In this Codelab, use Ray and Lock SDK to build a Bluetooth lock panel with slide to unlock, member management, temporary passwords, locking and unlocking records, alerts, and lock settings. Available capabilities depend on the product, firmware, account permissions, and connection conditions.
openDoor(). The current home page has no separate manual locking action.For more information, see Panel MiniApp > Set up environment.
A product defines the data points (DPs) of the associated panel and device. Before you develop a panel, you must create a product, define the required DPs, and then implement these DPs on the panel.
Register and log in to the Tuya Developer Platform and create a product.


Register and log in to the Smart MiniApp Developer Platform.
For more information, see Create panel miniapp.
Open Tuya MiniApp IDE and create a panel miniapp project based on the smart lock template. For more information, see Initialize project.

This tutorial is for panel developers familiar with React, TypeScript, and Ray. Use raytpl-ble-door-lock-template to run the panel and learn how to customize it by tracing the key implementation paths.
The examples use @ray-js/lock-sdk for lock operations and must be read together with this template.
The following requirements come from the template's README_zh.md and project.tuya.json.
Item | Requirement |
App | Tuya Smart / Smart Life 6.7.0 or later |
Local environment | Node.js 22 or later, Yarn 1.x |
Development tool | Tuya MiniApp development tool, installed and signed in |
Kits | BaseKit 3.0.6, MiniKit 3.0.0, DeviceKit 4.6.1, BizKit 4.2.0, HomeKit 3.0.2 |
Test device | A paired Bluetooth lock that matches the product definition |
Test account | Access to the device; use an owner or administrator account for management features |
Enable Bluetooth on the phone and grant the required app permissions. For proximity testing, keep the phone close to the lock and wake the lock as required by the device. Features that access cloud data also require a network connection on the phone.
Term | Meaning |
DP | Data point: a device feature such as battery level or the automatic locking switch |
Schema | The product's DP definitions, including codes, types, access modes, and value ranges |
Device model | The Panel SDK object that manages device data and supplies Schema and DP state to pages |
Lock SDK |
|
Unlocking method | A credential associated with a member, such as a password, fingerprint, or card |
Run the following commands in the template project root:
yarn install --frozen-lockfile
yarn start
Open the project in the development tool and wait for compilation to finish. The template sets miniprogramRoot to ./dist/tuya and devMode to ray in project.tuya.json.
After previewing in the development tool, use the app's device preview or debugging flow with an account that can access the test lock, and open its panel.
Resolve installation or compilation errors before proceeding. The source imports modules such as @tuya-miniapp/icons and dayjs. If a build reports missing modules, check the dependency declarations and lockfile, and ensure that directly imported dependencies are declared and installed according to the project's conventions.
src/
├── app.tsx # Panel environment, error boundary, device model provider
├── composeLayout.tsx # SDK initialization, startup state, and retry
├── devices/ # Device model, Schema, and protocols
├── routes.config.ts # Page routes
├── pages/
│ ├── home/ # Status overview, slide to unlock, and feature entries
│ ├── members/ # Members and sharing
│ ├── unlock/ # Credential enrollment, editing, and association
│ ├── temporary/ # Temporary passwords and records
│ ├── logs/ # Operation records and alerts
│ ├── accessories/ # Accessory discovery and binding
│ └── settings/ # Lock settings and voice packages
├── hooks/useOperate.ts # Throttling and optional online checks
├── utils/send-dps.ts # DP publishing and error feedback
├── utils/permission.ts # Role checks used by pages
└── i18n/ # UI and DP translations
app.tsx calls initPanelEnvironment({ useDefaultOffline: false }) so that the template handles offline presentation itself. SdmProvider supplies the device model to the pages.
composeLayout.tsx initializes the device model and Lock SDK at startup. The following excerpt belongs inside the existing initialization method:
devices.common.init();
devices.common.onInitialized((device) => dpKit.init(device));
await initLock({
passwordDigitalBase: 10,
passwordSupportZero: true,
strictMode: false,
});
initLock is an import alias for the SDK's init. The password numeric base and support for digit 0 must match the product protocol. Do not change them merely to make the page load.
Startup follows loading → ready / error: the business pages appear after successful SDK initialization, while a retry button appears on failure. The component calls the SDK's destroy() on unmount to release resources.
Scenario | Template implementation |
Read door lock status, battery level, and lock body status | Panel SDK |
Check whether a DP exists | Panel SDK |
Connect, unlock, and manage members and temporary passwords | Lock SDK business APIs |
Publish ordinary settings |
|
Successful initialization and an established Bluetooth connection are separate states. Check the connection state before performing a device operation.

Implementation: src/pages/home/components/open/index.tsx.
The template reads the current state with getDeviceStatus() and subscribes to changes. The following minimal pattern belongs inside a React component, with the required hooks and SDK methods imported:
const [deviceStatus, setDeviceStatus] = useState(() => getDeviceStatus());
useEffect(() => {
const handleChange = (status: ReturnType<typeof getDeviceStatus>) => {
setDeviceStatus(status);
};
onDeviceStatusChange(handleChange);
return () => offDeviceStatusChange(handleChange);
}, []);
Remove the same callback on unmount to prevent duplicate event handling when users revisit the page. The template also resets slide progress when the device goes offline.
When the user requests a connection, the template calls:
await connectDevice({ timeout: 15000 });
setDeviceStatus(getDeviceStatus());
The connecting state prevents duplicate connection attempts. On failure, the page shows feedback and restores the button state in finally.
The current home page uses a sliding gesture. The source defines MAX_SLIDE_RPX = 482 and UNLOCK_THRESHOLD = 0.75.
rpx2pxNum to obtain progress from 0 to 1.await openDoor() only when deviceStatus.type === 'online'.The operating and operationDone states limit repeated requests. The component clears the reset timer on unmount.
DP code | Use on the current home page |
| Lock body status |
| Door lock status |
| Double-lock status |
| Battery level category |
These are the codes used by the template. Verify their Schema definitions and firmware semantics for your product. Missing or unsupported values must not be treated as reliable physical state.
With a real device connected, release the slider below the threshold, slide past the threshold, slide again during an operation, and try sliding after disconnection. Confirm that unlocking is requested only when the conditions are met, and check the physical lock action.

Implementation: src/utils/permission.ts and src/pages/home/components/options/index.tsx.
SDK role | Current home page behavior |
| Show management entries |
| Open the member's own details; hide other management entries |
Other roles or unavailable role | Hide management shortcuts |
canViewLogs allows owners, administrators, and ordinary members to view logs. UI entry checks control presentation. SDK and server-side authorization still determine whether an operation is permitted.
src/pages/members/list/index.tsx retrieves members through getUsers. It also handles adding users, opening family member flows, synchronizing unlocking methods, and shared users.
src/pages/members/details/index.tsx retrieves member information through getUserInfo. Distinguish family member information, lock users, and shared users, and do not mix identifiers for these objects.
Requirement | File | SDK entry points |
Enroll fingerprints, cards, faces, and similar methods |
|
|
Add a member password |
|
|
Edit, delete, or disassociate a credential |
|
|
Associate an existing device credential |
|
|
Biometric and card enrollment is event driven: show instructions, start enrollment, update steps and the countdown from events, and then show success or failure. The template also handles enrollment cancellation and listener removal.
Preserve the instruction, enrolling, success, and failure states when customizing the flow. Check cancellation when navigating back or leaving the page. Password enrollment uses a separate page rather than the fingerprint collection flow.
As an administrator, enroll a supported credential for a test member, name it, and verify it in the member details. Test failure and cancellation as well. As an ordinary member, confirm that the home page opens your own details and does not show management shortcuts.

The entry page is src/pages/temporary/password/index.tsx. Each password type is implemented under its components directory.
Type | Main component | SDK methods used by the source |
Custom |
|
|
Time-limited |
|
|
One-time |
|
|
Dynamic |
|
|
Clearing code |
|
|
The selector lists these types, but not every product supports them all. Check support and SDK results for each type during testing.
custom/index.tsx validates the password and recurrence selection before calling createTempCustom. The key validity parameters are mapped as follows:
// Excerpt: use inside the existing createTempCustom validity configuration.
effectiveDate: Math.floor(effectConfig.effectiveTime.valueOf() / 1000),
expiredDate: Math.floor(effectConfig.invalidTime.valueOf() / 1000),
repeat: effectConfig.repeat ? 'week' : 'none',
weeks: effectConfig.weeks,
effectiveTime: effectConfig.startTime,
expiredTime: effectConfig.endTime,
Dates are converted to Unix timestamps in seconds. The daily validity window and overall date interval are separate fields. Do not pass millisecond timestamps to fields that expect seconds. When recurrence is enabled, the template checks that at least one day is selected. When extending the form, also validate that the start precedes the end and that the password follows the product's rules.

temporary/valid-list uses getTempEffectiveList to retrieve valid passwords and provides rename, edit, or removal actions according to password type.temporary/edit-custom uses updateTempCustom to edit custom passwords.temporary/invalid-list retrieves expired records through getTempInvalidList and clears those records through clearTempInvalidList.temporary/clear-one uses createTempClear for the clearing flow for a specific password.Clearing expired records and invalidating a password on the physical lock are different operations. A clearing code must be used on the device according to the product's rules. Generating it does not mean the lock has already removed the password.
Create a temporary password supported by the test product. Check its validity period, record, and actual use on the lock, then verify expiration or clearing. Mask real passwords and personal information in screenshots and troubleshooting material.

Implementation: src/pages/logs/logs.tsx, alarm.tsx, and the home page's components/log/index.tsx.
Operation records are retrieved through getLockLogList. The template uses this request:
const res = await getLockLogList({
logCategories: ["operation", "unlock_record", "close_record"],
limit: 20,
lastRowKey: reset ? undefined : lastRowKeyRef.current || undefined,
});
On initial loading or refresh, omit the previous page cursor. To load more, pass the last returned lastRowKey, append res.list, and use res.hasNext to determine whether more records are available.
A separate component handles alerts. The home page retrieves recent records through getLatestLogs, subscribes with onLogsRefresh, and removes the listener with offLogsRefresh on unmount.
The current log page provides record and alert categories, refresh, and pagination. Time-range filtering is not implemented in this template's current page. To extend filtering, first check the installed SDK's parameter definitions, and clear the list and pagination cursor when filters change.
Verify this step by generating a real unlock record and checking both the home page summary and log list. Refreshing must not append a duplicate first page. With enough records, check the pagination stop condition.

Entry page: src/pages/settings/overview/index.tsx.
remote-unlock: reads and updates the remote unlocking switch and permissions through the SDK.device-settings: handles automatic locking, arm away, enum settings, and settings gated by advanced capabilities.time-setings: handles the DND switch and schedule, using methods including getDpPeriodTime and updateDpPeriodTime.language-settings and settings/voice-file: query languages and voice packages, send packages, and display progress.Verify remote permissions and the actual remote unlocking connection separately. Gateway operation depends on product and connection capabilities. Enabling the switch alone does not establish that remote unlocking is available.
Ordinary settings components first check dpSchema[code] and return null if the DP is absent. Enum choices come from property.range. Automatic locking time uses the Schema's min, max, and step to validate input.
sendDps in src/utils/send-dps.ts checks the online state before calling publishDps. The current implementation uses a 15-second timeout, shows a loading indicator after 3 seconds, and distinguishes timeout from other failures. It accepts checkReport to check whether a device report matches expectations.
await sendDps({ automatic_lock: true });
Place this call in an existing operation callback and handle errors as needed. Display state based on device reports instead of assuming that clicking a switch changed the device.
The current home page uses 'unlock_record_check' in dpSchema to decide whether the accessory entry is supported. This is the template's entry condition, not a universal capability standard for all lock products.
src/pages/accessories/index.tsx uses these methods:
Operation | SDK method |
Read bound accessories |
|
Read available accessories |
|
Bind |
|
Unbind |
|
The page loads bound and available lists in parallel, requests confirmation before binding or unbinding, and prevents repeated operations. Both the product and actual accessory must support the operation for verification to succeed.
Reuse the existing DpSwitchSetting pattern to expose a Boolean DP already supported by the actual product. If there is no new DP to expose, trace the existing arming_switch flow for this exercise. There is no need to invent a new protocol.
Confirm the following in the actual product definition:
When adding a product DP, synchronize the Schema and types using the project's device model generation flow. Editing src/devices/schema.ts alone does not add hardware capability.
Reuse the existing component inside DeviceSettings in src/pages/settings/overview/components/device-settings/index.tsx:
// arming_switch is the template's existing arm-away switch.
// For a different DP, use its actual product code. Do not add a duplicate entry.
<DpSwitchSetting code="arming_switch" />
DpSwitchSetting already checks Schema availability, reads state through useProps, checks online status through useOperate, and publishes through sendDps. Do not duplicate this logic for each Boolean DP.
Follow the existing Strings.getDpLang(code) convention and add the required English and Chinese strings in src/i18n/strings.ts. Check the layout in both light and dark themes.
Scenario | Pass condition |
Initialization and retry | Success opens the home page; failure provides feedback and retry starts initialization again |
Connection and disconnection | State updates promptly; sliding offline does not request unlocking |
Slide to unlock | Threshold and duplicate-request checks work; physical action and reports can be verified |
Members and credentials | Supported enrollment completes; cancellation and failure are recoverable |
Temporary passwords | Creation, validity, actual use, and the corresponding clearing flow match |
Logs | Records, refresh, and pagination are correct |
Settings | Supported settings appear, and operation results match device reports |
Accessories | Discovery, binding, and unbinding work on supported products |
Page lifecycle | Repeated navigation does not duplicate listeners or leave timers running |
Symptom | Check first |
Module not found during compilation | Installation, explicit dependency declarations, and the project lockfile |
Stuck on initialization | SDK initialization failure, device parameters, project association, and required app/Kit versions |
Connection failure or offline state | Bluetooth permissions, distance, lock wake state, and device binding |
Missing management entries | Role returned by |
Missing setting | Whether the actual Schema contains its code and whether extra capability conditions apply |
Temporary password creation fails | Supported types, password rules, validity parameter units, and connection conditions |
Generated password does not work on the device | Conditions for that type, validity period, and device synchronization requirements |
Accessory entry unavailable | The current Schema-based entry check and actual product support |
Success shown without lock body movement | Check the SDK result, lock body reports, and physical action separately |
Run in the template project root:
yarn build
./node_modules/.bin/tsc --noEmit
./node_modules/.bin/eslint src --ext .js,.jsx,.ts,.tsx
These checks detect compilation, type, and style issues. They do not replace device communication, account permission, or physical action testing.
After completing the tutorial, you should be able to run the lock panel, locate connection, unlocking, and business implementations, and extend a setting based on the product's existing capabilities.