Google Cloud IoT Core は 2023 年 8 月 16 日に廃止されます。詳細については、担当の Google Cloud アカウント チームにお問い合わせください。

デバイスの状態を設定する

デバイスの状態を設定します。

コードサンプル

PHP

詳細については、Cloud IoT Core PHP の API のリファレンス ドキュメントをご覧ください。

Cloud IoT Core 認証するには、アプリケーションのデフォルト認証情報を設定します。 詳細については、ローカル開発環境の認証の設定をご覧ください。

use GuzzleHttp\Client;
use Firebase\JWT\JWT;

/**
 * Set a device's state.
 *
 * @param string $registryId IOT Device Registry ID
 * @param string $deviceId IOT Device ID
 * @param string $certificateFile Path to the RSA certificate file
 * @param string $stateData Binary data for the device state
 * @param string $projectId Google Cloud project ID
 * @param string $location (Optional) Google Cloud region
 */
function set_device_state(
    $registryId,
    $deviceId,
    $certificateFile,
    $stateData,
    $projectId,
    $location = 'us-central1'
) {
    print('Set device state' . PHP_EOL);

    // Instantiate an HTTP client.
    $httpClient = new Client();

    // Create/Sign a JWT for device authentication
    // @see https://cloud.google.com/iot/docs/how-tos/credentials/jwts
    $jwt = JWT::encode(
        ['aud' => $projectId, 'iat' => time(), 'exp' => time() + 3600],
        file_get_contents($certificateFile),
        'RS256'
    );

    // Format the device's URL
    $deviceName = sprintf('projects/%s/locations/%s/registries/%s/devices/%s',
        $projectId, $location, $registryId, $deviceId);

    $url = sprintf('https://cloudiotdevice.googleapis.com/v1/%s:setState', $deviceName);

    // Make the HTTP request
    $response = $httpClient->post($url, [
        'json' => [
            'state' => [
                'binaryData' => base64_encode($stateData)
            ]
        ],
        'headers' => [
            'Authorization' => sprintf('Bearer %s', $jwt)
        ]
    ]);

    print('Updated device State' . PHP_EOL);
}

次のステップ

他の Google Cloud プロダクトに関連するコードサンプルの検索およびフィルタ検索を行うには、Google Cloud のサンプルをご覧ください。