Prerequisites

Create a panel

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.

Learning objectives

Prerequisites

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.

  1. In the left-side navigation pane, choose Product > Development > Create.
  2. In the Standard Category tab, choose Smart Locks > Residential Lock Pro.
  3. Select a smart mode and solution, and complete product information. For example, specify Product Name as PanelLock and Protocol as Bluetooth.
  4. Click Create.
  5. After your product is created, the Add Standard Function dialog box appears. You can keep the default selections.

Create panel miniapp on Smart MiniApp Developer Platform

Register and log in to the Smart MiniApp Developer Platform.

For more information, see Create panel miniapp.

Create a project based on a template

Open Tuya MiniApp IDE and create a panel miniapp project based on the smart lock template. For more information, see Initialize project.

Audience and scope

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.

Environment and devices

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.

Terms

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

@ray-js/lock-sdk, the library used by the template for lock operations

Unlocking method

A credential associated with a member, such as a password, fingerprint, or card

Install and start

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.

Check the result

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.

Key files

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

Startup flow

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.

Data and operation responsibilities

Scenario

Template implementation

Read door lock status, battery level, and lock body status

Panel SDK useProps

Check whether a DP exists

Panel SDK useDevice to read dpSchema

Connect, unlock, and manage members and temporary passwords

Lock SDK business APIs

Publish ordinary settings

sendDps, wrapping Lock SDK publishDps

Successful initialization and an established Bluetooth connection are separate states. Check the connection state before performing a device operation.

Read and monitor connection state

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.

Slide-to-unlock flow

The current home page uses a sliding gesture. The source defines MAX_SLIDE_RPX = 482 and UNLOCK_THRESHOLD = 0.75.

  1. Record the horizontal position when the touch starts.
  2. Calculate the distance as the touch moves. Convert the slide area's length to pixels with rpx2pxNum to obtain progress from 0 to 1.
  3. On release, invoke the unlock handler only if progress reaches 75%. Otherwise, reset the slider.
  4. Check whether an operation is in progress, an operation has just completed, or the lock body state prevents another unlock.
  5. Call await openDoor() only when deviceStatus.type === 'online'.
  6. On success, display feedback and reset the temporary result after 1.5 seconds. On failure, reset progress and show an error.

The operating and operationDone states limit repeated requests. The component clears the reset timer on unmount.

Status overview

DP code

Use on the current home page

lock_motor_state

Lock body status

closed_opened

Door lock status

reverse_lock

Double-lock status

battery_state

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.

Verify this step

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.

Determine the account role

Implementation: src/utils/permission.ts and src/pages/home/components/options/index.tsx.

SDK role

Current home page behavior

OWNER, ADMIN

Show management entries

MEMBER

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.

Member list and details

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.

Enroll and edit unlocking methods

Requirement

File

SDK entry points

Enroll fingerprints, cards, faces, and similar methods

pages/unlock/add/index.tsx

startAddUnlockMethod, onAddUnlockMethod

Add a member password

pages/unlock/password/index.tsx

addPassword

Edit, delete, or disassociate a credential

pages/unlock/edit/index.tsx

getUnlockMethodDetail, updateUnlockMethod, deleteUnlockMethod, unbindUnlockMethod

Associate an existing device credential

pages/unlock/unbind-list/index.tsx

getUnbindUnlockMethods, bindUnlockMethod

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.

Verify this step

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

custom/index.tsx

createTempCustom

Time-limited

limit/index.tsx

createTempLimit

One-time

once/index.tsx

createTempCustom, createTempLimit, or createTempOnce, depending on the branch

Dynamic

dynamic/index.tsx

createTempDynamic

Clearing code

clear/index.tsx

createTempClear, getTempEffectiveList

The selector lists these types, but not every product supports them all. Check support and SDK results for each type during testing.

Key custom password parameters

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.

Password records

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.

Verify this step

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.

Show settings according to capabilities

Entry page: src/pages/settings/overview/index.tsx.

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.

Publish DPs and handle feedback

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.

Discover, bind, and unbind accessories

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

getBoundFitList

Read available accessories

getUnbindFitList

Bind

bindFitToLock

Unbind

unbindFitToLock

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.

Step 1: Check the DP definition

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.

Step 2: Add the setting entry

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.

Step 3: Add translations

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.

Step 4: Verify the result

  1. Show the setting if the product contains the DP, and hide it otherwise.
  2. When toggled online, the device acts and reports a state that matches the page.
  3. Changes made on the device update the page through reports.
  4. Offline operations, publishing failures, and timeouts provide clear feedback.
  5. Switching account roles preserves the existing permission design for setting entries.

Verification checklist

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

Common issues

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 getCurrentUserSync() and device permissions for the current account

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

Build and static checks

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.