Gunakan BatchPutAssetPropertyValue dengan AWS SDK atau CLI - AWS SDKContoh Kode

Ada lebih banyak AWS SDK contoh yang tersedia di GitHub repo SDKContoh AWS Dokumen.

Terjemahan disediakan oleh mesin penerjemah. Jika konten terjemahan yang diberikan bertentangan dengan versi bahasa Inggris aslinya, utamakan versi bahasa Inggris.

Gunakan BatchPutAssetPropertyValue dengan AWS SDK atau CLI

Contoh kode berikut menunjukkan cara menggunakanBatchPutAssetPropertyValue.

CLI
AWS CLI

Untuk mengirim data ke properti aset

batch-put-asset-property-valueContoh berikut mengirimkan data daya dan suhu ke properti aset yang diidentifikasi oleh alias properti.

aws iotsitewise batch-put-asset-property-value \ --cli-input-json file://batch-put-asset-property-value.json

Isi dari batch-put-asset-property-value.json:

{ "entries": [ { "entryId": "1575691200-company-windfarm-3-turbine-7-power", "propertyAlias": "company-windfarm-3-turbine-7-power", "propertyValues": [ { "value": { "doubleValue": 4.92 }, "timestamp": { "timeInSeconds": 1575691200 }, "quality": "GOOD" } ] }, { "entryId": "1575691200-company-windfarm-3-turbine-7-temperature", "propertyAlias": "company-windfarm-3-turbine-7-temperature", "propertyValues": [ { "value": { "integerValue": 38 }, "timestamp": { "timeInSeconds": 1575691200 } } ] } ] }

Output:

{ "errorEntries": [] }

Untuk informasi selengkapnya, lihat Menyerap data menggunakan AWS SiteWise API IoT di Panduan Pengguna AWS IoT SiteWise .

Java
SDKuntuk Java 2.x
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara pengaturan dan menjalankannya di Repositori Contoh Kode AWS.

/** * Sends data to the SiteWise service. * * @param assetId the ID of the asset to which the data will be sent. * @param tempPropertyId the ID of the temperature property. * @param humidityPropId the ID of the humidity property. * @return a {@link CompletableFuture} that represents a {@link BatchPutAssetPropertyValueResponse} result. The * calling code can attach callbacks, then handle the result or exception by calling * {@link CompletableFuture#join()} or {@link CompletableFuture#get()}. * <p> * If any completion stage in this method throws an exception, the method logs the exception cause and keeps it * available to the calling code as a {@link CompletionException}. By calling * {@link CompletionException#getCause()}, the calling code can access the original exception. */ public CompletableFuture<BatchPutAssetPropertyValueResponse> sendDataToSiteWiseAsync(String assetId, String tempPropertyId, String humidityPropId) { Map<String, Double> sampleData = generateSampleData(); long timestamp = Instant.now().toEpochMilli(); TimeInNanos time = TimeInNanos.builder() .timeInSeconds(timestamp / 1000) .offsetInNanos((int) ((timestamp % 1000) * 1000000)) .build(); BatchPutAssetPropertyValueRequest request = BatchPutAssetPropertyValueRequest.builder() .entries(Arrays.asList( PutAssetPropertyValueEntry.builder() .entryId("entry-3") .assetId(assetId) .propertyId(tempPropertyId) .propertyValues(Arrays.asList( AssetPropertyValue.builder() .value(Variant.builder() .doubleValue(sampleData.get("Temperature")) .build()) .timestamp(time) .build() )) .build(), PutAssetPropertyValueEntry.builder() .entryId("entry-4") .assetId(assetId) .propertyId(humidityPropId) .propertyValues(Arrays.asList( AssetPropertyValue.builder() .value(Variant.builder() .doubleValue(sampleData.get("Humidity")) .build()) .timestamp(time) .build() )) .build() )) .build(); return getAsyncClient().batchPutAssetPropertyValue(request) .whenComplete((response, exception) -> { if (exception != null) { logger.error("An exception occurred: {}", exception.getCause().getMessage()); } }); }
Python
SDKuntuk Python (Boto3)
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara pengaturan dan menjalankannya di Repositori Contoh Kode AWS.

class IoTSitewiseWrapper: """Encapsulates AWS IoT SiteWise actions using the client interface.""" def __init__(self, iotsitewise_client: client) -> None: """ Initializes the IoTSitewiseWrapper with an AWS IoT SiteWise client. :param iotsitewise_client: A Boto3 AWS IoT SiteWise client. This client provides low-level access to AWS IoT SiteWise services. """ self.iotsitewise_client = iotsitewise_client self.entry_id = 0 # Incremented to generate unique entry IDs for batch_put_asset_property_value. @classmethod def from_client(cls) -> "IoTSitewiseWrapper": """ Creates an IoTSitewiseWrapper instance with a default AWS IoT SiteWise client. :return: An instance of IoTSitewiseWrapper initialized with the default AWS IoT SiteWise client. """ iotsitewise_client = boto3.client("iotsitewise") return cls(iotsitewise_client) def batch_put_asset_property_value( self, asset_id: str, values: List[Dict[str, str]] ) -> None: """ Sends data to an AWS IoT SiteWise Asset. :param asset_id: The asset ID. :param values: A list of dictionaries containing the values in the form {propertyId : property_id, valueType : [stringValue|integerValue|doubleValue|booleanValue], value : the_value}. """ try: entries = self.properties_to_values(asset_id, values) self.iotsitewise_client.batch_put_asset_property_value(entries=entries) except ClientError as err: if err.response["Error"]["Code"] == "ResourceNotFoundException": logger.error("Asset %s does not exist.", asset_id) else: logger.error( "Error sending data to asset. Here's why %s", err.response["Error"]["Message"], ) raise

Fungsi pembantu untuk menghasilkan parameter entri dari daftar nilai.

def properties_to_values( self, asset_id: str, values: list[dict[str, Any]] ) -> list[dict[str, Any]]: """ Utility function to convert a values list to the entries parameter for batch_put_asset_property_value. :param asset_id : The asset ID. :param values : A list of dictionaries containing the values in the form {propertyId : property_id, valueType : [stringValue|integerValue|doubleValue|booleanValue], value : the_value}. :return: An entries list to pass as the 'entries' parameter to batch_put_asset_property_value. """ entries = [] for value in values: epoch_ns = time.time_ns() self.entry_id += 1 if value["valueType"] == "stringValue": property_value = {"stringValue": value["value"]} elif value["valueType"] == "integerValue": property_value = {"integerValue": value["value"]} elif value["valueType"] == "booleanValue": property_value = {"booleanValue": value["value"]} elif value["valueType"] == "doubleValue": property_value = {"doubleValue": value["value"]} else: raise ValueError("Invalid valueType: %s", value["valueType"]) entry = { "entryId": f"{self.entry_id}", "assetId": asset_id, "propertyId": value["propertyId"], "propertyValues": [ { "value": property_value, "timestamp": { "timeInSeconds": int(epoch_ns / 1000000000), "offsetInNanos": epoch_ns % 1000000000, }, } ], } entries.append(entry) return entries

Berikut adalah contoh daftar nilai untuk diteruskan ke fungsi pembantu.

values = [ { "propertyId": humidity_property_id, "valueType": "doubleValue", "value": 65.0, }, { "propertyId": temperature_property_id, "valueType": "doubleValue", "value": 23.5, }, ]