Android 相机设备指南

摄像头设备类型使用两个 trait 实现: PushAvStreamTransport,用于处理使用基于推送的协议的音频和视频串流传输;以及 WebRtcLiveView,用于控制直播和 TalkBack。

在使用任何功能或尝试更新属性之前,请务必检查设备是否支持属性和命令。如需了解详情,请参阅在 Control devices on Android 上控制设备。

Home API 设备类型 trait Kotlin 示例应用 使用场景

相机

GoogleCameraDevice

home.matter.6006.types.0158

一种拍摄静态图片或视频的设备。摄像头可能具有可访问的直播、双向对讲或检测事件等功能。

必需的 trait
     google PushAvStreamTransport
     google WebRtcLiveView

摄像头

获取有关设备的基本信息

The BasicInformation trait 包含设备的相关信息,例如供应商名称、供应商 ID、产品 ID、 商品名称(包括型号信息)、软件版本、 和序列号:

// Get device basic information. All general information traits are on the RootNodeDevice type.
    device.type(RootNodeDevice).first().standardTraits.basicInformation?.let { basicInformation ->
        println("vendorName ${basicInformation.vendorName}")
        println("vendorId ${basicInformation.vendorId}")
        println("productId ${basicInformation.productId}")
        println("productName ${basicInformation.productName}")
        println("softwareVersion ${basicInformation.softwareVersion}")
        println("serialNumber ${basicInformation.serialNumber}")
    }

获取设备最近一次与云端联系的时间

如需查找设备最近一次与云端联系的时间,请使用 lastContactTimestamp属性( ExtendedGeneralDiagnostics trait):

fun getLastContactTimeStamp(trait: ExtendedGeneralDiagnostics): java.time.Instant {
  val timestamp = trait.lastContactTimestamp
  return Instant.ofEpochSecond(timestamp.toLong())
}

检查设备的连接

实际上,设备的连接是在设备类型级别进行检查的,因为某些设备支持多种设备类型。返回的状态是该设备上所有 trait 的连接状态的组合。

val lightConnectivity = dimmableLightDevice.metadata.sourceConnectivity.connectivityState

如果设备类型混用且没有互联网连接,则可能会观察到 PARTIALLY_ONLINE 状态。Matter 标准 trait 可能仍处于在线状态,但基于云端的 trait 将处于离线状态。

开始直播

如需开始直播,请将会话描述协议 (SDP) 字符串 发送到 WebRtcLiveView trait 的 startLiveView() 方法,该方法会返回一个 WebRtcLiveViewTrait.StartLiveViewCommand.Response ,其中包含三个值:

  • 会话的 SDP。
  • 会话时长(以秒为单位)。
  • 会话 ID,可用于延长或终止会话。
suspend fun getWebRtcLiveViewTrait(cameraDevice: HomeDevice) {
 return cameraDevice.type(GoogleCameraDevice).trait(WebRtcLiveView).first {
    it?.metadata?.sourceConnectivity?.connectivityState == ConnectivityState.ONLINE
  }

}

// Start the live view
suspend fun startCameraStream(trait: WebRtcLiveView, offerSdp: String) {
  val response = trait.startLiveView(offerSdp)
  // Response contains three fields (see below)
  return response
}
  ...

// This is used to manage the WebRTC connection
val peerConnection: RTCPeerConnection = ...

   ...

val startResponse = startCameraStream(sdp)
val answerSdp = startResponse?.answerSdp
val sessionDuration = startResponse?.liveSessionDurationSeconds
val mediaSessionId = startResponse?.mediaSessionId

peerConnection.setRemoteDescription(SessionDescription.Type.ANSWER,
                                    answerSdp)

延长直播

直播具有预设时长,超过该时长后直播将过期。如需延长有效直播的时长,请使用 WebRtcLiveView.extendLiveView() 方法发出延长请求:

// Assuming camera stream has just been started
suspend fun scheduleExtension(trait: WebRtcLiveView, mediaSessionId: String, liveSessionDurationSeconds: UShort ) {
  delay(liveSessionDurationSeconds - BUFFER_SECONDS * 1000)
  val response = trait.extendLiveView(mediaSessionId)
  // returns how long the session will be live for
  return response.liveSessionDurationSeconds
}

开始和停止对讲

如需开始对讲,请调用 WebRtcLiveView trait 的 startTalkback() 方法。如需停止,请使用 stopTalkback()

// Make sure camera stream is on
suspend fun setTalkback(isOn: Boolean, trait: WebRtcLiveView, mediaSessionId: String) {
  if(isOn) {
    trait.startTalkback(mediaSessionId)
  } else {
    trait.stopTalkback(mediaSessionId)
  }
}

启用和停用录制功能

如需启用摄像头的录制功能,请将 TransportStatusEnum.Active 传递给 PushAvStreamTransport trait 的 setTransportStatus() 方法。如需停用录制功能,请将其传递给 TransportStatusEnum.Inactive。 在以下示例中,我们将这些调用封装在一个使用 Boolean 切换录制功能的调用中:

// Start or stop recording for all connections.
suspend fun setCameraRecording(trait: PushAvStreamTransport, isOn: Boolean) {
  if(isOn) {
    trait.setTransportStatus(TransportStatusEnum.Active)
  } else {
    trait.setTransportStatus(TransportStatusEnum.Inactive)
  }
}

启用或停用摄像头的录制功能与开启或关闭摄像头视频相同。当摄像头的视频开启时,它会进行录制(用于事件和相关剪辑)。

当录制功能停用(摄像头视频关闭)时:

检查是否启用了录制功能

如需确定是否启用了摄像头的录制功能,请检查是否有任何连接处于活动状态。以下示例定义了两个函数来执行此操作:

// Get the on/off state
suspend fun onOffState(pushAvStreamTransport: PushAvStreamTransport) {
  return pushAvStreamTransport
    .currentConnections?.any { it.transportStatus == TransportStatusEnum.Active } ?: false
}

// Check if the camera's recording capability is enabled
fun PushAvStreamTransport.recordModeActive(): Boolean {
  return currentConnections?.any { it.transportStatus == TransportStatusEnum.Active } ?: false
}

另一种检查方法是使用带有谓词的 findTransport() 函数:

// Fetch the current connections
suspend fun queryRecordModeState(trait: PushAvStreamTransport) {
  return trait.findTransport().let {
      it.transportConfigurations.any { it.transportStatus == TransportStatusEnum.Active
    }
}

电池设置

您可以通过 Home API 控制各种电池设置。

设置电池用量偏好设置

通过设置能量平衡,您可以配置设备的电池续航时间和性能之间的权衡。您可以创建不同的电池配置文件,例如“延长”“平衡”和“性能”,并在它们之间切换。

此功能通过更新 currentEnergyBalance属性 的 EnergyPreference trait 来实现。该属性接受一个整数索引,该索引对应于设备 energyBalances 列表中定义的特定配置文件(例如,0 表示 EXTENDED1 表示 BALANCED2 表示 PERFORMANCE)。

currentEnergyBalancenull 值表示设备正在使用自定义配置文件。这是一个只读状态。

以下示例展示了 currentEnergyBalance 属性将使用的结构,然后是使用该属性的实际代码段。

// Example energyBalances list
energy_balances: [
  {
    step: 0,
    label: "EXTENDED"
  },
  {
    step: 50,
    label: "BALANCED"
  },
  {
    step: 100,
    label: "PERFORMANCE"
  }
]
// The index parameter must be within the UByte range (0-255).
suspend fun setEnergyBalance(trait: EnergyPreference, index: Int) {
  trait.update { setCurrentEnergyBalance(index.toUByte()) }
}

// Setting the battery usage to more recording ie performance
setEnergyBalance(energyPreference, 2)

开启自动省电模式

如需配置此功能,请更新 currentLowPowerModeSensitivity属性 的 EnergyPreference trait。此属性使用索引来选择灵敏度级别,其中 0 通常表示 Disabled1 表示 EnabledAutomatic

suspend fun setAutomaticBatterySaver(enable: Boolean, trait: EnergyPreference) {
  // 0 is Disabled, 1 is Enabled
  val value = if (enable) 1.toUByte() else 0.toUByte()
  trait.update { setCurrentLowPowerModeSensitivity(value) }
}

获取电池充电状态

如需获取设备的当前充电状态(充电、已充满电或未 充电),请使用 batChargeState 属性的 PowerSource trait。

// Get the battery charging state
val batteryChargeState = powerSource.batChargeState

when (batteryChargeState) {
    PowerSourceTrait.BatChargeStateEnum.IsCharging -> "Charging"
    PowerSourceTrait.BatChargeStateEnum.IsAtFullCharge -> "Full"
    PowerSourceTrait.BatChargeStateEnum.IsNotCharging -> "Not Charging"
    else -> "Unknown"
}

获取电池电量

如需获取当前电池电量,请使用 batChargeLevel 属性的 PowerSource trait。电量为 OKWarning(低)或 Critical

// Get the battery charge level
val batteryLevel = powerSourceTrait.batChargeLevel

when (batteryLevel) {
    PowerSourceTrait.BatChargeLevelEnum.OK -> "OK"
    PowerSourceTrait.BatChargeLevelEnum.Warning -> "Warning"
    PowerSourceTrait.BatChargeLevelEnum.Critical -> "Critical"
    else -> "Unknown"
}

获取电源

如需确定设备正在使用的电源, 请使用 BatPresentwiredPresent 属性,这些属性属于 PowerSource trait。

  val trait: PowerSource
  val isWired = trait.wiredPresent
  val hasBattery = trait.batPresent

音频设置

您可以通过 Home API 控制各种音频设置。

开启或关闭麦克风

如需开启或关闭设备的麦克风,请使用内置的 setMicrophoneMuted Kotlin 函数更新 CameraAvStreamManagement trait 的 microphoneMuted 属性:

// Turn the device's microphone on or off
suspend fun turnOffMicrophone(disableMicrophone: Boolean, trait: CameraAvStreamManagement) {
  trait.update { setMicrophoneMuted(disableMicrophone) }
}

开启或关闭录音功能

如需开启或关闭设备的录音功能,请使用内置的 setRecordingMicrophoneMuted Kotlin 函数更新 CameraAvStreamManagement trait 的 recordingMicrophoneMuted 属性:

// Turn audio recording on or off for the device
suspend fun turnOffAudioRecording(disableAudioRecording: Boolean, trait: CameraAvStreamManagement) {
  trait.update { setRecordingMicrophoneMuted(disableAudioRecording) }
}

调节扬声器音量

如需调节设备的扬声器音量,请使用内置的 setSpeakerVolumeLevel Kotlin 函数更新 CameraAvStreamManagement trait 的 speakerVolumeLevel 属性:

// Adjust the camera speaker volume
suspend fun adjustSpeakerVolume(volume: Int, trait: CameraAvStreamManagement) {
  trait.update { setSpeakerVolumeLevel(volume.toUbyte()) }
}

活动区域设置

ZoneManagement trait 提供了一个界面,用于管理摄像头和门铃设备上的自定义感兴趣区域(活动区域)。这些区域用于将事件检测(例如人员或车辆移动)过滤到设备视野范围内的特定区域。

活动区域由用户在合作伙伴应用中配置,允许用户在摄像头视野范围内的特定区域绘制区域。然后,这些用户定义的区域会转换为此 trait 使用的结构。 如需详细了解活动区域的工作原理,请参阅 设置和使用活动区域

活动区域通常使用二维笛卡尔坐标定义。 该 trait 为顶点提供 TwoDCartesianVertexStruct,为区域定义(名称、顶点、颜色和用途)提供 TwoDCartesianZoneStruct

检查活动区域

如需显示活动区域,请检查 zones trait 的 ZoneManagement属性。

// 1. Obtain the trait flow from the device
private val zoneManagementFlow: Flow =
  device.type(CAMERA_TYPE).flatMapLatest { it.trait(ZoneManagement) }

// 2. Map the flow to the list of zone structures
val activityZones: Flow<List<ZoneManagementTrait.ZoneInformationStruct>> =
  zoneManagementFlow.map { trait ->
    trait.zones ?: emptyList()
  }

添加活动区域

如需创建新区域,请使用 createTwoDCartesianZone命令。此命令采用 TwoDCartesianZoneStruct, 用于定义区域的名称、顶点、颜色和用途。

以下示例展示了如何创建一个名为“Front Porch”的区域,该区域有四个顶点,颜色为鲑鱼色 (#F439A0),用于移动侦测。

import com.google.home.google.ZoneManagement
import com.google.home.google.ZoneManagementTrait
import com.google.home.matter.serialization.OptionalValue

/**
 * Creates a custom activity zone named "Front Porch" with a salmon color
 * configured for motion detection.
 */
suspend fun createFrontPorchZone(zoneManagement: ZoneManagement) {
  // 1. Define the vertices for the zone (2D Cartesian coordinates)
  // Values are typically scaled to a maximum defined by the device's twoDCartesianMax attribute.
  val vertices =
    listOf(
      ZoneManagementTrait.TwoDCartesianVertexStruct(x = 260u, y = 422u),
      ZoneManagementTrait.TwoDCartesianVertexStruct(x = 1049u, y = 0u),
      ZoneManagementTrait.TwoDCartesianVertexStruct(x = 2048u, y = 0u),
      ZoneManagementTrait.TwoDCartesianVertexStruct(x = 2048u, y = 950u),
      ZoneManagementTrait.TwoDCartesianVertexStruct(x = 1630u, y = 1349u),
      ZoneManagementTrait.TwoDCartesianVertexStruct(x = 880u, y = 2048u),
      ZoneManagementTrait.TwoDCartesianVertexStruct(x = 0u, y = 2048u),
      ZoneManagementTrait.TwoDCartesianVertexStruct(x = 638u, y = 1090u)
    )

  // 2. Define the zone structure
  val newZone =
    ZoneManagementTrait.TwoDCartesianZoneStruct(
      name = "Front Porch",
      vertices = vertices,
      // Usage defines what the zone filters (for example, Motion, Person, Vehicle)
      use = listOf(ZoneManagementTrait.ZoneUseEnum.Motion),
      // Color is typically a hex string (for example, Salmon/Pink)
      color = OptionalValue.present("#F439A0")
    )

  try {
    // 3. Execute the command to add the zone to the device
    zoneManagement.createTwoDCartesianZone(newZone)
    println("Successfully created activity zone.")
  } catch (e: Exception) {
    // Handle potential HomeException or Timeout
    println("Failed to create activity zone: ${e.message}")
  }
}

更新活动区域

如需更新现有区域,请使用 updateTwoDCartesianZone 命令。此命令需要 zoneId 和更新后的 TwoDCartesianZoneStruct

private suspend fun ZoneManagement.updateZone(
  zoneId: UShort,
  zone: ZoneManagementTrait.TwoDCartesianZoneStruct
) {
  // Execute the command to update the zone
  this.updateTwoDCartesianZone(zoneId = zoneId, zone = zone)
}

删除活动区域

如需移除区域,请使用 removeZone 命令和特定 zoneId

private suspend fun ZoneManagement.deleteZone(zoneId: UShort) {
  // Execute the command to remove the zone
  this.removeZone(zoneId = zoneId)
}

声音事件触发器

AvStreamAnalysis trait 提供了一个界面,用于管理摄像头和门铃设备上的事件检测触发器。虽然基于视觉的触发器(例如人员或车辆)可以是特定于区域的,但与声音相关的触发器通常是设备级配置。

以下触发器类型可用于通过 EventTriggerTypeEnum进行声音检测:

模式 枚举值 说明
声音 Sound 一般声音检测。
人说话声 PersonTalking 检测语音。
狗吠声 DogBark 检测犬类发声。
玻璃破碎声 GlassBreak 检测玻璃破碎的声音。
烟雾警报器 SmokeAlarm 检测烟雾警报声,通常通过 T3 声音模式(三声短促的蜂鸣声,然后暂停)识别。
一氧化碳警报声 CoAlarm 检测一氧化碳 (CO) 警报声,通常通过 T4 声音模式(四声短促的蜂鸣声,然后暂停)识别。

检查声音检测状态

如需向用户显示声音检测的当前状态,您必须检查设备支持哪些功能以及设备硬件启用了哪些功能。要检查的两个属性是:

在使用 Kotlin Flow 进行 Android 开发时,您通常会从 HomeDevice 中观察 AvStreamAnalysis trait。

// Example structure to store the
data class EventTriggerAttribute(val type: EventTriggerTypeEnum, val enabled: Boolean)

// 1. Obtain the trait flow from the device
private val avStreamAnalysisFlow: Flow<AvStreamAnalysis> =
  device.traitFromType(AvStreamAnalysis, CAMERA_TYPES.first { device.has(it) })

// 2. Map the flow to a list of sound event attributes
val soundEventTriggersState: Flow<List<EventTriggerAttribute>> =
  avStreamAnalysisFlow.map { trait ->
    // Get raw lists from the trait attributes
    val supported = trait.supportedEventTriggers ?: emptyList()
    val enabled = trait.enabledEventTriggers ?: emptyList()

    // Define sound-specific triggers to filter for
    val soundTypes = setOf(
      EventTriggerTypeEnum.Sound,
      EventTriggerTypeEnum.PersonTalking,
      EventTriggerTypeEnum.DogBark,
      EventTriggerTypeEnum.GlassBreak,
      EventTriggerTypeEnum.SmokeAlarm,
      EventTriggerTypeEnum.CoAlarm,
    )

    // Filter and associate status
    supported
      .filter { soundTypes.contains(it) }
      .map { type ->
        EventTriggerAttribute(
          type = type,
          enabled = enabled.contains(type)
        )
      }
  }

更新已启用触发器的集合

如需更新已启用触发器的集合,请使用 SetOrUpdateEventDetectionTriggers 命令,该命令采用 EventTriggerEnablement 结构的列表。

private suspend fun AvStreamAnalysis.updateEventTriggers(
  eventTriggers: List<EventTriggerAttribute>
) {
  val toUpdate = eventTriggers.map {
    EventTriggerEnablement(
      eventTriggerType = it.type,
      enablementStatus = if (it.enabled) {
        EnablementStatusEnum.Enabled
      } else {
        EnablementStatusEnum.Disabled
      },
    )
  }

  // Execute the command on the device
  setOrUpdateEventDetectionTriggers(toUpdate)
}

录制模式

RecordingMode trait 提供了一个界面,用于管理摄像头和门铃设备上的视频和图片录制行为。它允许用户在连续录像、事件录像或完全停用录制(仅限实时画面)之间进行选择。

RecordingModeEnum 定义了可用的录制策略:

模式 枚举值 说明
已停用 Disabled 录制功能已完全停用。主要由旧版设备使用。
CVR (连续录像) Cvr 全天候录制视频。需要订阅 (例如 Google Google Home Premium)。
EBR (基于事件的录制) Ebr 录制由事件(人员、移动)触发。 视频时长取决于事件时长和订阅。
ETR (事件触发的录制) Etr 由事件触发的短预览录制(例如 10 秒) 。
实时画面 LiveView 录制功能已停用,但用户仍可访问直播。
静态图片 Images 发生事件时,系统会录制快照而不是视频。

检查录制模式

如需显示当前的录制配置,请检查 RecordingMode trait 的属性:

// 1. Obtain the trait flow from the device
private val recordingModeTraitFlow: Flow =
    device.traitFromType(RecordingMode, CAMERA_TYPES.first { device.has(it) })

// 2. Map the flow to recording mode options
data class RecordingModeOptions(
    val recordingMode: RecordingModeTrait.RecordingModeEnum,
    val index: Int,
    val available: Boolean,
    val readableString: String,
)

private val recordingModeOptions: Flow<List> =
    recordingModeTraitFlow.map { trait ->
        val supported = trait.supportedRecordingModes?.map { it.recordingMode } ?: emptyList()
        val available = trait.availableRecordingModes?.map { it.toInt() } ?: emptyList()

        supported.withIndex().map { (index, mode) ->
            RecordingModeOptions(
                recordingMode = mode,
                index = index,
                available = available.contains(index),
                readableString = mode.toReadableString(),
            )
        }
    }

更改录制模式

在更新之前,请确保 supportedRecordingModes 属性中选择的索引存在于 availableRecordingModes 属性中。

如需更新所选模式,请使用 setSelectedRecordingMode 函数,并传递所选模式的索引:

private suspend fun RecordingMode.updateRecordingMode(index: Int) {
    // Execute the command to update the selected mode
    this.setSelectedRecordingMode(index.toUByte())
}

其他设置

您可以通过 Home API 控制各种其他设置。

更改图片方向

摄像头图片(视频)的方向可以旋转。视频只能旋转 180 度。

如需更改相机的图片方向,请使用内置的 setImageRotation Kotlin 函数更新 CameraAvStreamManagement trait 的 imageRotation 属性:

// Change the camera's image orientation
val isRotated = false

cameraAvStreamManagement.update { setImageRotation(if (isRotated) 180.toUShort() else 0.toUShort()) }

开启或关闭夜视功能

如需开启或关闭摄像头的夜视效果,请使用 TriStateAutoEnum 更新 nightVision trait 的 CameraAvStreamManagement 属性,方法是使用内置的 setNightVision Kotlin 函数:

// Turn night vision on
cameraAvStreamManagement.update {
  setNightVision(CameraAvStreamManagementTrait.TriStateAutoEnum.On)
}

// Turn night vision off
CameraAvStreamManagement.update {
  setNightVision(CameraAvStreamManagementTrait.TriStateAutoEnum.Off)
}

更改状态 LED 的亮度

如需更改状态 LED 的亮度,请使用 ThreeLevelAutoEnum 更新 statusLightBrightness 属性,方法是使用内置的 setStatusLightBrightness Kotlin 函数:CameraAvStreamManagement

// Set the LED brightness to high
cameraAvStreamManagement.update {
  setStatusLightBrightness(CameraAvStreamManagementTrait.ThreeLevelAutoEnum.High)
}

// Set the LED brightness to low
cameraAvStreamManagement.update {
  setStatusLightBrightness(CameraAvStreamManagementTrait.ThreeLevelAutoEnum.Low)
}

更改摄像头视口

摄像头视口与缩放和增强 Nest 摄像头视频画面支持文章中所述的 “缩放和裁剪”功能相同。

视口在 ViewportStruct 中定义,其中包含四个值,这些值用作视口的坐标。坐标定义如下:

(x1,y1) -- (x2,y1)
   |          |
(x1,y2) -- (x2,y2)

确定 ViewportStruct 的值取决于应用的界面和摄像头实现。在非常基本的层面上,如需设置摄像头 视频的视口,请使用 内置的 setViewport Kotlin 函数,通过 ViewportStruct 更新 CameraAvStreamManagement trait 的 viewport 属性:

cameraAvStreamManagement
  .update { setViewport(
    CameraAvStreamManagementTrait.ViewportStruct(
      x1 = horizontalRange.rangeStart.roundToInt().toUShort(),
      x2 = horizontalRange.rangeEnd.roundToInt().toUShort(),
      y1 = verticalRange.rangeStart.roundToInt().toUShort(),
      y2 = verticalRange.rangeEnd.roundToInt().toUShort(),
    )
) }

调整设备唤醒灵敏度

设备的唤醒灵敏度用于通过以下方式节省电池电量:降低设备可以感应活动的范围,并增加检测到活动后唤醒的时间。

在 Home API 中,可以使用设备 transportOptions 中的 triggerOptionsmotionSensitivity 属性进行设置。这些选项在每个设备的 PushAvStreamTransport trait 中定义。

唤醒灵敏度只能设置为以下值:

  • 1 = 低
  • 5 = 中
  • 10 = 高

更新过程是使用 命令查找有效 录制流的传输配置,然后使用 modifyPushTransport 命令使用新的灵敏度值修改配置:findTransport

// Create a struct with the new wake-up sensitivity
val toUpdate =  TransportOptionsStruct(
  triggerOptions =
    TransportTriggerOptionsStruct(
      motionSensitivity =
        OptionalValue.present(wakeUpSensitivity.toUByte())
    )
  )

// Get the configurations for active connections
val connections  = pushAvStreamTransport.findTransport().transportConfigurations
  // Update all recording streams with the new transport options.
  for (connection in connections) {
    if (connection.transportOptions.getOrNull()?.streamUsage == StreamUsageEnum.Recording) {
      trait.modifyPushTransport(
        connectionId = connection.connectionId,
        transportOptions = toUpdate,
      )
    }
  }

调整事件录制时长上限

事件录制时长上限是指摄像头为事件录制剪辑的时长。通过 Home API,您可以为每个设备配置此设置,使其与通过 GHA 配置的时长相同 ,以秒为间隔:

  • 10 秒
  • 15 秒
  • 30 秒
  • 60 秒(1 分钟)
  • 120 秒(2 分钟)
  • 180 秒(3 分钟)

在 Home API 中,可以使用设备 transportOptions 中的 triggerOptionsmotionTimeControl 属性进行设置。这些选项在每个设备的 PushAvStreamTransport trait 中定义。

更新过程是使用 命令查找有效 录制流的传输配置,然后使用 modifyPushTransport 命令使用新的事件时长值修改配置:findTransport

// Create a struct with the new max event length
// where maxDuration is the length in seconds
val toUpdate =  TransportOptionsStruct(
  triggerOptions =
    TransportTriggerOptionsStruct(
      motionTimeControl =
        OptionalValue.present(
          TransportMotionTriggerTimeControlStruct(maxDuration = it.toUInt())
        )
    )
  )

// Get the configurations for active connections
val connections  = pushAvStreamTransport.findTransport().transportConfigurations
  // Update all recording streams with the new transport options.
  for (connection in connections) {
    if (connection.transportOptions.getOrNull()?.streamUsage == StreamUsageEnum.Recording) {
      trait.modifyPushTransport(
        connectionId = connection.connectionId,
        transportOptions = toUpdate,
      )
    }
  }

启用或停用分析功能

每台设备都可以单独选择将详细的分析数据发送到 Google Home 云端(请参阅 Home API 的 Cloud Monitoring )。

如需为设备启用分析功能,请将 analyticsEnabledExtendedGeneralDiagnosticsTrait 设置为 true。当您设置 analyticsEnabled 时,另一个属性 logUploadEnabled 会自动设置为 true,这允许将分析日志文件上传到 Google Home 云端。

// Enable analytics
extendedGeneralDiagnostics.update {
  setAnalyticsEnabled(true)
}

// Disable analytics
extendedGeneralDiagnostics.update {
  setAnalyticsEnabled(false)
}