Bluetooth Smart Lock

Last Updated on : 2023-06-12 06:43:51download

Description

Class name Description
TuyaOptimusSdk Provides access to the SDK initialization feature and returns the lock management class.
ITuyaLockManager The lock management class that is used to get different types of lock classes.
ITuyaBleLock The Bluetooth lock class that includes all methods of Bluetooth locks.

Example

The following code block shows how to create a Bluetooth lock class based on a device ID.

// Initialize the SDK for only once.
TuyaOptimusSdk.init(getApplicationContext());
// Get the `TuyaLockManager` class.
ITuyaLockManager tuyaLockManager = TuyaOptimusSdk.getManager(ITuyaLockManager.class);
// Create the `ITuyaBleLock` class.
ITuyaBleLock tuyaLockDevice = tuyaLockManager.getBleLock(your_device_id);

Terms

Term Description
Duress alarms The duress alarm feature allows users to enroll a password or fingerprint as a duress code. If they are coerced by hostile persons, unlocking with the duress code can trigger alarms to be sent to a list of contacts.
Lock members Lock members are classified into home members and non-home members.
  • Home member: the same as that defined in the Smart Life App SDK. The Smart Lock SDK can be used to associate a lock password ID with a home member account. For more information, see Home Management.
  • Non-home members: an individual member of a smart lock, only associated with the device. This member can be created and assigned. The Smart Lock SDK can be used to associate a lock password ID with this member.
lockUserId A lockUserId is a firmware member ID that the cloud assigns to a lock when you create a lock member. Each lockUserId indicates the member ID that is recorded in the firmware.
userId A userId is the ID that the cloud assigns to a lock member when you create the member. Each userId is a unique ID of each user and is recorded in a database.
dpCode An identifier of a data point (DP) for a device. Each DP is assigned a name and an identifier indicated by dpCode. For more information, see List of Lock DPs.

Lock members

This section describes the operations regarding non-home members.

Query a list of lock members

API description

/**
 * get lock users
 */
public void getLockUsers(final ITuyaResultCallback<List<BLELockUser>> callback)

Data model of BLELockUser

Field Type Description
userId String The user ID.
lockUserId Integer The user ID that is associated with the lock.
userContact String The contact method.
nickName String The nickname.
avatarUrl String The avatar URL of the user.
userType Integer The type of user. Valid values:
  • 10: administrator
  • 20: ordinary home user
  • 30: lock user
supportUnlockTypes List The supported unlocking types. For more information, see the unlocking methods that are specified by TuyaUnlockType.
effectiveTimestamp Long The timestamp in milliseconds when the user takes effect.
invalidTimestamp Long The timestamp in milliseconds when the user expires.

Example

tuyaLockDevice.getLockUsers(new ITuyaResultCallback<List<BLELockUser>>() {
    @Override
    public void onError(String code, String message) {
        Log.e(TAG, "get lock users failed: code = " + code + "  message = " + message);
    }

    @Override
    public void onSuccess(List<BLELockUser> user) {
        Log.i(TAG, "get lock users success: lockUserBean = " + user);
    }
});

Create a lock member

Creates a non-home member to be associated with an unlocking record in later operations.

This API method only applies to non-home members. For more information about home member management, see Home Management.

Bluetooth Smart Lock

API description

/**
 * add lock user
 *
 * @param userName           userName
 * @param allowedUnlock      Whether allowed unlock with bluetooth
 * @param permanent          Whether the user is permanent
 * @param effectiveTimestamp User effective time
 * @param invalidTimestamp   User invalid time
 * @param avatarFile         avatar
 * @param callback           callback
 */
void addLockUser(final String userName, boolean allowedUnlock, boolean permanent, long effectiveTimestamp, long invalidTimestamp, File avatarFile, final ITuyaResultCallback<Boolean> callback);

Parameters

Parameter Description
userName The username.
allowedUnlock Specifies whether the member can unlock over Bluetooth.
unlockType The unlocking method. For more information, see the unlocking methods that are specified by TuyaUnlockType.
permanent Specifies whether the user is a permanent user.
effectiveTimestamp The timestamp when the non-permanent user takes effect. Unit: milliseconds. The user’s permanent parameter is set to false.
invalidTimestamp The timestamp when the non-permanent user expires. Unit: milliseconds. The user’s permanent parameter is set to false.
avatarFile The user avatar file.

Example

tuyaLockDevice.addLockUser("your_user_name", true, true, 0, 0, null, new ITuyaResultCallback<Boolean>() {
    @Override
    public void onError(String code, String message) {
        Log.e(TAG, "add lock user failed: code = " + code + "  message = " + message);
    }

    @Override
    public void onSuccess(Boolean result) {
        Log.i(TAG, "add lock user success");
    }
});

Modify a lock member

Modifies the information about a lock member, including the user name, avatar, and mapping with the unlocking password. This feature requires communication between your app and a Bluetooth lock. Your app must be connected to the lock over Bluetooth during the operation.

Bluetooth Smart Lock

API description

/**
 * update lock user
 *
 * @param userId             userId
 * @param userName           userName
 * @param allowedUnlock      Whether allowed unlock with bluetooth
 * @param permanent          Whether the user is permanent
 * @param effectiveTimestamp User effective time
 * @param invalidTimestamp   User invalid time
 * @param avatarFile         avatar
 * @param callback           callback
 */
void updateLockUser(final String userId, boolean allowedUnlock, final String userName, final boolean permanent, long effectiveTimestamp, long invalidTimestamp, File avatarFile, final ITuyaResultCallback<Boolean> callback);

Parameters

Parameter Description
userId The user ID.
allowedUnlock Specifies whether the member can unlock over Bluetooth.
userName The username.
permanent Specifies whether the user is a permanent user.
effectiveTimestamp The timestamp when the non-permanent user takes effect. Unit: milliseconds. The user’s permanent parameter is set to false.
invalidTimestamp The timestamp when the non-permanent user expires. Unit: milliseconds. The user’s permanent parameter is set to false.
avatarFile The user avatar file.

Example

tuyaLockDevice.updateLockUser("your_user_id", true, "your_user_name", true, 0, 0, null, new ITuyaResultCallback<Boolean>() {
    @Override
    public void onError(String code, String message) {
        Log.e(TAG, "update lock user failed: code = " + code + "  message = " + message);
    }

    @Override
    public void onSuccess(Boolean aBoolean) {
        Log.i(TAG, "update lock user success");
    }
});

Delete a lock member

You can call this operation to delete a lock member. This feature requires communication between your app and a Bluetooth lock. Your app must be connected to the lock over Bluetooth during the operation. After a lock member is deleted, all unlocking methods and passwords that are associated with the member are deleted.

Bluetooth Smart Lock

API description

/**
 * delete lock user
 * @param user user bean
 * @param callback  callback
 */
public void deleteLockUser(BLELockUser user, final ITuyaResultCallback<Boolean> callback)

Bluetooth connections

To use certain features of a Bluetooth lock, you must enable the Bluetooth feature on your app.

Query Bluetooth connection status

API description

The SDK can be used to enable an automatic connection with the lock over Bluetooth. The following API methods can be called to create a connection and query the connection status.

/**
 *  @return if lock online, return true
 */
public boolean isBLEConnected() 

Example

boolean online = tuyaLockDevice.isBLEConnected();

Connect to a Bluetooth lock

API description

If a Bluetooth lock is not connected to your app, you can call this operation to connect to the Bluetooth lock.

/**
 * connect to lock
 *
 * @param connectListener callback BLE lock connect status
 */
public void connect(ConnectListener connectListener)

Parameters

ConnectListener is a callback for the lock status. The onStatusChanged method indicates whether the lock is connected to your app.

Example

tuyaLockDevice.connect(new ConnectListener() {
    @Override
    public void onStatusChanged(boolean online) {
        Log.i(TAG, "onStatusChanged  online: " + online);
    }
});

Dynamic passwords

Users can enter a dynamic password to unlock a door. The dynamic password is valid for five minutes.

API description

public void getDynamicPassword(final ITuyaResultCallback<String> callback)

Parameters

Parameter Description
callback The callback.

Example

tuyaLockDevice.getDynamicPassword(new ITuyaResultCallback<String>() {
    @Override
    public void onError(String code, String message) {
        Log.e(TAG, "get lock dynamic password failed: code = " + code + "  message = " + message);
    }

    @Override
    public void onSuccess(String dynamicPassword) {
        Log.i(TAG, "get lock dynamic password success: dynamicPassword = " + dynamicPassword);
    }
});

Unlock and lock over Bluetooth

Unlock over Bluetooth

Bluetooth Smart Lock

API description

/**
 * unlock the door
 */
public void unlock(String lockUserId)

Parameters

Parameter Description
lockUserId The user ID that is associated with the lock. Each user of a lock is assigned an ID. It starts with 1, with an increment of 1 for each newly added user.

Example

// `1` indicates the current user ID that is associated with the lock.
tuyaLockDevice.unlock("1");

Lock over Bluetooth

Bluetooth Smart Lock

API description

You can call this operation to lock a door over Bluetooth after your app is connected to the Bluetooth lock.

/**
 * lock the door
 */
public void lock()

Example

tuyaLockDevice.lock();

Support for remote unlocking

API description

Specifies whether remote unlocking is supported.

/**
 * Whether to support remote unlock
 * @param callback callback
 */
void isRemoteUnlockAvailable(IResultCallback callback);

Example

tuyaLockDevice.isRemoteUnlockAvailable(new IResultCallback() {
    @Override
    public void onError(String code, String message) {
        Log.e(TAG, "get remote unlock available failed: code = " + code + "  message = " + message);
    }

    @Override
    public void onSuccess() {
        Log.i(TAG, "get remote unlock available success");
    }
});

Lock usage records

Get alert records

API description

/**
 * get alarm records
 * @param offset page number
 * @param limit item count
 * @param callback callback
 */
void getAlarmRecords(int offset, int limit, final ITuyaResultCallback<Record> callback);

Parameters

Parameter Description
offset The page number starting from which records are returned.
limit The maximum number of records to be returned in each call.

Data model of Record

Field Type Description
totalCount Integer The total number of records to be returned in each call.
hasNext Boolean Specifies whether to return the next page.
datas List The data that is included in a record.

Fields of DataBean

Field Type Description
userId String The member ID.
userName String The nickname of the user.
unlockType String The type of unlocking.
devId String The device ID.
createTime Long The timestamp when the record was created.
tags Integer The flag of the record. Valid values:
  • 0: other types of alarms
  • 1: duress alarm
unlockRelation UnlockRelation The instance that specifies the relationship between an unlocking type and an unlocking password number. Ignore this parameter for non-unlocking records.

Example

tuyaLockDevice. getAlarmRecords(0, 10, new ITuyaResultCallback<Record>() {
    @Override
    public void onError(String code, String message) {
        Log.e(TAG, "get lock records failed: code = " + code + "  message = " + message);
    }

    @Override
    public void onSuccess(Record recordBean) {
        Log.i(TAG, "get lock records success: recordBean = " + recordBean);
    }
});

Query unlocking records

API description

/**
 * get unlock records
 * @param unlockTypes unlock type list
 * @param offset page number
 * @param limit item count
 * @param callback callback
 */
void getUnlockRecords(int offset, int limit, final ITuyaResultCallback<Record> callback);

Parameters

Parameter Description
offset The page number starting from which records are returned.
limit The maximum number of records to be returned in each call.

Example

tuyaLockDevice.getUnlockRecords(0, 10, new ITuyaResultCallback<Record>() {
    @Override
    public void onError(String code, String message) {
        Log.e(TAG, "get unlock records failed: code = " + code + "  message = " + message);
    }

    @Override
    public void onSuccess(Record recordBean) {
        Log.i(TAG, "get unlock records success: recordBean = " + recordBean);
    }
});

Unlocking methods

This section describes the operations that are used to add, modify, or delete an unlocking method.

Add an unlocking method

The following procedure shows how to add an unlocking method.

Bluetooth Smart Lock

Get a list of unlocking methods

API description

/**
 * get unlock mode by unlockType
 *
 * @param unlockType unlock type {@link com.tuya.smart.optimus.lock.api.TuyaUnlockType}
 * @param callback callback
 */
void getUnlockModeList(String unlockType, final ITuyaResultCallback<ArrayList<UnlockMode>> callback);

Data model of UnlockMode

Field Type Description
userId String The user ID.
lockUserId Integer The user ID that is associated with the lock.
userName String The nickname of the user.
unlockAttr Integer The attribute of the unlocking method. Valid values:
  • 0: normal password
  • 1: password that indicates a duress alarm
userType Integer The type of user. Valid values:
  • 10: administrator
  • 20: ordinary user
  • 30: lock user
unlockModeId String The ID of the current unlocking method on the service end.
unlockId String The ID of the current unlocking method in the lock.
unlockName String The name of the current unlocking method.
unlockType String The type of unlocking method. For more information, see the settings of TuyaUnlockType.

Example

tuyaLockDevice.getUnlockModeList(TuyaUnlockType.PASSWORD, new ITuyaResultCallback<ArrayList<UnlockMode>>() {
    @Override
    public void onSuccess(ArrayList<UnlockMode> result) {
        Log.i(TAG, "getUnlockModeList  onSuccess: " + result);
    }

    @Override
    public void onError(String errorCode, String errorMessage) {
        Log.e(TAG, "getUnlockModeList failed: code = " + errorCode + "  message = " + errorMessage);
    }
});

Listen for unlocking method operations

This operation is called to return a result after you call the asynchronous operations that are used to add, modify, or delete unlocking methods.

API description

void setUnlockModeListener(UnlockModeListener unlockModeListener);

The following code block shows how to set UnlockModeListener:

public interface UnlockModeListener {

    /**
     * The unlocking method parameter is missing.
     */
    int FAILED_STATUS_ILLEGAL_ARGUMENT = -1;
    /**
     * The current operation does not support the specified unlocking method.
     */
    int FAILED_STATUS_NOT_SUPPORT_UNLOCK_TYPE = -2;
    /**
     * Failed to send a control command.
     */
    int FAILED_STATUS_SEND_ERROR = -3;
    /**
     * Failed to send a request to the service end.
     */
    int FAILED_STATUS_REQUEST_SERVER_ERROR = -4;
    /**
     * The fingerprint is incomplete.
     */
    int FAILED_STATUS_FINGERPRINT_INCOMPLETE = -5;
    /**
     * The service end fails to return a response.
     */
    int FAILED_STATUS_SERVER_RESPONSE_FAILED = -6;
    /**
     * The lock fails to return a response.
     */
    int FAILED_STATUS_LOCK_RESPONSE_FAILED = -7;
    /*----The following types of status are defined in a lock. An error code is returned to indicate the status when the system fails to create an unlocking method.----*/
    int FAILED_STATUS_TIMEOUT = 0x00;
    int FAILED_STATUS_FAILED = 0x01;
    int FAILED_STATUS_REPEAT = 0x02;
    int FAILED_STATUS_LOCK_ID_EXHAUSTED = 0x03;
    int FAILED_STATUS_PASSWORD_NOT_NUMBER = 0x04;
    int FAILED_STATUS_PASSWORD_WRONG_LENGTH = 0x05;
    int FAILED_STATUS_NOT_SUPPORT = 0x06;
    int FAILED_STATUS_ALREADY_ENTERED = 0x07;
    int FAILED_STATUS_ALREADY_BOUND_CARD = 0x08;
    int FAILED_STATUS_ALREADY_BOUND_FACE = 0x09;
    int FAILED_STATUS_PASSWORD_TOO_SIMPLE = 0x0A;
    int FAILED_STATUS_WRONG_LOCK_ID = 0xFE;

    /**
     * The callback used to add, modify, or delete an unlocking method.
     *
     * @param devId              The device ID.
     * @param userId             The user ID.
     * @param unlockModeResponse The response.
     */
    void onResult(String devId, String userId, UnlockModeResponse unlockModeResponse);
}

Parameters

Field Type Description
unlockMethod String The type of unlocking method operation. Valid values:
/** Add an unlocking method  */
public static final String UNLOCK_METHOD_CREATE = “unlock_method_create”;
/** Modify an unlocking method */
public static final String UNLOCK_METHOD_MODIFY = “unlock_method_modify”;
/** Delete an unlocking method */
public static final String UNLOCK_METHOD_DELETE = “unlock_method_delete”;
unlockType String The type of unlocking method. For more information, see the settings of TuyaUnlockType.
stage Integer The current stage in which the lock is managed. by BleLockConstant. Valid values:
int STAGE_AFTER = -2;   // Synchronizes data to the service end after the lock is managed.
int STAGE_BEFORE = -1; // Runs tasks, such as command delivery and communication with the service end, before communication with the lock.
int STAGE_START = 0x00; // Starts the unlocking method enrollment.
int STAGE_CANCEL = 0xFE;// Cancels the unlocking method enrollment.
int STAGE_FAILED = 0xFD;// Failed to enroll the unlocking method.
int STAGE_ENTERING = 0xFC;// Enrolling the unlocking method.
int STAGE_SUCCESS = 0xFF;// The unlocking method is enrolled.
lockUserId Integer The user ID that is associated with the lock.
unlockId Integer The ID of the current unlocking method in the lock.
unlockModeId String The ID of the current unlocking method on the service end.
admin Boolean Specifies whether the user is an administrator.
times Integer The number of times the specified password can be used as expected. Valid values:
  • 0: a permanently valid password.
  • 1 to 254: the number of times the password can be used as expected.
  • Other value: an invalid password.
status Integer The HTTP status code of an error message. For more information, see UnlockModeListener.
failedStage Integer The stage in which the error has occurred. This parameter is required only when stage is set to STAGE_FAILED.

Example

tuyaLockDevice.setUnlockModeListener(new UnlockModeListener() {
  @Override
  public void onResult(String devId, String userId, UnlockModeResponse unlockModeResponse) {
    Log.i(TAG, "UnlockModeListener devId: " + devId);
    Log.i(TAG, "UnlockModeListener userId: " + userId);
    Log.i(TAG, "UnlockModeListener unlockType: " + unlockModeResponse.unlockType);
    Log.d(TAG, "UnlockModeListener: " + unlockModeResponse);
    if (unlockModeResponse.success) {
      if (TextUtils.equals(unlockModeResponse.unlockMethod, UnlockModeResponse.UNLOCK_METHOD_CREATE)) {
        Log.i(TAG, "Create unlock mode success");
      } else if (TextUtils.equals(unlockModeResponse.unlockMethod, UnlockModeResponse.UNLOCK_METHOD_MODIFY)) {
        Log.i(TAG, "Modify unlock mode success");
      } else if (TextUtils.equals(unlockModeResponse.unlockMethod, UnlockModeResponse.UNLOCK_METHOD_DELETE)) {
        Log.i(TAG, "Delete unlock mode success");
      }
    } else if (unlockModeResponse.stage == BleLockConstant.STAGE_FAILED) {
      if (TextUtils.equals(unlockModeResponse.unlockMethod, UnlockModeResponse.UNLOCK_METHOD_CREATE)) {
        Log.w(TAG, "Create unlock mode failed.");
        Log.w(TAG, "Create unlock mode failed reason: " + unlockModeResponse.status);
        Log.w(TAG, "Create unlock mode failed stage: " + unlockModeResponse.failedStage);
      } else if (TextUtils.equals(unlockModeResponse.unlockMethod, UnlockModeResponse.UNLOCK_METHOD_MODIFY)) {
        Log.w(TAG, "Modify unlock mode failed.");
        Log.w(TAG, "Modify unlock mode failed reason: " + unlockModeResponse.status);
        Log.w(TAG, "Modify unlock mode failed stage: " + unlockModeResponse.failedStage);
      } else if (TextUtils.equals(unlockModeResponse.unlockMethod, UnlockModeResponse.UNLOCK_METHOD_DELETE)) {
        Log.w(TAG, "Delete unlock mode failed.");
        Log.w(TAG, "Delete unlock mode failed reason: " + unlockModeResponse.status);
        Log.w(TAG, "Delete unlock mode failed stage: " + unlockModeResponse.failedStage);
      }
    }
  }
});

Add an unlocking method

API description

You can call this operation to add an unlocking method based on the specified unlocking type. Your app must be connected to the lock over Bluetooth during the operation.

/**
 * Add unlock method.
 *
 * @param unlockType TuyaUnlockType {@link com.tuya.smart.optimus.lock.api.TuyaUnlockType}
 * @param user       BLELockUser {@link com.tuya.smart.sdk.optimus.lock.bean.ble.BLELockUser}
 * @param name       Unlock mode name.
 * @param password   Unlock mode password. If it is not the password unlock method, this field can be null
 * @param times      Number of times the unlock mode can be used. The value range is 0 to 254, 0 means unlimited times, and 1 ~ 254 is the actual number of times.
 * @param isHijack   Hijack flag. If it is true, a hijacking alarm will be triggered when unlocking with this unlock mode.
 */
void addUnlockMode(final String unlockType, final BLELockUser user, String name, String password, int times, boolean isHijack);

Parameters

Field Description
unlockType The type of unlocking method. For more information, see the settings of TuyaUnlockType.
user The user data model BLELockUser.
name The name of the unlocking method.
password The password of the unlocking method.
  • For the password-based unlocking method, this parameter is required.
  • For other types of unlocking methods, this parameter is optional.
times The number of times the specified password can be used as expected. Valid values:
  • 0: a permanently valid password.
  • 1 to 254: the number of times the password can be used as expected.
  • Other value: an invalid password.
isHijack The flag that specifies whether the unlocking method is associated with a duress alarm. When this parameter is set to true, if the specified password is used to unlock the door, a duress alarm is triggered.

Example

The following code block shows how to set a password for a home member:

tuyaLockDevice.getHomeUsers(new ITuyaResultCallback<List<BLELockUser>>() {
    @Override
    public void onSuccess(List<BLELockUser> result) {
        Log.i(TAG, "getHomeUsers  onSuccess: " + result);
        // add password unlock mode
        tuyaLockDevice.addUnlockMode(TuyaUnlockType.PASSWORD, result.get(0), "test_unlock_mode1", "431232", 0, false);
    }

    @Override
    public void onError(String errorCode, String errorMessage) {
        Log.e(TAG, "getHomeUsers failed: code = " + errorCode + "  message = " + errorMessage);
    }
});

Update unlocking method data

API description

You can call this operation to update the name of an unlocking method or modify the duress tag. Modifies a lock member. This feature requires communication between your app and the cloud, rather than a Bluetooth lock. Your app does not need to be connected to the lock over Bluetooth during the operation.

/**
 * Update name and hijack flag of the unlocking method. Only update server information, not communicate with door lock device
 *
 * @param unlockMode UnlockMode bean {@link com.tuya.smart.sdk.optimus.lock.bean.ble.UnlockMode}
 * @param name       Unlock mode name
 * @param isHijack   Hijack flag. If it is true, a hijacking alarm will be triggered when unlocking with this unlock mode.
 */
void updateUnlockModeServerInfo(UnlockMode unlockMode, String name, boolean isHijack);

Parameters

Field Description
unlockMode The data model of the unlocking method.
name The name of the unlocking method.
isHijack The flag that specifies whether the unlocking method is associated with a duress alarm. When this parameter is set to true, if the specified password is used to unlock the door, a duress alarm is triggered.

Example

tuyaLockDevice.getUnlockModeList(TuyaUnlockType.FINGERPRINT, new ITuyaResultCallback<ArrayList<UnlockMode>>() {
    @Override
    public void onSuccess(ArrayList<UnlockMode> result) {
        Log.i(TAG, "getUnlockModeList  onSuccess: " + result);
        for (UnlockMode unlockMode : result) {
            if (TextUtils.equals(unlockMode.unlockName, "test_unlock_mode1")) {
                tuyaLockDevice.updateUnlockModeServerInfo(unlockMode, "test_unlock2", false);// rename unlock mode
            }
        }
    }

    @Override
    public void onError(String errorCode, String errorMessage) {
        Log.e(TAG, "getUnlockModeList failed: code = " + errorCode + "  message = " + errorMessage);
    }
});

Delete an unlocking method

API description

Deletes a card unlocking method. Your app must be connected to the lock over Bluetooth during the operation.

/**
 * Delete unlockMode.
 *
 * @param unlockMode unlockMode
 */
void deleteUnlockMode(UnlockMode unlockMode);

Example

tuyaLockDevice.deleteUnlockMode(unlockMode);

Cancel fingerprint enrollment

API description

You can call this operation to cancel fingerprint enrollment. To unlock a door with a fingerprint, you might need to enroll the fingerprint four to five times. Your app must be connected to the lock over Bluetooth during the cancel process.

/**
 * Cancel fingerprint entry.
 * <p>
 * The fingerprint entry process will be repeated multiple times and can be canceled during the entry process.
 *
 * @param user BLELockUser {@link com.tuya.smart.sdk.optimus.lock.bean.ble.BLELockUser}
 */
void cancelFingerprintUnlockMode(final BLELockUser user);

Update an unlocking password

API description

Updates an unlocking password after a password-based unlocking method is created. You can call this operation to update information about the password of an unlocking method. The information includes the password, password name, number of times the password can be used as expected, and duress flag. Your app must be connected to the lock over Bluetooth during the operation.

This operation supports only the password-based unlocking method.

/**
 * Update the name, password, validity period, and other information of the unlocking method
 *
 * @param unlockMode UnlockMode bean {@link com.tuya.smart.sdk.optimus.lock.bean.ble.UnlockMode}
 * @param name       Unlock mode name
 * @param password   Unlock mode password. If it is not the password unlock method, this field can be null
 * @param times      Number of times the unlock mode can be used. The value range is 0 to 254, 0 means unlimited times, and 1 ~ 254 is the actual number of times.
 * @param isHijack   Hijack flag. If it is true, a hijacking alarm will be triggered when unlocking with this unlock mode.
 */
void updatePasswordUnlockMode(UnlockMode unlockMode, String name, String password, int times, boolean isHijack);

Parameters

Field Description
unlockMode The data model of the unlocking method.
name The name of the unlocking method.
password The password of the unlocking method.
  • For the password-based unlocking method, this parameter is required.
  • For other types of unlocking methods, this parameter is optional.
times The number of times the specified password can be used as expected. Valid values:
  • 0: a permanently valid password.
  • 1 to 254: the number of times the password can be used as expected.
  • Other value: an invalid password.
isHijack The flag that specifies whether the unlocking method is associated with a duress alarm. When this parameter is set to true, if the specified password is used to unlock the door, a duress alarm is triggered.

Example

tuyaLockDevice.getUnlockModeList(TuyaUnlockType.PASSWORD, new ITuyaResultCallback<ArrayList<UnlockMode>>() {
    @Override
    public void onSuccess(ArrayList<UnlockMode> result) {
        Log.i(TAG, "getUnlockModeList  onSuccess: " + result);
        for (UnlockMode unlockMode : result) {
            if (TextUtils.equals(unlockMode.unlockName, "test_password")) {
                tuyaLockDevice.updatePasswordUnlockMode(unlockMode, "test_password", "131232", 0, false);// modify password
            }
        }
    }

    @Override
    public void onError(String errorCode, String errorMessage) {
        Log.e(TAG, "getUnlockModeList failed: code = " + errorCode + "  message = " + errorMessage);
    }
});

Temporary passwords

Temporary passwords are added to a lock for temporary use. This type of password is classified into one-time passwords and periodic passwords.

  • One-time passwords can be used only once and then become invalid.
  • Periodic passwords are valid only within a specified period.

Add a temporary password

The following procedure shows how to add a temporary password.

Bluetooth Smart Lock

Register a temporary password listener

You can call this operation to register a temporary password listener. This listener is used as a callback to add, modify, or delete a temporary password.

API description

/**
 * Set temporary password listener
 *
 * @param temporaryPasswordListener temporary password listener
 */
void setTemporaryPasswordListener(TemporaryPasswordListener temporaryPasswordListener);

Parameters

Field Description
temporaryPasswordListener The listener that is used to add, modify, or delete a temporary password.

Listen for events

public interface TemporaryPasswordListener {

    /**
     * Create a temporary password.
     */
    String TEMPORARY_PASSWORD_CREATE = "temporary_password_creat";
    /**
     * Modify the temporary password.
     */
    String TEMPORARY_PASSWORD_MODIFY = "temporary_password_modify";
    /**
     * Delete the temporary password.
     */
    String TEMPORARY_PASSWORD_DELETE = "temporary_password_delete";

    /*----Error codes returned when the temporary password failed to be added, modified, or deleted----*/
    /**
     * illegal argument
     */
    int FAILED_STATUS_ILLEGAL_ARGUMENT = -1;
    /**
     * Device not support such method
     */
    int FAILED_STATUS_NOT_SUPPORT_UNLOCK_TYPE = -2;
    /**
     * Command send to device failed
     */
    int FAILED_STATUS_SEND_FAILED = -3;
    /**
     * Request server failed
     */
    int FAILED_STATUS_REQUEST_SERVER_FAILED = -4;
    /**
     * Device offline
     */
    int FAILED_STATUS_DEVICE_OFFLINE = -5;
    /**
     * Server response failed
     */
    int FAILED_STATUS_SERVER_RESPONSE_FAILED = -6;
    /** Lock response failed */
    int FAILED_STATUS_LOCK_RESPONSE_FAILED = 1;
    /** Lock sequence number exhausted */
    int FAILED_STATUS_SEQUENCE_NUMBER_EXHAUSTED = 2;

    /**
     * The callback used to add, modify, or delete an unlocking method.
     *
     * @param sn The serial number of the password.
     */
    void onSuccess(String type, int sn);

    /**
     * The callback used to add, modify, or delete an unlocking method.
     *
     * @param type       The type of operation, for example, to add, delete, or modify.
     * @param resultCode The HTTP status code.
     */
    void onFailed(String type, int resultCode);
}

Example

tuyaLockDevice.setTemporaryPasswordListener(new TemporaryPasswordListener() {
    @Override
    public void onSuccess(String type, int sn) {
        switch (type) {
            case TemporaryPasswordListener.TEMPORARY_PASSWORD_CREATE:
                Log.i(TAG, "temporary password create success, passsword sequence number: " + sn);
                break;
            case TemporaryPasswordListener.TEMPORARY_PASSWORD_MODIFY:
                Log.i(TAG, "temporary password modify success, passsword sequence number: " + sn);
                break;
            case TemporaryPasswordListener.TEMPORARY_PASSWORD_DELETE:
                Log.i(TAG, "temporary password delete success, passsword sequence number: " + sn);
                break;
        }
    }

    @Override
    public void onFailed(String type, int resultCode) {
        switch (type) {
            case TemporaryPasswordListener.TEMPORARY_PASSWORD_CREATE:
                Log.w(TAG, "temporary password create failed, resultCode: " + resultCode);
                break;
            case TemporaryPasswordListener.TEMPORARY_PASSWORD_MODIFY:
                Log.w(TAG, "temporary password modify failed, resultCode: " + resultCode);
                break;
            case TemporaryPasswordListener.TEMPORARY_PASSWORD_DELETE:
                Log.w(TAG, "temporary password delete failed, resultCode: " + resultCode);
                break;
        }
    }
});

Query temporary password list

You can call this operation to get a list of temporary passwords. Temporary passwords are classified into one-time passwords and periodic passwords.

API description

/**
 * @param availTimes Specify a one-time password or a periodic password. Valid values: `0` to represent a periodic password and `1` to represent a one-time password.
 */
public void getTempPasswordList(int availTimes, final ITuyaDataCallback<List<TempPasswordBeanV3>> dataCallback);

Data model of TempPasswordBeanV3

Field Description Type
effective The status of the temporary password. Valid values:
  • 1: to be effective
  • 2: to be sent
  • 3: in use
  • 4: to be deleted
  • 5: expired
Integer
availTimes Specify a one-time password or a periodic password. Valid values:
  • 0: a periodic password
  • 1: a one-time password
Integer
passwordId The ID of the temporary password on the service end. Integer
sn The serial number of the password in the lock. Integer
name The name of the temporary password. String
scheduleBean The period in which the password is valid. Ignore this parameter for a one-time password. ScheduleBean
phone The mobile number. Users can be asked to fill in this field if you have subscribed to the SMS service. Otherwise, pass in an empty value. String
effectiveTime The 13-digit timestamp when the password takes effect. Long
invalidTime The 13-digit timestamp when the password expires. Long

Fields of ScheduleBean

Field Description Type
allDay Specifies whether the password is valid for the whole day. When the value is set to true, ignore effectiveTime and invalidTime. Boolean
effectiveTime The number of minutes starting from which the password becomes valid in a day. Integer
invalidTime The number of minutes starting from which the password becomes invalid in a day. Integer
dayOfWeeks The date on which the password becomes valid in a week. Set

Example

// Get a periodic password.
tuyaLockDevice.getTempPasswordList(0, new ITuyaDataCallback<List<TempPasswordBeanV3>>() {
    @Override
    public void onSuccess(List<TempPasswordBeanV3> result) {
        Log.i(TAG, "getTempPasswordList  onSuccess: " + result);
    }

    @Override
    public void onError(String errorCode, String errorMessage) {
        Log.e(TAG, "getTempPasswordList failed: code = " + errorCode + "  message = " + errorMessage);
    }
});
// Get a one-time password.
tuyaLockDevice.getTempPasswordList(1, new ITuyaDataCallback<List<TempPasswordBeanV3>>() {
    @Override
    public void onSuccess(List<TempPasswordBeanV3> result) {
        Log.i(TAG, "getTempPasswordList  onSuccess: " + result);
    }

    @Override
    public void onError(String errorCode, String errorMessage) {
        Log.e(TAG, "getTempPasswordList failed: code = " + errorCode + "  message = " + errorMessage);
    }
});

Verify temporary password

Verifies the validity of the parameters for a specified temporary password.

API description

/**
 * @param availTimes    Specify a one-time password or a periodic password. Valid values: `0` that specifies a periodic password and `1` that specifies a one-time password.
 * @param name          The name of the temporary password.
 * @param password      The temporary password.
 * @param scheduleBean  The period in which the password is valid. Ignore this parameter for a one-time password.
 * @param phone         The mobile phone number. Users can be asked to fill in this field if you have subscribed to the SMS service. Otherwise, pass in an empty value.
 * @param countryCode   The country code. Users can be asked to fill in this field if you have subscribed to the SMS service. Otherwise, pass in an empty value.
 * @param effectiveTime The 13-digit timestamp when the password takes effect.
 * @param invalidTime   The 13-digit timestamp when the password expires.
 * @param callback      The callback.
 */
void validateTempPassword(int availTimes, String name, String password, ScheduleBean scheduleBean, String phone, String countryCode, long effectiveTime, long invalidTime, IResultCallback callback);

Parameters

Field Description Optional
availTimes Specifies a one-time password or a periodic password. Valid values: 0: a periodic password. 1: a one-time password. No
name The name of a specified temporary password. No
password The password. No
scheduleBean The period in which the password is valid. Ignore this parameter for a one-time password. Yes
phone The mobile phone number. Users can be asked to fill in this field if you have subscribed to the SMS service. Otherwise, pass in an empty value. Yes
countryCode The country code. Users can be asked to fill in this field if you have subscribed to the SMS service. Otherwise, pass in an empty value. Yes
effectiveTime The 13-digit timestamp when the password takes effect. No
invalidTime The 13-digit timestamp when the password expires. No

The following table describes the fields of scheduleBean.

Field Description Type
allDay Specifies whether the password is valid for the whole day. When the value is set to true, ignore effectiveTime and invalidTime. Boolean
effectiveTime The number of minutes starting from which the password becomes valid in a day. int
invalidTime The number of minutes starting from which the password becomes invalid in a day. int
dayOfWeeks The day(s) of the week on which the password becomes valid. Set

Example

tuyaLockDevice.validateTempPassword(1, "your_password_name", "111222", null, "", "", System.currentTimeMillis(), System.currentTimeMillis() + 24 * 60 * 60 * 1000, new IResultCallback() {
    @Override
    public void onError(String code, String message) {
        Log.e(TAG, "validate temp password failed: code = " + code + "  message = " + message);
    }

    @Override
    public void onSuccess() {
        Log.i(TAG, "validate temp password success");
    }
});

Create a temporary password

Creates a temporary password. Temporary passwords are classified into one-time passwords and periodic passwords.

API description

/**
 * @param availTimes    Specify a one-time password or a periodic password. Valid values: `0` to represent a periodic password and `1` to represent a one-time password.
 * @param name          The name of the temporary password.
 * @param password      The temporary password.
 * @param scheduleBean  The period in which the password is valid. Ignore this parameter for a one-time password.
 * @param phone         The mobile number. Users can be asked to fill in this field if you have subscribed to the SMS service. Otherwise, pass in an empty value.
 * @param countryCode   The country code. Users can be asked to fill in this field if you have subscribed to the SMS service. Otherwise, pass in an empty value.
 * @param effectiveTime The 13-digit timestamp when the password takes effect.
 * @param invalidTime   The 13-digit timestamp when the password expires.
 */
public void createTempPassword(final int availTimes, final String name, final String password, final ScheduleBean scheduleBean, final String phone, final String countryCode, final long effectiveTime, final long invalidTime);

Parameters

Field Description Optional
availTimes Specify a one-time password or a periodic password. Valid values:
  • 0: a periodic password
  • 1: a one-time password
No
name The name of the temporary password. No
password The password. No
scheduleBean The period in which the password is valid. Ignore this parameter for a one-time password. Yes
phone The mobile number. Users can be asked to fill in this field if you have subscribed to the SMS service. Otherwise, pass in an empty value. Yes
countryCode The country or region code. Users can be asked to fill in this field if you have subscribed to the SMS service. Otherwise, pass in an empty value. Yes
effectiveTime The 13-digit timestamp when the password takes effect. No
invalidTime The 13-digit timestamp when the password expires. No

The following table describes the fields of scheduleBean.

Field Description Type
allDay Specifies whether the password is valid for the whole day. When the value is set to true, ignore effectiveTime and invalidTime. Boolean
effectiveTime The number of minutes starting from which the password becomes valid in a day. Integer
invalidTime The number of minutes starting from which the password becomes invalid in a day. Integer
dayOfWeeks The date on which the password becomes valid in a week. Set

Example

  • The following code block shows how to add a one-time password:

    tuyaLockDevice.createTempPassword(1, "your_password_name", "111222", null, "", "", System.currentTimeMillis(), System.currentTimeMillis() + 24 * 60 * 60 * 1000);
    
  • The following code block shows how to add a periodic password:

    ScheduleBean scheduleBean = new ScheduleBean();
    scheduleBean.allDay = false; // `false` specifies that the password is not valid for the whole day, but valid for some time of the day.
    scheduleBean.effectiveTime = 480; // The password takes effect on the 480th minute of the day. The 480th minute means 08:00 (UTC+8).
    scheduleBean.invalidTime = 1080; // The password expires on the 1,080th minute of the day. The 1,080th minute means 18:00 (UTC+8).
    // Add the number of days for which the password is valid.
    scheduleBean.dayOfWeeks.add(ScheduleBean.DayOfWeek.MONDAY);
    scheduleBean.dayOfWeeks.add(ScheduleBean.DayOfWeek.TUESDAY);
    scheduleBean.dayOfWeeks.add(ScheduleBean.DayOfWeek.WEDNESDAY);
    scheduleBean.dayOfWeeks.add(ScheduleBean.DayOfWeek.THURSDAY);
    scheduleBean.dayOfWeeks.add(ScheduleBean.DayOfWeek.FRIDAY);
    scheduleBean.dayOfWeeks.add(ScheduleBean.DayOfWeek.SATURDAY);
    scheduleBean.dayOfWeeks.add(ScheduleBean.DayOfWeek.SUNDAY);
    tuyaLockDevice.createTempPassword(0, "your_password_name", "111222", scheduleBean, "", "", System.currentTimeMillis(), System.currentTimeMillis() + 24 * 60 * 60 * 1000);
    

Modify a temporary password

Bluetooth Smart Lock

API description

/**
 * @param availTimes    Specify a one-time password or a periodic password. Valid values: `0` to represent a periodic password and `1` to represent a one-time password.
 * @param passwordId    The ID of the temporary password on the service end.
 * @param sn            The serial number of the password in the lock.
 * @param name          The name of the temporary password.
 * @param scheduleBean  The period in which the password is valid. Ignore this parameter for a one-time password.
 * @param phone         The mobile number. Users can be asked to fill in this field if you have subscribed to the SMS service. Otherwise, pass in an empty value.
 * @param countryCode   The country code. Users can be asked to fill in this field if you have subscribed to the SMS service. Otherwise, pass in an empty value.
 * @param effectiveTime The 13-digit timestamp when the password takes effect.
 * @param invalidTime   The 13-digit timestamp when the password expires.
 */
public void modifyTempPassword(final int availTimes, int passwordId, int sn, final String name, final ScheduleBean scheduleBean, final String phone, final String countryCode, final long effectiveTime, final long invalidTime);

Parameters

Field Description Optional
availTimes Specifies a one-time password or a periodic password. Valid values:
  • 0: a periodic password
  • 1: a one-time password
No
passwordId The ID of the temporary password on the service end. No
sn The serial number of the password in the lock. No
name The name of the temporary password. No
scheduleBean The period in which the password is valid. Ignore this parameter for a one-time password. Yes
phone The mobile number. Users can be asked to fill in this field if you have subscribed to the SMS service. Otherwise, pass in an empty value. Yes
countryCode The country or region code. Users can be asked to fill in this field if you have subscribed to the SMS service. Otherwise, pass in an empty value. Yes
effectiveTime The 13-digit timestamp when the password takes effect. No
invalidTime The 13-digit timestamp when the password expires. No

Example

  • The following code block shows how to modify a one-time password

    tuyaLockDevice.modifyTempPassword(1, 2202004, 2, "your_password_name", null, "", "", System.currentTimeMillis(), System.currentTimeMillis() + 24 * 60 * 60 * 1000);
    
  • Modify a periodic password

    ScheduleBean scheduleBean = new ScheduleBean();
    scheduleBean.allDay = true; // The password is valid for the whole day. You do not need to specify the time when the password takes effect.
    scheduleBean.effectiveTime = 0;
    scheduleBean.invalidTime = 0;
    scheduleBean.dayOfWeeks.add(ScheduleBean.DayOfWeek.FRIDAY);
    tuyaLockDevice.modifyTempPassword(0, 2202005, 3, "your_password_name", scheduleBean, "", "", System.currentTimeMillis(), System.currentTimeMillis() + 24 * 60 * 60 * 1000);
    

Delete a temporary password

Bluetooth Smart Lock

API description

/**
 * @param passwordId The ID of the temporary password on the service end.
 * @param sn         The serial number of the password in the lock.
 */
public void deleteTempPassword(int passwordId, int sn);

Parameters

Field Description Optional
passwordId The ID of the temporary password on the service end. No
sn The serial number of the password in the lock. No

Example

tuyaLockDevice.deleteTempPassword(2202004, 2);

List of lock DPs

DP name DP identifier (dpCode)
Add an unlocking method unlock_method_create
Delete an unlocking method unlock_method_delete
Modify an unlocking method unlock_method_modify
Disable an unlocking method unlock_method_freeze
Enable an unlocking method unlock_method_enable
Unlock over Bluetooth bluetooth_unlock
Get feedback on Bluetooth-based unlocking bluetooth_unlock_fb
Remaining battery capacity residual_electricity
Battery status battery_state
Child lock status child_lock
Double lock by lifting up anti_lock_outside
Unlock with a fingerprint unlock_fingerprint
Unlock with a normal password unlock_password
Unlock with a dynamic password unlock_dynamic
Unlock with a card unlock_card
Unlock with a mechanical key unlock_key
Door opening and closing events open_close
Unlock from the inside of the door open_inside
Records of Bluetooth-based unlocking unlock_ble
Door opened door_opened
Alerts alarm_lock
Duress alarms hijack
Doorbell call doorbell
SMS notification message
Chime sounds doorbell_song
Sound level of the chime doorbell_volume
Language switching language
Manage welcome messages on the display screen welcome_words
Volume on keypress key_tone
Local voice guidance volume beep_volume
Double locking status reverse_lock
Switch of automatic latch automatic_lock
Switch between single unlocking and combination unlocking unlock_switch
Synchronize unlocking methods among members synch_member
Set the latency of automatic latch auto_lock_time
Timed automatic locking auto_lock_timer
Number of fingerprint enrollments finger_input_times
Unlock with biometric recognition unlock_face
Open and closed status of the door closed_opened
Unlock with irises unlock_eye
Unlock with palm prints unlock_hand
Unlock with finger veins unlock_finger_vein
Hardware RTC rtc_lock
Report of countdown for automatic locking auto_lock_countdown
Manual locking manual_lock
Locking status lock_motor_state
Rotation direction of the motor on a smart stick lock lock_motor_direction
Disable users unlock_user_freeze
Enable users unlock_user_enable
Add a temporary password to a Bluetooth lock temporary password_creat
Delete a temporary password from a Bluetooth lock temporary password_delete
Modify a temporary password of a Bluetooth lock temporary password_modify
Synchronize unlocking methods (large datasets) synch_method
Unlock with a temporary password unlock_temporary
Motor torque motor_torque
Records of combination unlocking unlock_double
Switch of the arm away mode arming_mode
Configure password-free remote unlocking remote_no_pd_setkey
Password-free remote unlocking with keys remote_no_dp_key
Remote unlocking with mobile phones unlock_phone_remote
Remote unlocking with voice unlock_voice_remote
Send the offline password T0 time password_offline_time
Report the clearing of a single offline password unlock_offline_clear_single
Report the clearing of offline passwords unlock_offline_clear
Report offline password unlocking unlock_offline_pd