Home Management

Last Updated on : 2024-01-29 02:27:21download

This topic describes the home management service, including home information, rooms, and members. After the user is logged in, check the current home, because devices must be added to a specific home. The following diagram shows the example implementation logic.

Home Management

Set the global variables as follows:

private var mFamilyUseCase: IFamilyUseCase = FamilyManagerCoreKit.getFamilyUseCase()
private var mMemberUseCase: IMemberUseCase = FamilyManagerCoreKit.getMemberUseCase()
private var mRoomUseCase: IFamilyRoomUseCase = FamilyManagerCoreKit.getRoomUseCase()

Home information update

After the user is logged in, retrieve the current default home, update the home information, and exchange data.

  1. Get the current default home.

    Typically, no home exists when a new user logs in to the app for the first time. In this case, getHomeDefaultDetail() will return null. A default home needs to be created. After a default home is created, call the home switching method and specify the current default home. This default home will be returned the next time the app starts.

    Example:

     fun getHomeDefaultDetail() {
      mFamilyUseCase.getCurrentDefaultFamilyDetail(object :
           IFamilyDataCallback<BizResponseData<FamilyBean>> {
           override fun onSuccess(result: BizResponseData<FamilyBean>?) {
               if (result?.data == null) {//There is no default home.
                   creatDefaultFamily()
               } else {
                   result?.data?.let {
                      //Register home messages.
                       registerHomeListener(it.homeId, it.familyName)
                       //Refresh home data and the list of devices and groups.
                       getHomeDeviceList()
                   }
               }
           }
           override fun onError(errorCode: String?, errorMessage: String?) {
               view.showErrorMsg(errorCode, errorMessage)
           }
        })
    
      //Create a default home with no room and location information, only default room names.
       private fun creatDefaultFamily() {
       mFamilyUseCase.createDefaultFamily( view.getHomeDefaultName(),
           object : IFamilyDataCallback<BizResponseData<FamilyBean>> {
               override fun onSuccess(result: BizResponseData<FamilyBean>?) {
                   result?.data?.let {
                       view.hideLoading()
                       //Call this method and use FamilyChangeListener #onFamilyShift callback to refresh data.
                       mFamilyUseCase.shiftCurrentFamily(it.homeId, null)
                   }
               }
    
               override fun onError(errorCode: String?, errorMessage: String?) {
                   view.showErrorMsg(errorCode, errorMessage)
               }
           })
          }
        }
    
  2. Register the listener for adding and removing devices in a home.

    After obtaining the current default home, you can register the listener for adding and removing devices in a home. Based on the received notification, update the home information, such as the city and weather of its location, as well as the devices and groups.

    Example:

    private fun registerHomeListener(homeId: Long, familyName: String?) {
    
           homeStatusListener = object : IThingHomeStatusListener {
               override fun onDeviceAdded(devId: String?) {
                   //Refresh using cached data.
                   refreshDevlist(mCurrentHomeId?.let { ThingHomeSdk.newHomeInstance(it).homeBean })
               }
    
               override fun onDeviceRemoved(devId: String?) {
                   //Refresh using cached data.
                   refreshDevlist(mCurrentHomeId?.let { ThingHomeSdk.newHomeInstance(it).homeBean })
               }
    
               override fun onGroupAdded(groupId: Long) {
                   //Refresh using cached data.
                   refreshDevlist(mCurrentHomeId?.let { ThingHomeSdk.newHomeInstance(it).homeBean })
               }
    
               override fun onGroupRemoved(groupId: Long) {
                   //Refresh using cached data.
                   refreshDevlist(mCurrentHomeId?.let { ThingHomeSdk.newHomeInstance(it).homeBean })
               }
    
               override fun onMeshAdded(meshId: String?) {
    
               }
    
           }
           FamilyManagerCoreKit.registerHomeStatusListener(homeId,
               homeStatusListener as IThingHomeStatusListener
           )
    
          }
    
  3. Update the home information.

    After the default home is specified, update the home name, location, weather information, and all device and group information in the home.

    Example:

    private fun getHomeDeviceList(homeId: Long) {
       //Get the HomeBean. HomeBean contains the list of all devices. getHomeDetail will trigger the cloud API to refresh the device list.
        ThingHomeSdk.newHomeInstance(homeId).getHomeDetail(object : IThingHomeResultCallback {
            override fun onSuccess(bean: HomeBean?) {
                refreshDevlist(bean)
            }
    
            override fun onError(errorCode: String?, errorMsg: String?) {
                view.showErrorMsg(errorCode, errorMsg)
            }
        })
      }
        private fun refreshDevlist(home: HomeBean?) {
         view.updateDevlist(home)
         home?.let {
            //Get weather.
            getHomeWeather(it.lon,it.lat)
            //Get city name.
            getHomeCity(it.lon,it.lat)
           }
        }
    
        private fun getHomeCity( lon:Double, lat:Double) {
        mFamilyUseCase.getCityByLatLon(lon,lat,object:IFamilyDataCallback<LocationCityBean>{
            override fun onSuccess(result: LocationCityBean?) {
                result?.let {
                    view.updateCityName(it.province+"  "+it.city)
                }
            }
    
            override fun onError(errorCode: String?, errorMessage: String?) {
    
            }
        } )
       }
    
       private fun getHomeWeather( lon:Double, lat:Double) {
        mFamilyUseCase.getHomeWeather(lon,lat,object:IFamilyDataCallback<WeatherBean>{
            override fun onSuccess(result: WeatherBean?) {
                result?.let {
                    view.updateWeather(it.condition+" ,"+result.temp)
                }
            }
    
            override fun onError(errorCode: String?, errorMessage: String?) {
    
            }
        } )
      }
    
  4. Listen for home-based messages.

    After updating the home information, you can add a listener for global home-related messages, including home creation, invitation, deletion, as well as changes in the sharing devices. Implement different update logic based on the message and data.

    Example:

      private val familyChangeListener = object : FamilyChangeListener {
      override fun onFamilyAdded(homeId: Long) {
    
      }
    
      override fun onFamilyInvite(homeId: Long, homeName: String?) {
          //Home invitation pop-up.
          view.showFamilyInviteDialog(homeId, homeName)
      }
    
      override fun onFamilyRemoved(homeId: Long, isBySelfRemoved: Boolean) {
          if (!isBySelfRemoved) { //If the home is not deleted by the owner, prompt that the home has been deleted.
              view.showFamilyRemovedDialog()
          }
          if (mCurrentHomeId == homeId) {
              getHomeDefaultDetail()
          }
      }
    
      override fun onFamilyInfoChanged(homeId: Long) {
           refreshFamilyBean(homeId)
      }
    
      override fun onFamilyShift(familyId: Long, familyName: String?) {
          registerHomeListener(familyId, familyName)
      }
    
      override fun onSharedDeviceList(sharedDeviceList: MutableList<DeviceBean>?) {
          //Refresh using cached data.
          refreshDevlist(mCurrentHomeId?.let { ThingHomeSdk.newHomeInstance(it).homeBean })
      }
    
      override fun onSharedGroupList(sharedGroupList: MutableList<GroupBean>?) {
          //Refresh using cached data.
          refreshDevlist(mCurrentHomeId?.let { ThingHomeSdk.newHomeInstance(it).homeBean })
      }
    
      override fun onServerConnectSuccess() {
    
      }
    }
    FamilyManagerCoreKit.registerFamilyChangeListener(familyChangeListener)
    

    The above describes the implementation of the logic after the user is logged in, which includes switching between homes, updating device caches, and receiving, accepting, and declining home invitations. See the Demo for the implementation.

Home management

Query the list of homes, modify home information, and delete a home.

  1. Query the list of homes.

    Query the list of homes to retrieve all homes associated with the account, including those created by the account and those shared with others. A home can be in one of three states:

    • HomeStatus.WAITING: Pending acceptance
    • HomeStatus.ACCEPT: Accepted
    • HomeStatus.REJECT: Declined
      When loading and displaying the list of homes, it is recommended to filter out declined homes.

    Example:

      fun getFamilyList() {
       mFamilyUseCase.getFamilyList(object :
           IFamilyDataCallback<BizResponseData<List<FamilyBean>>> {
           override fun onSuccess(result: BizResponseData<List<FamilyBean>>?) {
    
                   result?.data?.let {
                        it.filter { family->family.familyStatus != HomeStatus.REJECT }
                   }
               }
    
           }
    
           override fun onError(errorCode: String?, errorMessage: String?) {
    
           }
       })
     }
    
    
  2. Modify home information.

    The default home created only has one default name. This method can modify the home name and add information such as home address and room. The rooms field in CreateFamilyRequestBean cannot be empty.

    Example:

    fun updateFamily(
      name: String,
      lon: Double,
      lat: Double,
      address: String,
      settingFamilybean: FamilyBean?
    ) {
      val requestBean = settingFamilybean?.rooms?.let {
          CreateFamilyRequestBean(name, lon, lat, address, null)
      } ?: CreateFamilyRequestBean(name, lon, lat, address, arrayListOf("room1")).apply {
          isForComplete = true //Set isForComplete to complete the home information, which will return the home information.
      }
      settingFamilybean?.homeId?.let {
          mFamilyUseCase.updateFamily(
              it,
              requestBean,
              object : IFamilyDataCallback<BizResponseData<FamilyBean>> {
                  override fun onSuccess(result: BizResponseData<FamilyBean>?) {
                      result?.let {result->
                          if( result.data == null){
                              getFamilyDetail(it)
                          }
                      }
                  }
    
                  override fun onError(errorCode: String?, errorMessage: String?) {
                      ...
                  }
              })
      }
    }
    
  3. Delete a home.

    Only the home owner can delete a home. The home to be deleted must have no associated members. Deleting a home will remove all devices in that home. Once a home is deleted, it cannot be recovered.

    If a home has other members besides the owner, the owner can transfer their role to another member to become an admin and then leave that home.

    Example:

    fun dismissfamily(homeId: Long?) {
        homeId?.let {
            mFamilyUseCase.dismissFamily(it, object : IFamilyDataCallback<Boolean> {
                override fun onSuccess(result: Boolean?) {
                    viewModelScope.launch {
                        _delFamilybean.emit(true)
                    }
                }
    
                override fun onError(errorCode: String?, errorMessage: String?) {
    
                }
            })
        }
    }
    

    For methods such as ownership transfer and leaving a home, see the Demo.

Room management

Query all the rooms in a home, add, modify, and delete a room.

  1. Query the list of rooms in a home.

    This method returns the list of rooms in a home. You need to pass in the home ID to specify which home to query.

    Example:

     fun getRoomList(homeId: Long?) {
        if (homeId != null) {
            mRoomUseCase?.getRoomList(
                homeId,
                true,
                object : IFamilyDataCallback<BizResponseData<List<TRoomBean>>> {
                    override fun onSuccess(result: BizResponseData<List<TRoomBean>>?) {
                        result?.data?.let {
                            val list = arrayListOf<TRoomBean>()
                            list.addAll(it)
                           ...
                        }
                    }
    
                    override fun onError(errorCode: String?, errorMessage: String?) {
                        ...
                    }
                })
        }
      }
    
  2. Add a room to a home.

    This method can add a room to a home. You need to pass in the home ID to specify which home the room will be added to, and name the room.

    Example:

     fun addRoom(homeId: Long?,name: String?) {
        if (homeId != null) {
            mRoomUseCase?.addRoom(
                homeId,
                name,
                object : IFamilyDataCallback<BizResponseData<TRoomBean>> {
                    override fun onSuccess(result: BizResponseData<TRoomBean>?) {
                        result?.data?.let {
                            ...
                        }
                    }
    
                    override fun onError(errorCode: String?, errorMessage: String?) {
                        ...
                    }
                })
        }
        }
    
  3. Delete a room.

    This method can delete a room from a home. You need to pass in the home ID and specify the room ID.

    Example:

      fun deleteRoom(homeId: Long, roomId: Long) {
        if (roomId != null) {
            mRoomUseCase?.removeRoom(homeId, roomId, object : IFamilyDataCallback<Boolean> {
                override fun onSuccess(result: Boolean?) {
                   ...
                }
    
                override fun onError(errorCode: String?, errorMessage: String?) {
                   ...
                }
            })
        }
      }
    

    For methods such as sorting rooms, deleting, adding, or sorting devices in a room, see the Demo.

Member management

Get all members of a home, and add or remove a home member.

  1. Query the list of members of a home.

    Two methods are available:

    • getFamilyMemberList: Get the list of members who have accepted the invitation.
    • getInvitationMemberList: Get the list of members who have not responded to the invitation.

    If a user declines a home invitation, they will not be a member of that home.

    Example:

        fun getMemberList(homeId: Long) {
        mFamilyUseCase.getFamilyMemberList(homeId,
            object : IFamilyDataCallback<BizResponseData<List<MemberBean>>> {
                override fun onSuccess(result: BizResponseData<List<MemberBean>>?) {
                    val members: ArrayList<MemberBean> = arrayListOf()
                    result?.data?.let { members.addAll(it) }
                    //Retrieve the members who have not yet responded to the invitation.
                    mFamilyUseCase.getInvitationMemberList(homeId,
                        object : IFamilyDataCallback<BizResponseData<List<MemberBean>>> {
                            override fun onSuccess(result1: BizResponseData<List<MemberBean>>?) {
                                result1?.data?.let { members.addAll(it) }
                                 ...
                            }
    
                            override fun onError(errorCode: String?, errorMessage: String?) {
                                 ...
                            }
                        })
                }
    
                override fun onError(errorCode: String?, errorMessage: String?) {
                   ...
                }
            })
        }
    
  2. Add a member.

    The home owner can add a registered account as a member and assign the role of common member or admin to that account. The CountryCode of the added member should match that of the home owner. In MemberWrapperBean, the home ID (homeId), member role (role), member name (memberName), and member account (account) cannot be empty.

    Example:

     private fun showAddMemberDialog() {
        val inputLayout = TextInputLayout(requireContext()).apply {
            hint = getString(R.string.add_member_name_hint)
            setPadding(32, 0, 32, 0)
        }
        val editText = EditText(context)
        inputLayout.addView(editText)
        val inputLayout2 = TextInputLayout(requireContext()).apply {
            hint = getString(R.string.add_member_account_hint)
            setPadding(32, 0, 32, 0)
        }
        val editText2 = EditText(context)
        inputLayout2.addView(editText2)
        val radioGroup = RadioGroup(context).apply {
            orientation = LinearLayout.HORIZONTAL
            setPadding(32, 16, 32, 16)
        }
        val radioButton1 = MaterialRadioButton(requireContext()).apply {
            text = "admin"
        }
        val radioButton2 = MaterialRadioButton(requireContext()).apply {
            text = "common"
        }
    
        radioGroup.addView(radioButton1)
        radioGroup.addView(radioButton2)
        val linearLayout = LinearLayout(context).apply {
            orientation = LinearLayout.VERTICAL
            addView(inputLayout)
            addView(inputLayout2)
            addView(radioGroup)
        }
        MaterialAlertDialogBuilder(requireContext())
            .setTitle(getString(R.string.update_member))
            .setView(linearLayout)
            .setPositiveButton(getString(R.string.confirm)) { d, _ ->
                val name = editText.text.toString()
                val account = editText2.text.toString()
                var role = MemberRole.ROLE_MEMBER //Common member
                if (radioGroup.checkedRadioButtonId == radioButton1.id) {
                    role = MemberRole.ROLE_ADMIN //Admin
                }
                val bean = MemberBean()
                var code: String? = "86"
                if (!TextUtils.isEmpty(viewModel.mCurMemberBen?.countryCode)) {
                    code = viewModel.mCurMemberBen?.countryCode
                }
                bean.memberName = name
                bean.homeId = settingFamilybean?.homeId!!
                bean.countryCode = code
                bean.account = account
                bean.role = role
                addMember(bean)
                d.dismiss()
            }
            .setNegativeButton(getString(R.string.cancel)) { d, _ ->
                d.dismiss()
            }
            .show()
    
         }
    
       fun addMember(memberBean: MemberBean) {
        val bean = MemberWrapperBean.Builder()
            .setHomeId(memberBean.homeId)
            .setRole(memberBean.role)
            .setNickName(memberBean.memberName)
            .setAccount(memberBean.account)
            .setCountryCode(memberBean.countryCode)
            .setAdmin(memberBean.isAdmin)
            .build()
        mMemberUseCase.addMember(bean, object : IFamilyMemberDataCallback<MemberBean> {
            override fun onSuccess(result: MemberBean?) {
                 ...
            }
    
            override fun onError(errorCode: String?, errorMessage: String?) {
               ...
            }
        })
    }
    
  3. Delete a member.

    To delete a member, the role of the operator must be higher than that of the member to be deleted. This means that the home owner can delete both admins and common members, while an admin can only delete a common member. Common members are not allowed to delete other members. This method requires the home ID (homeId).

    Example:

        if(viewModel.mCurMemberBen == null | | memberBean== null){
            return
        }
        if(isAdmin && (mCurMemberBen!!.role <= memberBean!!.role)){
            Toast.makeText(
                requireContext(),
                getString(R.string.member_can_not_delete_tip),
                Toast.LENGTH_LONG
            )
            return
        }
        MaterialAlertDialogBuilder(requireContext())
            .setTitle(getString(R.string.confirm_delete_member))
            .setPositiveButton(getString(R.string.confirm)) { d, _ ->
                settingFamilybean?.homeId?.let {  deleteMember(it,memberBean) }
                d.dismiss()
            }
            .setNegativeButton(getString(R.string.cancel)) { d, _ ->
                d.dismiss()
            }
            .show()
    
        fun deleteMember(homeId: Long, memberBean: MemberBean) {
           mMemberUseCase.removeMember(
            homeId,
            memberBean.memberId,
            object : IFamilyMemberResultCallback {
                override fun onError(code: String?, error: String?) {
                   ...
                }
    
                override fun onSuccess() {
                   ...
                }
            })
      }
    

    There are other operations available for home members. For example, modify the home member information and their role, invite home members, and accept an invitation to join a home. For the complete code, see the Demo.

Destroy resources

If global variables for UseCase are set, they should be destroyed upon exiting the page.

...
private var mFamilyUseCase: IFamilyUseCase = FamilyManagerCoreKit.getFamilyUseCase()
private var mMemberUseCase: IMemberUseCase = FamilyManagerCoreKit.getMemberUseCase()
private var mRoomUseCase: IFamilyRoomUseCase = FamilyManagerCoreKit.getRoomUseCase()
...
   override fun onDestroy() {
        mFamilyUseCase.onDestroy()
        mMemberUseCase.onDestroy()
        mRoomUseCase.onDestroy()
    }