Wi-Fi Smart Lock

Last Updated on : 2024-11-18 11:33:15download

Description of classes

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.
ITuyaWifiLock The Wi-Fi lock class that includes all methods of Wi-Fi locks.

Example

The following code block shows how to create a Wi-Fi 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 `ITuyaWifiLock`.
ITuyaWifiLock tuyaLockDevice = tuyaLockManager.getWifiLock("your_lock_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.
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

public void getLockUsers(final ITuyaResultCallback<List<WifiLockUser>> callback)

Fields of WifiLockUser

Field Type Description
userId String The member ID.
userName String The nickname of the user.
avatarUrl String The URL of the avatar.
contact String The contact method.
unlockRelations List The unlocking method and password serial number.
devId String The device ID.
ownerId String The home ID.
userType int The type of lock member. Valid values:
  • 1: home member
  • 2: non-home member

Example

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

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

Create a lock member

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

API description

public void addLockUser(final String userName, File avatarFile, final List<UnlockRelation> unlockRelations, final ITuyaResultCallback<String> callback)

Parameters

Parameter Optional Description
userName No The name of the member.
avatarFile Yes The avatar of the member. If it is not set, the default avatar is used.
unlockRelations No The mapping between the unlocking method and the password serial number.

You can call getRecords to get the value of UnlockRelation. After unlocking with a password or another method, an unlocking record can be obtained. The unlocking method in the unlocking record can be assigned to a user.

Fields of UnlockRelationBean

Field Type Description
TuyaUnlockType Enum The unlocking method.
passwordNumber int The associated password serial number. Valid values: 0 to 999.

Example

ArrayList<UnlockRelation> unlockRelations = new ArrayList<>();
UnlockRelation unlockRelation = new UnlockRelation();
unlockRelation.unlockType = TuyaUnlockType.PASSWORD;
unlockRelation.passwordNumber = 1;
unlockRelations.add(unlockRelation);
File avatarFile = new File(getFilesDir(), "1.png");
tuyaLockDevice.addLockUser("Pan", avatarFile , unlockRelations, new ITuyaResultCallback<String>() {
    @Override
    public void onError(String code, String message) {
        Log.e(TAG, "add lock user failed: code = " + code + "  message = " + message);
    }

    @Override
    public void onSuccess(String userId) {
        Log.i(TAG, "add lock user success: " + userId);
    }
});

Modify a lock member

API description

Modifies the information about a lock member, including the user name, avatar, and mapping with the unlocking password.

public void updateLockUser(final String userId, final String userName, File avatarFile, final List<UnlockRelation> unlockRelations, final ITuyaResultCallback<Boolean> callback)

Parameters

Parameter Optional Description
userId No The member ID, required.
userName Yes The username of the member. This parameter is optional and not changed if not set.
avatarFile Yes The avatar of the member. If it is not set, the default avatar is used.
unlockRelations No The mapping between the unlocking method and the password serial number. This parameter is required and not changed if not set.

Example

ArrayList<UnlockRelation> unlockRelations = new ArrayList<>();
UnlockRelation unlockRelation = new UnlockRelation();
unlockRelation.unlockType = TuyaUnlockType.PASSWORD;
unlockRelation.passwordNumber = 1;
unlockRelations.add(unlockRelation);
tuyaLockDevice.updateLockUser("0000005f1g", "pan", null, unlockRelations, 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");
    }
});

Modify an unlocking method

API description

Modifies only an unlocking method that is assigned to a home member. The username and avatar of the member are not modified in this call.

The username, avatar, and other information about a member can be modified only in the API requests mentioned in Home Management.

public void updateFamilyUserUnlockMode(String userId, List<UnlockRelation> unlockRelations, ITuyaResultCallback<Boolean> callback)

Parameters

Parameter Optional Description
userId No The member ID, required.
unlockRelations No The mapping between the unlocking method and the password serial number.

Example

ArrayList<UnlockRelation> unlockRelations = new ArrayList<>();
UnlockRelation unlockRelation = new UnlockRelation();
unlockRelation.unlockType = TuyaUnlockType.PASSWORD;
unlockRelation.passwordNumber = 1;
unlockRelations.add(unlockRelation);
tuyaLockDevice.updateFamilyUserUnlockMode("your_family_user_id", unlockRelations, new ITuyaResultCallback<Boolean>() {
    @Override
    public void onError(String code, String message) {
        Log.e(TAG, "update family user failed: code = " + code + "  message = " + message);
    }

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

Delete a lock member

API description

Deletes the information about a lock member. After the member is deleted, the existing password is not deleted.

public void deleteLockUser(String userId, final ITuyaResultCallback<Boolean> callback)

Parameters

Parameter Description
userId The member ID.

Example

tuyaLockDevice.deleteLockUser("0000004pnk", new ITuyaResultCallback<Boolean>() {
    @Override
    public void onError(String code, String message) {
        Log.e(TAG, "delete lock user failed: code = " + code + "  message = " + message);
    }

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

Temporary passwords

Creates a temporary password. Users can enter this password to unlock a door.

Wi-Fi Smart Lock

Query temporary password list

Returns a list of temporary passwords. The usage status of each temporary password is also displayed.

API description

public void getTempPasswords(final ITuyaResultCallback<List<TempPassword>> callback)

Data model of TuyaSmartLockTempPwdModel

Field Type Description
phone String The mobile phone number.
name String The name of the temporary password.
countryCode String The country or region code.
invalidTime long The timestamp in milliseconds when the temporary password expires.
effectiveTime long The timestamp in milliseconds when the temporary password takes effect.
createTime long The timestamp in milliseconds when the temporary password was created.
id int The unique ID of the temporary password.
sequenceNumber int The serial number of the password, associated with a user account.
status int The status of the temporary password.

Valid values of status include:

int REMOVED = 0; // Deleted
int INVALID = 1; // Invalid
int TO_BE_PUBILSH = 2; // To be sent
int WORKING = 3; // Being used
int TO_BE_DELETED = 4; // To be deleted
int EXPIRED = 5; // Expired

Example

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

    @Override
    public void onSuccess(List<TempPassword> tempPasswords) {
        Log.i(TAG, "get lock temp passwords success: tempPasswords" + tempPasswords); 
    }
});

Create a temporary password

The validity period of a temporary password can be customized. This setting must be synced with the lock after the temporary password is created.

API description

public void createTempPassword(TempPassword tempPassword, final ITuyaResultCallback<Boolean> callback)

Parameters of TempPassword

The following table describes the parameters of this class.

Parameter Optional Description
name No The name of the password.
password No The 7-digit numeric temporary password.
effectiveDate No The timestamp in milliseconds when the temporary password takes effect.
invalidDate No The timestamp in milliseconds when the temporary password expires.
countryCode Yes The country or region code. For example, 86 means mainland China.
phone Yes The mobile phone number. After the password is created, a notification will be sent to this mobile phone number. phone and countryCode are optional. Before phone is set, the mobile phone’s SMS service must be enabled. Otherwise, this setting will not take effect

TempPassword is created by TempPassword.Builder. For more information, see the following example.

Example

TempPasswordBuilder tempPasswordBuilder = new TempPasswordBuilder()
        .name("Liam's password")
        .password("1231231")
        .effectiveTime(System.currentTimeMillis())
        .invalidTime(System.currentTimeMillis() + 24 * 60 * 60 * 1000);
tuyaLockDevice.createTempPassword(tempPasswordBuilder, new ITuyaResultCallback<Boolean>() {
    @Override
    public void onError(String code, String message) {
        Log.e(TAG, "create lock temp password: code = " + code + "  message = " + message);
    }

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

Delete a temporary password

Deletes a temporary password. This setting must be synced with the lock after the temporary password is deleted.

API description

public void deleteTempPassword(int passwordId, final ITuyaResultCallback<Boolean> callback)

Parameters

Parameter Description
passwordId The unique ID of the temporary password.

Example

tuyaLockDevice.deleteTempPassword(1111, new ITuyaResultCallback<Boolean>() {
    @Override
    public void onError(String code, String message) {
        Log.e(TAG, "delete lock temp password failed: code = " + code + "  message = " + message);
    }

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

Dynamic passwords

Wi-Fi Smart Lock

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

API description

public void getDynamicPassword(final ITuyaResultCallback<String> 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);
    }
});

Remote unlocking

Users can trigger a remote unlocking request on a lock. Then, the SDK can be used to implement remote locking.

Wi-Fi Smart Lock

Listen for remote unlocking requests

API description

public void setRemoteUnlockListener(RemoteUnlockListener remoteUnlockListener)

Parameters

RemoteUnlockListener provides the following Receive method:

void onReceive(String devId, int second);

Parameters

Field Type Description
devId String The device ID.
second int The minimum response time. Unit: seconds.

Request remote unlocking

API description

public void replyRemoteUnlock(boolean allow, final ITuyaResultCallback<Boolean> callback)

Parameters

Field Type Description
allow Boolean Specifies whether to allow unlocking the door.

Example

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_lock_device);

	....

    // Registers a listener for remote unlocking requests
    tuyaLockDevice.setRemoteUnlockListener(new RemoteUnlockListener() {
        @Override
        public void onReceive(String devId, int second) {
            if (second != 0 && !dialogShowing) {
                dialogShowing = true;
                Log.i(TAG, "remote unlock request onReceive");
                onCreateDialog();
            }
        }
    });
}

/**
 * Creates a dialog box that confirms whether to remotely unlock a door.
 */
public void onCreateDialog() {
    // Use the Builder class for convenient dialog construction
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setMessage("Whether to allow remote unlocking?")
            .setPositiveButton("YES", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    replyRemoteUnlockRequest(true);
                    Log.i(TAG, "remote unlock request access");
                    dialog.dismiss();
                    dialogShowing = false;
                }
            })
            .setNegativeButton("NO", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    replyRemoteUnlockRequest(false);
                    dialog.dismiss();
                    Log.i(TAG, "remote unlock request deny");
                    dialogShowing = false;
                }
            }).setCancelable(false);
    AlertDialog alertDialog = builder.create();
    alertDialog.setCanceledOnTouchOutside(false);
    alertDialog.show();
}

/**
 * Requests to remotely unlock a door.
 *
 * @param allow
 */
private void replyRemoteUnlockRequest(boolean allow) {
    tuyaLockDevice.replyRemoteUnlock(allow, new ITuyaResultCallback<Boolean>() {
        @Override
        public void onError(String code, String message) {
            Log.e(TAG, "reply remote unlock failed: code = " + code + "  message = " + message);
        }

        @Override
        public void onSuccess(Boolean result) {
            Log.i(TAG, "reply remote unlock success");
        }
    });
}

Lock usage records

Query lock usage records

Returns lock usage records based on the specified data point (DP) ID.

API description

public void getRecords(ArrayList<String> dpCodes, int offset, int limit, final ITuyaResultCallback<Record> callback)

Parameters

Parameter Description
dpCodes The list of data points (DPs) of the target device. For more information, see List of lock DPs.
offset The page number starting from which entries are returned.
limit The total number of returned entries in each call.

Return values

Fields of Record

Field Type Description
totalCount int The total number of returned entries in each call.
hasNext Boolean Indicates whether the next page is included.
datas List The data that is included in a record.

Fields of DataBean

Field Type Description
userId String The member ID.
avatarUrl String The avatar URL of the user.
userName String The nickname of the user.
createTime long The timestamp in milliseconds when the lock usage record was created.
devId String The device ID.
dpCodesMap HashMap<String, Object> The ID and current value of the DP.
unlockRelation UnlockRelation The mapping between an unlocking method and an unlocking password serial number. Ignore this parameter for non-unlocking records.
tags int The flag of the record. Valid values:
  • 0: other types of alarms
  • 1: duress alarm

You can query lock usage records to get the value of unlockRelation and assign the value to a created user.

For example, a password is created on a lock and used to unlock the door. This way, an unlocking record is generated and the unlocking method is returned. Users can query this unlocking record on the app and assign the associated password to a user as needed.

Example

// Sends the DP ID of the unlocking method to get the unlocking records.
ArrayList<String> dpCodes = new ArrayList<>();
dpCodes.add("alarm_lock");
dpCodes.add("hijack");
dpCodes.add("doorbell");
tuyaLockDevice.getRecords(dpCodes, 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);
    }
});

Get unlocking records

Unlocking records include the following events: unlock with a fingerprint, unlock with a normal password, unlock with a temporary password, unlock with a dynamic password, unlock with a card, unlock with biometric recognition, and unlock with a mechanical key.

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 entries are returned.
limit The total number of returned entries 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);
    }
});

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.

Add a duress alarm flag

Adds a duress alarm flag to an unlocking method. The associated password or fingerprint will be specified as a duress code.

API description

/**
 * Set the hijacking flag for the unlock method.
 *
 * @param unlockRelation UnlockRelation
 * @param callback callback
 */
void setHijackingConfig(UnlockRelation unlockRelation, final ITuyaResultCallback<Boolean> callback);

Parameters

Parameter Description
unlockRelation The mapping between an unlocking method and an unlocking password serial number.
callback The callback.

Remove a duress alarm flag

API description

/**
 * Remove the hijacking flag for the unlock method.
 *
 * @param unlockRelation UnlockRelation
 * @param callback callback
 */
void removeHijackingConfig(UnlockRelation unlockRelation, final ITuyaResultCallback<Boolean> callback);

Parameters

Parameter Description
unlockRelation The mapping between an unlocking method and an unlocking password serial number.
callback The callback.

Query duress alarm records

Returns the duress alarm records based on the specified unlocking DP data.

API description

public void getHijackRecords(int offset, int limit, final ITuyaResultCallback<RecordBean> callback)

Parameters

Parameter Description
offset The page number starting from which entries are returned.
limit The total number of returned entries in each call.

Example

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

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

List of lock DPs

DP name DP identifier (dpCode)
Unlock with a fingerprint unlock_fingerprint
Unlock with a normal password unlock_password
Unlock with a temporary password unlock_temporary
Unlock with a dynamic password unlock_dynamic
Unlock with a card unlock_card
Unlock with biometric recognition unlock_face
Unlock with a mechanical key unlock_key
Alerts alarm_lock
Countdown of remote unlocking unlock_request
Reply to a remote unlocking request reply_unlock_request
Battery capacity status battery_state
Remaining battery capacity residual_electricity
Double locking status reverse_lock
Child lock status child_lock
Remote unlocking with app unlock_app
Duress alarm hijack
Unlock from the inside of the door open_inside
Open and closed status of the door closed_opened
Doorbell call doorbell
SMS notification message
Double lock by lifting up anti_lock_outside
Unlock with irises unlock_eye
Unlock with palm prints unlock_hand
Unlock with finger veins unlock_finger_vein
Synchronize all fingerprint numbers update_all_finger
Synchronize all password numbers update_all_password
Synchronize all card numbers update_all_card
Synchronize all face numbers update_all_face
Synchronize all iris numbers update_all_eye
Synchronize all palm print numbers update_all_hand
Synchronize all finger vein numbers update_all_fin_vein
Report offline password unlocking unlock_offline_pd
Report the clearing of offline passwords unlock_offline_clear
Report the clearing of a single offline password unlock_offline_clear_single