Android 向けカメラ デバイス ガイド

カメラ デバイスタイプは、2 つのトレイトを使用して実装されます。 PushAvStreamTransportはプッシュベースのプロトコルを使用して音声と動画のストリーム転送を処理し、 WebRtcLiveViewはライブ ストリームとトークバックを制御する機能を提供します。

機能を使用したり、属性を更新したりする前に、デバイスで属性とコマンドがサポートされていることを必ず確認してください。詳しくは、でデバイスを制御する Androidをご覧ください。

Google Home の API デバイスタイプ トレイト Kotlin サンプルアプリ ユースケース

カメラ

GoogleCameraDevice

home.matter.6006.types.0158

静止画像や動画を撮影するデバイス。カメラには、アクセス可能なライブ ストリーム、双方向トークバック、アクティビティ検出などの機能が搭載されている場合があります。

必須のトレイト
     google PushAvStreamTransport
     google WebRtcLiveView

カメラ

デバイスに関する基本情報を取得する

BasicInformation トレイトには、ベンダー名、ベンダー 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 使用します。

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

デバイスの接続を確認する

デバイスの接続は、デバイスタイプ レベルで確認されます。一部のデバイスは複数のデバイスタイプをサポートしているためです。返される状態は、そのデバイスのすべてのトレイトの接続状態の組み合わせです。

val lightConnectivity = dimmableLightDevice.metadata.sourceConnectivity.connectivityState

インターネットに接続されていない場合、デバイスタイプが混在していると PARTIALLY_ONLINE 状態になることがあります。Matter 標準トレイトはローカル ルーティングによりオンラインのままですが、クラウドベースのトレイトはオフラインになります。

ライブ配信を開始する

ライブ配信を開始するには、セッション記述プロトコル(SDP)文字列を WebRtcLiveView トレイトの startLiveView() メソッドに送信します。このメソッドは、次の 3 つの値を含む 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 トレイトの 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)
  }
}

録画機能を有効または無効にする

カメラの録画機能を有効にするには、 PushAvStreamTransportトレイトの setTransportStatus()メソッドに TransportStatusEnum.Activeを渡します。録画機能を無効にするには、 TransportStatusEnum.Inactive を渡します。 次の例では、これらの呼び出しを 1 つの呼び出しでラップし、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)
  }
}

カメラの録画機能を有効または無効にすることは、カメラの動画をオンまたはオフにすることと同じです。カメラの動画がオンになっている場合、録画が行われます(アクティビティと関連するクリップの場合)。

録画機能が無効になっている場合(カメラの動画がオフの場合):

録画機能が有効になっているかどうかを確認する

カメラの録画機能が有効になっているかどうかを確認するには、接続がアクティブかどうかを確認します。次の例では、これを行うための 2 つの関数を定義しています。

// 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
    }
}

バッテリーの設定

さまざまなバッテリー設定は、Google Home の API で制御できます。

バッテリー使用量の設定

エネルギー バランスを設定すると、デバイスのバッテリー寿命とパフォーマンスのトレードオフを構成できます。「拡張」、「バランス」、「パフォーマンス」など、さまざまなバッテリー プロファイルを作成して切り替えることができます。

この機能は、 currentEnergyBalance 属性 を更新することで、EnergyPreference トレイトに実装されます。この属性は、デバイスの energyBalances リストで定義された特定のプロファイルに対応する整数インデックスを受け取ります(例: EXTENDED の場合は 0BALANCED の場合は 1PERFORMANCE の場合は 2)。

currentEnergyBalance の値が null の場合、デバイスはカスタム プロファイルを使用しています。これは読み取り専用の状態です。

以下に、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 トレイトを更新します。この属性はインデックスを使用して感度レベルを選択します。通常、0Disabled を表し、1Enabled または Automatic を表します。

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

// 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 トレイトを使用します。レベルは 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 トレイトで使用します。

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

音声設定

さまざまな音声設定は、Google Home の API で制御できます。

マイクのオンとオフを切り替える

デバイスのマイクのオンとオフを切り替えるには、組み込みの setMicrophoneMuted Kotlin 関数を使用して、CameraAvStreamManagement トレイトの microphoneMuted 属性を更新します。

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

音声録音のオンとオフを切り替える

デバイスの音声録音のオンとオフを切り替えるには、組み込みの setRecordingMicrophoneMuted Kotlin 関数を使用して、CameraAvStreamManagement トレイトの recordingMicrophoneMuted 属性を更新します。

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

スピーカーの音量を調整する

デバイスのスピーカーの音量を調整するには、組み込みの setSpeakerVolumeLevel Kotlin 関数を使用して、CameraAvStreamManagement トレイトの speakerVolumeLevel 属性を更新します。

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

アクティビティ エリアの設定

ZoneManagement トレイトは、カメラとドアホン デバイスのカスタム関心領域(アクティビティ エリア)を管理するためのインターフェースを提供します。これらのゾーンは、デバイスの画角内の特定エリアに対するイベント検出(人物や車両の動きなど)をフィルタするために使用されます。

アクティビティ エリアは、パートナー アプリケーション内でお客様が構成します。これにより、カメラの画角内の特定のエリアにエリアを描画できます。お客様が定義したエリアは、このトレイトで使用される構造に変換されます。 アクティビティ エリアの仕組みについて詳しくは、 アクティビティ エリアを設定して使用するをご覧ください。

アクティビティ エリアは通常、2D デカルト座標を使用して定義されます。 このトレイトは、頂点に TwoDCartesianVertexStruct、ゾーン定義(名前、頂点、色、使用状況)に TwoDCartesianZoneStruct を提供します。

アクティビティ エリアを確認する

アクティビティ エリアを表示するには、 zones トレイトの 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、 エリアの名前、頂点、色、使用状況を定義するを受け取ります。

次の例は、4 つの頂点を持つ「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)
}

アクティビティ エリアを削除する

ゾーンを削除するには、特定の zoneId を指定して removeZone コマンドを使用します。

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

サウンド アクティビティ トリガー

AvStreamAnalysis トレイトは、カメラとドアホン デバイスのアクティビティ検出トリガーを管理するためのインターフェースを提供します。ビジョンベースのトリガー(人物や車両など)はエリア固有にできますが、サウンド関連のトリガーは通常、デバイスレベルの構成です。

` EventTriggerTypeEnum` を使用したサウンド検知には、次のトリガータイプを使用できます。

モード 列挙値 説明
サウンド Sound 一般的なサウンド検知。
話し声 PersonTalking 音声を検出します。
犬の鳴き声 DogBark 犬の鳴き声を検出します。
ガラスの割れる音 GlassBreak ガラスの割れる音を検出します。
煙警報 SmokeAlarm 煙警報を検出します。多くの場合、T3 可聴 パターン(短いビープ音 3 回の後に一時停止)で認識されます。
一酸化炭素警報 CoAlarm 一酸化炭素(CO)警報を検出します。通常、T4 可聴パターン(短いビープ音 4 回の後に一時停止)で認識されます。

サウンド検知のステータスを確認する

サウンド検知の現在の状態をお客様に表示するには、デバイスがサポートしている機能と、デバイス ハードウェアで有効になっている機能を確認する必要があります。確認する属性は次の 2 つです。

Kotlin Flows を使用した Android 開発では、通常、HomeDevice から AvStreamAnalysis トレイトを監視します。

// 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 トレイトは、カメラとドアホン デバイスの動画と画像の録画動作を管理するためのインターフェースを提供します。これにより、連続録画、アクティビティ検出時の録画、録画の完全無効化(ライブビューのみ)を選択できます。

RecordingModeEnum は、使用可能な録画戦略を定義します。

モード 列挙値 説明
無効 Disabled 録画は完全に無効になっています。主にレガシー デバイスで使用されます。
CVR (連続録画) Cvr 動画は 24 時間 365 日録画されます。定期購入が必要です (例: Google Google Home Premium)。
EBR (アクティビティ検出時の録画) Ebr アクティビティ(人物、動き)によって録画がトリガーされます。 動画の長さは、アクティビティの長さと定期購入によって異なります。
ETR (アクティビティ トリガー録画) Etr アクティビティによってトリガーされる短いプレビュー録画(10 秒など) 。
ライブビュー LiveView 録画は無効になっていますが、ライブ配信にはアクセスできます。
静止画像 Images アクティビティが発生すると、動画ではなくスナップショットが録画されます。

録画モードを確認する

現在の録画構成を表示するには、RecordingMode トレイトの属性を確認します。

// 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())
}

その他の設定

さまざまな設定は、Google Home の API で制御できます。

画像の向きを変更する

カメラ画像(動画)の向きを回転させることができます。動画は 180 度しか回転できません。

カメラの画像の向きを変更するには、組み込みの setImageRotation Kotlin 関数を使用して、CameraAvStreamManagement トレイトの imageRotation 属性を更新します。

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

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

ナイトビジョン機能をオンまたはオフにする

カメラのナイトビジョン機能をオンまたはオフにするには、TriStateAutoEnum を使用して、 nightVision 属性を、組み込みの CameraAvStreamManagement Kotlin 関数を使用して、setNightVision トレイトの更新します。

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

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

ステータス LED の明るさを変更する

ステータス LED の明るさを変更するには、 ThreeLevelAutoEnum を使用して、組み込みの setStatusLightBrightness Kotlin 関数を使用して、CameraAvStreamManagement トレイトの statusLightBrightness 属性を更新します。

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

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

カメラのビューポートを変更する

カメラのビューポートは、 Google Nest カメラの動画でズーム機能や補正機能を使用する サポート記事で説明されているズームと切り抜き機能と同じです。

ビューポートは、ビューポートの座標として使用される 4 つの値を含む ViewportStruct で定義されます。座標は次のように定義されます。

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

ViewportStruct の値を決定する方法は、アプリの UI とカメラの実装によって異なります。基本的なレベルでは、カメラの 動画のビューポートを設定するには、組み込みの setViewport Kotlin 関数を使用して、ViewportStructCameraAvStreamManagement トレイトの 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(),
    )
) }

デバイスの復帰感度を調整する

デバイスの復帰感度は、デバイスがアクティビティを検知できる範囲を狭め、アクティビティを検出してから復帰するまでの時間を長くすることで、バッテリーを節約するために使用されます。

Google Home の API では、デバイスの transportOptionstriggerOptionsmotionSensitivity プロパティを使用して設定できます。これらのオプションは、デバイスごとに PushAvStreamTransport トレイト内で定義されます。

復帰感度は、次の値にのみ設定できます。

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

更新プロセスでは、アクティブな 録画ストリームの転送構成を findTransport コマンドを使用して見つけ、 modifyPushTransport コマンドを使用して新しい感度値で構成を変更します。

// 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,
      )
    }
  }

最長アクティビティ時間を調整する

最長アクティビティ時間は、カメラがアクティビティのクリップを録画する時間の長さです。Google Home の API では、デバイスごとに、GHA と同じ 長さ(秒単位)で構成できます。

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

Google Home の API では、デバイスの transportOptionstriggerOptionsmotionTimeControl プロパティを使用して設定できます。これらのオプションは、デバイスごとに PushAvStreamTransport トレイト内で定義されます。

更新プロセスでは、アクティブな 録画ストリームの転送構成を findTransport コマンドを使用して見つけ、新しいアクティビティ時間値で構成を modifyPushTransport コマンドを使用して変更します。

// 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 クラウドに送信することを個別にオプトインできます(Google Home の API の Cloud Monitoring をご覧ください)。

デバイスの分析を有効にするには、 analyticsEnabledExtendedGeneralDiagnosticsTraittrue に設定します。analyticsEnabled を設定すると、別のプロパティ logUploadEnabled が自動的に true に設定され、分析ログファイルを Google Home クラウドにアップロードできるようになります。

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

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