Google Cloud IoT Core is being retired on August 16, 2023. Contact your Google Cloud account team for more information.

Set device state

Stay organized with collections Save and categorize content based on your preferences.

Set a device's state.

Code sample

PHP

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);
}

What's next

To search and filter code samples for other Google Cloud products, see the Google Cloud sample browser.