diff --git a/.coveragerc b/.coveragerc index dd39c854..6abe3a19 100644 --- a/.coveragerc +++ b/.coveragerc @@ -21,15 +21,14 @@ branch = True [report] fail_under = 100 show_missing = True +omit = google/cloud/iot/__init__.py exclude_lines = # Re-enable the standard pragma pragma: NO COVER # Ignore debug-only repr def __repr__ - # Ignore abstract methods - raise NotImplementedError -omit = - */gapic/*.py - */proto/*.py - */core/*.py - */site-packages/*.py \ No newline at end of file + # Ignore pkg_resources exceptions. + # This is added at the module level as a safeguard for if someone + # generates the code and tries to run it without pip installing. This + # makes it virtually impossible to test properly. + except pkg_resources.DistributionNotFound \ No newline at end of file diff --git a/README.rst b/README.rst index 258c2c16..77955b41 100644 --- a/README.rst +++ b/README.rst @@ -50,11 +50,13 @@ dependencies. Supported Python Versions ^^^^^^^^^^^^^^^^^^^^^^^^^ -Python >= 3.5 +Python >= 3.6 Deprecated Python Versions ^^^^^^^^^^^^^^^^^^^^^^^^^^ -Python == 2.7. Python 2.7 support will be removed on January 1, 2020. +Python == 2.7. + +The last version of this library compatible with Python 2.7 is google-cloud-iot==1.0.0. Mac/Linux diff --git a/UPGRADING.md b/UPGRADING.md new file mode 100644 index 00000000..32c8329d --- /dev/null +++ b/UPGRADING.md @@ -0,0 +1,157 @@ +# 2.0.0 Migration Guide + +The 2.0 release of the `google-cloud-iot` client is a significant upgrade based on a [next-gen code generator](https://github.com/googleapis/gapic-generator-python), and includes substantial interface changes. Existing code written for earlier versions of this library will likely require updates to use this version. This document describes the changes that have been made, and what you need to do to update your usage. + +If you experience issues or have questions, please file an [issue](https://github.com/googleapis/python-iot/issues). + +## Supported Python Versions + +> **WARNING**: Breaking change + +The 2.0.0 release requires Python 3.6+. + + +## Method Calls + +> **WARNING**: Breaking change + +Methods expect request objects. We provide a script that will convert most common use cases. + +* Install the library + +```py +python3 -m pip install google-cloud-iot +``` + +* The script `fixup_iot_v1_keywords.py` is shipped with the library. It expects +an input directory (with the code to convert) and an empty destination directory. + +```sh +$ fixup_iot_v1_keywords.py --input-directory .samples/ --output-directory samples/ +``` + +**Before:** +```py +from google.cloud import iot_v1 + +client = iot_v1.DeviceManagerClient() + +registry = client.get_device_registry("registry_name") +``` + + +**After:** +```py +from google.cloud import iot_v1 + +client = iot_v1.DeviceManagerClient() + +registry = client.get_device_registry(request={'name': "registry_name"}) +``` + +### More Details + +In `google-cloud-iot<2.0.0`, parameters required by the API were positional parameters and optional parameters were keyword parameters. + +**Before:** +```py + def create_device( + self, + parent, + device, + retry=google.api_core.gapic_v1.method.DEFAULT, + timeout=google.api_core.gapic_v1.method.DEFAULT, + metadata=None, + ): +``` + +In the 2.0.0 release, all methods have a single positional parameter `request`. Method docstrings indicate whether a parameter is required or optional. + +Some methods have additional keyword only parameters. The available parameters depend on the `google.api.method_signature` annotation specified by the API producer. + + +**After:** +```py + def create_device( + self, + request: device_manager.CreateDeviceRequest = None, + *, + parent: str = None, + device: resources.Device = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.Device: +``` + +> **NOTE:** The `request` parameter and flattened keyword parameters for the API are mutually exclusive. +> Passing both will result in an error. + + +Both of these calls are valid: + +```py +response = client.create_device( + request={ + "parent": parent, + "device": device, + } +) +``` + +```py +response = client.create_device( + parent=parent, + device=device, +) +``` + +This call is invalid because it mixes `request` with a keyword argument `device`. Executing this code +will result in an error. + +```py +response = client.create_device( + request={ + "parent": parent, + }, + device=device +) +``` + + + +## Enums and Types + + +> **WARNING**: Breaking change + +The submodules `enums` and `types` have been removed. + +**Before:** +```py +from google.cloud import iot_v1 + +gateway_type = iot_v1.enums.GatewayType.GATEWAY +device = iot_v1.types.Device(name="name") +``` + + +**After:** +```py +from google.cloud import iot_v1 + +gateway_type = iot_v1.GatewayType.GATEWAY +device = iot_v1.Device(name="name") +``` + +## Location Path Helper Method + +Location path helper method has been removed. Please construct +the path manually. + +```py +project = 'my-project' +location = 'location' + +location_path = f'projects/{project}/locations/{location}' +``` \ No newline at end of file diff --git a/docs/UPGRADING.md b/docs/UPGRADING.md new file mode 120000 index 00000000..01097c8c --- /dev/null +++ b/docs/UPGRADING.md @@ -0,0 +1 @@ +../UPGRADING.md \ No newline at end of file diff --git a/docs/gapic/v1/api.rst b/docs/gapic/v1/api.rst deleted file mode 100644 index dc91697f..00000000 --- a/docs/gapic/v1/api.rst +++ /dev/null @@ -1,6 +0,0 @@ -Client for Cloud IoT API -======================== - -.. automodule:: google.cloud.iot_v1 - :members: - :inherited-members: \ No newline at end of file diff --git a/docs/gapic/v1/types.rst b/docs/gapic/v1/types.rst deleted file mode 100644 index fa7bab9d..00000000 --- a/docs/gapic/v1/types.rst +++ /dev/null @@ -1,5 +0,0 @@ -Types for Cloud IoT API Client -============================== - -.. automodule:: google.cloud.iot_v1.types - :members: \ No newline at end of file diff --git a/docs/index.rst b/docs/index.rst index 2fafcc45..a6b052d3 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -7,8 +7,19 @@ Api Reference .. toctree:: :maxdepth: 2 - gapic/v1/api - gapic/v1/types + iot_v1/services + iot_v1/types + + +Migration Guide +--------------- + +See the guide below for instructions on migrating to the 2.x release of this library. + +.. toctree:: + :maxdepth: 2 + + UPGRADING Changelog diff --git a/docs/iot_v1/services.rst b/docs/iot_v1/services.rst new file mode 100644 index 00000000..c077b659 --- /dev/null +++ b/docs/iot_v1/services.rst @@ -0,0 +1,6 @@ +Services for Google Cloud Iot v1 API +==================================== + +.. automodule:: google.cloud.iot_v1.services.device_manager + :members: + :inherited-members: diff --git a/docs/iot_v1/types.rst b/docs/iot_v1/types.rst new file mode 100644 index 00000000..f4ffca48 --- /dev/null +++ b/docs/iot_v1/types.rst @@ -0,0 +1,5 @@ +Types for Google Cloud Iot v1 API +================================= + +.. automodule:: google.cloud.iot_v1.types + :members: diff --git a/google/cloud/iot.py b/google/cloud/iot.py deleted file mode 100644 index 66493952..00000000 --- a/google/cloud/iot.py +++ /dev/null @@ -1,21 +0,0 @@ -# Copyright 2018 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from __future__ import absolute_import - -from google.cloud.iot_v1 import DeviceManagerClient -from google.cloud.iot_v1 import enums -from google.cloud.iot_v1 import types - -__all__ = ("enums", "types", "DeviceManagerClient") diff --git a/google/cloud/iot/__init__.py b/google/cloud/iot/__init__.py new file mode 100644 index 00000000..ecd9dab0 --- /dev/null +++ b/google/cloud/iot/__init__.py @@ -0,0 +1,116 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from google.cloud.iot_v1.services.device_manager.async_client import ( + DeviceManagerAsyncClient, +) +from google.cloud.iot_v1.services.device_manager.client import DeviceManagerClient +from google.cloud.iot_v1.types.device_manager import BindDeviceToGatewayRequest +from google.cloud.iot_v1.types.device_manager import BindDeviceToGatewayResponse +from google.cloud.iot_v1.types.device_manager import CreateDeviceRegistryRequest +from google.cloud.iot_v1.types.device_manager import CreateDeviceRequest +from google.cloud.iot_v1.types.device_manager import DeleteDeviceRegistryRequest +from google.cloud.iot_v1.types.device_manager import DeleteDeviceRequest +from google.cloud.iot_v1.types.device_manager import GatewayListOptions +from google.cloud.iot_v1.types.device_manager import GetDeviceRegistryRequest +from google.cloud.iot_v1.types.device_manager import GetDeviceRequest +from google.cloud.iot_v1.types.device_manager import ListDeviceConfigVersionsRequest +from google.cloud.iot_v1.types.device_manager import ListDeviceConfigVersionsResponse +from google.cloud.iot_v1.types.device_manager import ListDeviceRegistriesRequest +from google.cloud.iot_v1.types.device_manager import ListDeviceRegistriesResponse +from google.cloud.iot_v1.types.device_manager import ListDeviceStatesRequest +from google.cloud.iot_v1.types.device_manager import ListDeviceStatesResponse +from google.cloud.iot_v1.types.device_manager import ListDevicesRequest +from google.cloud.iot_v1.types.device_manager import ListDevicesResponse +from google.cloud.iot_v1.types.device_manager import ModifyCloudToDeviceConfigRequest +from google.cloud.iot_v1.types.device_manager import SendCommandToDeviceRequest +from google.cloud.iot_v1.types.device_manager import SendCommandToDeviceResponse +from google.cloud.iot_v1.types.device_manager import UnbindDeviceFromGatewayRequest +from google.cloud.iot_v1.types.device_manager import UnbindDeviceFromGatewayResponse +from google.cloud.iot_v1.types.device_manager import UpdateDeviceRegistryRequest +from google.cloud.iot_v1.types.device_manager import UpdateDeviceRequest +from google.cloud.iot_v1.types.resources import Device +from google.cloud.iot_v1.types.resources import DeviceConfig +from google.cloud.iot_v1.types.resources import DeviceCredential +from google.cloud.iot_v1.types.resources import DeviceRegistry +from google.cloud.iot_v1.types.resources import DeviceState +from google.cloud.iot_v1.types.resources import EventNotificationConfig +from google.cloud.iot_v1.types.resources import GatewayAuthMethod +from google.cloud.iot_v1.types.resources import GatewayConfig +from google.cloud.iot_v1.types.resources import GatewayType +from google.cloud.iot_v1.types.resources import HttpConfig +from google.cloud.iot_v1.types.resources import HttpState +from google.cloud.iot_v1.types.resources import LogLevel +from google.cloud.iot_v1.types.resources import MqttConfig +from google.cloud.iot_v1.types.resources import MqttState +from google.cloud.iot_v1.types.resources import PublicKeyCertificate +from google.cloud.iot_v1.types.resources import PublicKeyCertificateFormat +from google.cloud.iot_v1.types.resources import PublicKeyCredential +from google.cloud.iot_v1.types.resources import PublicKeyFormat +from google.cloud.iot_v1.types.resources import RegistryCredential +from google.cloud.iot_v1.types.resources import StateNotificationConfig +from google.cloud.iot_v1.types.resources import X509CertificateDetails + +__all__ = ( + "BindDeviceToGatewayRequest", + "BindDeviceToGatewayResponse", + "CreateDeviceRegistryRequest", + "CreateDeviceRequest", + "DeleteDeviceRegistryRequest", + "DeleteDeviceRequest", + "Device", + "DeviceConfig", + "DeviceCredential", + "DeviceManagerAsyncClient", + "DeviceManagerClient", + "DeviceRegistry", + "DeviceState", + "EventNotificationConfig", + "GatewayAuthMethod", + "GatewayConfig", + "GatewayListOptions", + "GatewayType", + "GetDeviceRegistryRequest", + "GetDeviceRequest", + "HttpConfig", + "HttpState", + "ListDeviceConfigVersionsRequest", + "ListDeviceConfigVersionsResponse", + "ListDeviceRegistriesRequest", + "ListDeviceRegistriesResponse", + "ListDeviceStatesRequest", + "ListDeviceStatesResponse", + "ListDevicesRequest", + "ListDevicesResponse", + "LogLevel", + "ModifyCloudToDeviceConfigRequest", + "MqttConfig", + "MqttState", + "PublicKeyCertificate", + "PublicKeyCertificateFormat", + "PublicKeyCredential", + "PublicKeyFormat", + "RegistryCredential", + "SendCommandToDeviceRequest", + "SendCommandToDeviceResponse", + "StateNotificationConfig", + "UnbindDeviceFromGatewayRequest", + "UnbindDeviceFromGatewayResponse", + "UpdateDeviceRegistryRequest", + "UpdateDeviceRequest", + "X509CertificateDetails", +) diff --git a/google/cloud/iot/py.typed b/google/cloud/iot/py.typed new file mode 100644 index 00000000..d89d40c8 --- /dev/null +++ b/google/cloud/iot/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-iot package uses inline types. diff --git a/google/cloud/iot_v1/__init__.py b/google/cloud/iot_v1/__init__.py index eb1976de..be964c8e 100644 --- a/google/cloud/iot_v1/__init__.py +++ b/google/cloud/iot_v1/__init__.py @@ -1,45 +1,113 @@ # -*- coding: utf-8 -*- -# + # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # -# https://www.apache.org/licenses/LICENSE-2.0 +# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. +# - -from __future__ import absolute_import -import sys -import warnings - -from google.cloud.iot_v1 import types -from google.cloud.iot_v1.gapic import device_manager_client -from google.cloud.iot_v1.gapic import enums - - -if sys.version_info[:2] == (2, 7): - message = ( - "A future version of this library will drop support for Python 2.7. " - "More details about Python 2 support for Google Cloud Client Libraries " - "can be found at https://cloud.google.com/python/docs/python2-sunset/" - ) - warnings.warn(message, DeprecationWarning) - - -class DeviceManagerClient(device_manager_client.DeviceManagerClient): - __doc__ = device_manager_client.DeviceManagerClient.__doc__ - enums = enums +from .services.device_manager import DeviceManagerClient +from .types.device_manager import BindDeviceToGatewayRequest +from .types.device_manager import BindDeviceToGatewayResponse +from .types.device_manager import CreateDeviceRegistryRequest +from .types.device_manager import CreateDeviceRequest +from .types.device_manager import DeleteDeviceRegistryRequest +from .types.device_manager import DeleteDeviceRequest +from .types.device_manager import GatewayListOptions +from .types.device_manager import GetDeviceRegistryRequest +from .types.device_manager import GetDeviceRequest +from .types.device_manager import ListDeviceConfigVersionsRequest +from .types.device_manager import ListDeviceConfigVersionsResponse +from .types.device_manager import ListDeviceRegistriesRequest +from .types.device_manager import ListDeviceRegistriesResponse +from .types.device_manager import ListDeviceStatesRequest +from .types.device_manager import ListDeviceStatesResponse +from .types.device_manager import ListDevicesRequest +from .types.device_manager import ListDevicesResponse +from .types.device_manager import ModifyCloudToDeviceConfigRequest +from .types.device_manager import SendCommandToDeviceRequest +from .types.device_manager import SendCommandToDeviceResponse +from .types.device_manager import UnbindDeviceFromGatewayRequest +from .types.device_manager import UnbindDeviceFromGatewayResponse +from .types.device_manager import UpdateDeviceRegistryRequest +from .types.device_manager import UpdateDeviceRequest +from .types.resources import Device +from .types.resources import DeviceConfig +from .types.resources import DeviceCredential +from .types.resources import DeviceRegistry +from .types.resources import DeviceState +from .types.resources import EventNotificationConfig +from .types.resources import GatewayAuthMethod +from .types.resources import GatewayConfig +from .types.resources import GatewayType +from .types.resources import HttpConfig +from .types.resources import HttpState +from .types.resources import LogLevel +from .types.resources import MqttConfig +from .types.resources import MqttState +from .types.resources import PublicKeyCertificate +from .types.resources import PublicKeyCertificateFormat +from .types.resources import PublicKeyCredential +from .types.resources import PublicKeyFormat +from .types.resources import RegistryCredential +from .types.resources import StateNotificationConfig +from .types.resources import X509CertificateDetails __all__ = ( - "enums", - "types", + "BindDeviceToGatewayRequest", + "BindDeviceToGatewayResponse", + "CreateDeviceRegistryRequest", + "CreateDeviceRequest", + "DeleteDeviceRegistryRequest", + "DeleteDeviceRequest", + "Device", + "DeviceConfig", + "DeviceCredential", + "DeviceRegistry", + "DeviceState", + "EventNotificationConfig", + "GatewayAuthMethod", + "GatewayConfig", + "GatewayListOptions", + "GatewayType", + "GetDeviceRegistryRequest", + "GetDeviceRequest", + "HttpConfig", + "HttpState", + "ListDeviceConfigVersionsRequest", + "ListDeviceConfigVersionsResponse", + "ListDeviceRegistriesRequest", + "ListDeviceRegistriesResponse", + "ListDeviceStatesRequest", + "ListDeviceStatesResponse", + "ListDevicesRequest", + "ListDevicesResponse", + "LogLevel", + "ModifyCloudToDeviceConfigRequest", + "MqttConfig", + "MqttState", + "PublicKeyCertificate", + "PublicKeyCertificateFormat", + "PublicKeyCredential", + "PublicKeyFormat", + "RegistryCredential", + "SendCommandToDeviceRequest", + "SendCommandToDeviceResponse", + "StateNotificationConfig", + "UnbindDeviceFromGatewayRequest", + "UnbindDeviceFromGatewayResponse", + "UpdateDeviceRegistryRequest", + "UpdateDeviceRequest", + "X509CertificateDetails", "DeviceManagerClient", ) diff --git a/google/cloud/iot_v1/gapic/__init__.py b/google/cloud/iot_v1/gapic/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/google/cloud/iot_v1/gapic/device_manager_client.py b/google/cloud/iot_v1/gapic/device_manager_client.py deleted file mode 100644 index 0ab40a26..00000000 --- a/google/cloud/iot_v1/gapic/device_manager_client.py +++ /dev/null @@ -1,1846 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Accesses the google.cloud.iot.v1 DeviceManager API.""" - -import functools -import pkg_resources -import warnings - -from google.oauth2 import service_account -import google.api_core.client_options -import google.api_core.gapic_v1.client_info -import google.api_core.gapic_v1.config -import google.api_core.gapic_v1.method -import google.api_core.gapic_v1.routing_header -import google.api_core.grpc_helpers -import google.api_core.page_iterator -import google.api_core.path_template -import grpc - -from google.cloud.iot_v1.gapic import device_manager_client_config -from google.cloud.iot_v1.gapic import enums -from google.cloud.iot_v1.gapic.transports import device_manager_grpc_transport -from google.cloud.iot_v1.proto import device_manager_pb2 -from google.cloud.iot_v1.proto import device_manager_pb2_grpc -from google.cloud.iot_v1.proto import resources_pb2 -from google.iam.v1 import iam_policy_pb2 -from google.iam.v1 import options_pb2 -from google.iam.v1 import policy_pb2 -from google.protobuf import empty_pb2 -from google.protobuf import field_mask_pb2 - - -_GAPIC_LIBRARY_VERSION = pkg_resources.get_distribution("google-cloud-iot",).version - - -class DeviceManagerClient(object): - """Internet of Things (IoT) service. Securely connect and manage IoT devices.""" - - SERVICE_ADDRESS = "cloudiot.googleapis.com:443" - """The default address of the service.""" - - # The name of the interface for this client. This is the key used to - # find the method configuration in the client_config dictionary. - _INTERFACE_NAME = "google.cloud.iot.v1.DeviceManager" - - @classmethod - def from_service_account_file(cls, filename, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - DeviceManagerClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_file(filename) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - from_service_account_json = from_service_account_file - - @classmethod - def device_path(cls, project, location, registry, device): - """Return a fully-qualified device string.""" - return google.api_core.path_template.expand( - "projects/{project}/locations/{location}/registries/{registry}/devices/{device}", - project=project, - location=location, - registry=registry, - device=device, - ) - - @classmethod - def location_path(cls, project, location): - """Return a fully-qualified location string.""" - return google.api_core.path_template.expand( - "projects/{project}/locations/{location}", - project=project, - location=location, - ) - - @classmethod - def registry_path(cls, project, location, registry): - """Return a fully-qualified registry string.""" - return google.api_core.path_template.expand( - "projects/{project}/locations/{location}/registries/{registry}", - project=project, - location=location, - registry=registry, - ) - - def __init__( - self, - transport=None, - channel=None, - credentials=None, - client_config=None, - client_info=None, - client_options=None, - ): - """Constructor. - - Args: - transport (Union[~.DeviceManagerGrpcTransport, - Callable[[~.Credentials, type], ~.DeviceManagerGrpcTransport]): A transport - instance, responsible for actually making the API calls. - The default transport uses the gRPC protocol. - This argument may also be a callable which returns a - transport instance. Callables will be sent the credentials - as the first argument and the default transport class as - the second argument. - channel (grpc.Channel): DEPRECATED. A ``Channel`` instance - through which to make calls. This argument is mutually exclusive - with ``credentials``; providing both will raise an exception. - credentials (google.auth.credentials.Credentials): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is mutually exclusive with providing a - transport instance to ``transport``; doing so will raise - an exception. - client_config (dict): DEPRECATED. A dictionary of call options for - each method. If not specified, the default configuration is used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - client_options (Union[dict, google.api_core.client_options.ClientOptions]): - Client options used to set user options on the client. API Endpoint - should be set through client_options. - """ - # Raise deprecation warnings for things we want to go away. - if client_config is not None: - warnings.warn( - "The `client_config` argument is deprecated.", - PendingDeprecationWarning, - stacklevel=2, - ) - else: - client_config = device_manager_client_config.config - - if channel: - warnings.warn( - "The `channel` argument is deprecated; use " "`transport` instead.", - PendingDeprecationWarning, - stacklevel=2, - ) - - api_endpoint = self.SERVICE_ADDRESS - if client_options: - if type(client_options) == dict: - client_options = google.api_core.client_options.from_dict( - client_options - ) - if client_options.api_endpoint: - api_endpoint = client_options.api_endpoint - - # Instantiate the transport. - # The transport is responsible for handling serialization and - # deserialization and actually sending data to the service. - if transport: - if callable(transport): - self.transport = transport( - credentials=credentials, - default_class=device_manager_grpc_transport.DeviceManagerGrpcTransport, - address=api_endpoint, - ) - else: - if credentials: - raise ValueError( - "Received both a transport instance and " - "credentials; these are mutually exclusive." - ) - self.transport = transport - else: - self.transport = device_manager_grpc_transport.DeviceManagerGrpcTransport( - address=api_endpoint, channel=channel, credentials=credentials, - ) - - if client_info is None: - client_info = google.api_core.gapic_v1.client_info.ClientInfo( - gapic_version=_GAPIC_LIBRARY_VERSION, - ) - else: - client_info.gapic_version = _GAPIC_LIBRARY_VERSION - self._client_info = client_info - - # Parse out the default settings for retry and timeout for each RPC - # from the client configuration. - # (Ordinarily, these are the defaults specified in the `*_config.py` - # file next to this one.) - self._method_configs = google.api_core.gapic_v1.config.parse_method_configs( - client_config["interfaces"][self._INTERFACE_NAME], - ) - - # Save a dictionary of cached API call functions. - # These are the actual callables which invoke the proper - # transport methods, wrapped with `wrap_method` to add retry, - # timeout, and the like. - self._inner_api_calls = {} - - # Service calls - def delete_device_registry( - self, - name, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Deletes a device registry configuration. - - Example: - >>> from google.cloud import iot_v1 - >>> - >>> client = iot_v1.DeviceManagerClient() - >>> - >>> name = client.registry_path('[PROJECT]', '[LOCATION]', '[REGISTRY]') - >>> - >>> client.delete_device_registry(name) - - Args: - name (str): Required. The name of the device registry. For example, - ``projects/example-project/locations/us-central1/registries/my-registry``. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "delete_device_registry" not in self._inner_api_calls: - self._inner_api_calls[ - "delete_device_registry" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.delete_device_registry, - default_retry=self._method_configs["DeleteDeviceRegistry"].retry, - default_timeout=self._method_configs["DeleteDeviceRegistry"].timeout, - client_info=self._client_info, - ) - - request = device_manager_pb2.DeleteDeviceRegistryRequest(name=name,) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("name", name)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - self._inner_api_calls["delete_device_registry"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def delete_device( - self, - name, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Deletes a device. - - Example: - >>> from google.cloud import iot_v1 - >>> - >>> client = iot_v1.DeviceManagerClient() - >>> - >>> name = client.device_path('[PROJECT]', '[LOCATION]', '[REGISTRY]', '[DEVICE]') - >>> - >>> client.delete_device(name) - - Args: - name (str): Required. The name of the device. For example, - ``projects/p0/locations/us-central1/registries/registry0/devices/device0`` - or - ``projects/p0/locations/us-central1/registries/registry0/devices/{num_id}``. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "delete_device" not in self._inner_api_calls: - self._inner_api_calls[ - "delete_device" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.delete_device, - default_retry=self._method_configs["DeleteDevice"].retry, - default_timeout=self._method_configs["DeleteDevice"].timeout, - client_info=self._client_info, - ) - - request = device_manager_pb2.DeleteDeviceRequest(name=name,) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("name", name)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - self._inner_api_calls["delete_device"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def modify_cloud_to_device_config( - self, - name, - binary_data, - version_to_update=None, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Modifies the configuration for the device, which is eventually sent from - the Cloud IoT Core servers. Returns the modified configuration version and - its metadata. - - Example: - >>> from google.cloud import iot_v1 - >>> - >>> client = iot_v1.DeviceManagerClient() - >>> - >>> name = client.device_path('[PROJECT]', '[LOCATION]', '[REGISTRY]', '[DEVICE]') - >>> - >>> # TODO: Initialize `binary_data`: - >>> binary_data = b'' - >>> - >>> response = client.modify_cloud_to_device_config(name, binary_data) - - Args: - name (str): Required. The name of the device. For example, - ``projects/p0/locations/us-central1/registries/registry0/devices/device0`` - or - ``projects/p0/locations/us-central1/registries/registry0/devices/{num_id}``. - binary_data (bytes): Required. The configuration data for the device. - version_to_update (long): The version number to update. If this value is zero, it will not check the - version number of the server and will always update the current version; - otherwise, this update will fail if the version number found on the server - does not match this version number. This is used to support multiple - simultaneous updates without losing data. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.iot_v1.types.DeviceConfig` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "modify_cloud_to_device_config" not in self._inner_api_calls: - self._inner_api_calls[ - "modify_cloud_to_device_config" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.modify_cloud_to_device_config, - default_retry=self._method_configs["ModifyCloudToDeviceConfig"].retry, - default_timeout=self._method_configs[ - "ModifyCloudToDeviceConfig" - ].timeout, - client_info=self._client_info, - ) - - request = device_manager_pb2.ModifyCloudToDeviceConfigRequest( - name=name, binary_data=binary_data, version_to_update=version_to_update, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("name", name)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["modify_cloud_to_device_config"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def send_command_to_device( - self, - name, - binary_data, - subfolder=None, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Sends a command to the specified device. In order for a device to be - able to receive commands, it must: - - 1) be connected to Cloud IoT Core using the MQTT protocol, and - 2) be subscribed to the group of MQTT topics specified by - /devices/{device-id}/commands/#. This subscription will receive - commands at the top-level topic /devices/{device-id}/commands as well - as commands for subfolders, like - /devices/{device-id}/commands/subfolder. Note that subscribing to - specific subfolders is not supported. If the command could not be - delivered to the device, this method will return an error; in - particular, if the device is not subscribed, this method will return - FAILED_PRECONDITION. Otherwise, this method will return OK. If the - subscription is QoS 1, at least once delivery will be guaranteed; for - QoS 0, no acknowledgment will be expected from the device. - - Example: - >>> from google.cloud import iot_v1 - >>> - >>> client = iot_v1.DeviceManagerClient() - >>> - >>> name = client.device_path('[PROJECT]', '[LOCATION]', '[REGISTRY]', '[DEVICE]') - >>> - >>> # TODO: Initialize `binary_data`: - >>> binary_data = b'' - >>> - >>> response = client.send_command_to_device(name, binary_data) - - Args: - name (str): Required. The name of the device. For example, - ``projects/p0/locations/us-central1/registries/registry0/devices/device0`` - or - ``projects/p0/locations/us-central1/registries/registry0/devices/{num_id}``. - binary_data (bytes): Required. The command data to send to the device. - subfolder (str): Optional subfolder for the command. If empty, the command will be delivered - to the /devices/{device-id}/commands topic, otherwise it will be delivered - to the /devices/{device-id}/commands/{subfolder} topic. Multi-level - subfolders are allowed. This field must not have more than 256 characters, - and must not contain any MQTT wildcards ("+" or "#") or null characters. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.iot_v1.types.SendCommandToDeviceResponse` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "send_command_to_device" not in self._inner_api_calls: - self._inner_api_calls[ - "send_command_to_device" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.send_command_to_device, - default_retry=self._method_configs["SendCommandToDevice"].retry, - default_timeout=self._method_configs["SendCommandToDevice"].timeout, - client_info=self._client_info, - ) - - request = device_manager_pb2.SendCommandToDeviceRequest( - name=name, binary_data=binary_data, subfolder=subfolder, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("name", name)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["send_command_to_device"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def create_device_registry( - self, - parent, - device_registry, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Creates a device registry that contains devices. - - Example: - >>> from google.cloud import iot_v1 - >>> - >>> client = iot_v1.DeviceManagerClient() - >>> - >>> parent = client.location_path('[PROJECT]', '[LOCATION]') - >>> - >>> # TODO: Initialize `device_registry`: - >>> device_registry = {} - >>> - >>> response = client.create_device_registry(parent, device_registry) - - Args: - parent (str): Required. The project and cloud region where this device registry - must be created. For example, - ``projects/example-project/locations/us-central1``. - device_registry (Union[dict, ~google.cloud.iot_v1.types.DeviceRegistry]): Required. The device registry. The field ``name`` must be empty. The - server will generate that field from the device registry ``id`` provided - and the ``parent`` field. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.iot_v1.types.DeviceRegistry` - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.iot_v1.types.DeviceRegistry` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "create_device_registry" not in self._inner_api_calls: - self._inner_api_calls[ - "create_device_registry" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.create_device_registry, - default_retry=self._method_configs["CreateDeviceRegistry"].retry, - default_timeout=self._method_configs["CreateDeviceRegistry"].timeout, - client_info=self._client_info, - ) - - request = device_manager_pb2.CreateDeviceRegistryRequest( - parent=parent, device_registry=device_registry, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("parent", parent)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["create_device_registry"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def get_device_registry( - self, - name, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Gets a device registry configuration. - - Example: - >>> from google.cloud import iot_v1 - >>> - >>> client = iot_v1.DeviceManagerClient() - >>> - >>> name = client.registry_path('[PROJECT]', '[LOCATION]', '[REGISTRY]') - >>> - >>> response = client.get_device_registry(name) - - Args: - name (str): Required. The name of the device registry. For example, - ``projects/example-project/locations/us-central1/registries/my-registry``. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.iot_v1.types.DeviceRegistry` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "get_device_registry" not in self._inner_api_calls: - self._inner_api_calls[ - "get_device_registry" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.get_device_registry, - default_retry=self._method_configs["GetDeviceRegistry"].retry, - default_timeout=self._method_configs["GetDeviceRegistry"].timeout, - client_info=self._client_info, - ) - - request = device_manager_pb2.GetDeviceRegistryRequest(name=name,) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("name", name)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["get_device_registry"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def update_device_registry( - self, - device_registry, - update_mask, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Updates a device registry configuration. - - Example: - >>> from google.cloud import iot_v1 - >>> - >>> client = iot_v1.DeviceManagerClient() - >>> - >>> # TODO: Initialize `device_registry`: - >>> device_registry = {} - >>> - >>> # TODO: Initialize `update_mask`: - >>> update_mask = {} - >>> - >>> response = client.update_device_registry(device_registry, update_mask) - - Args: - device_registry (Union[dict, ~google.cloud.iot_v1.types.DeviceRegistry]): Required. The new values for the device registry. The ``id`` field - must be empty, and the ``name`` field must indicate the path of the - resource. For example, - ``projects/example-project/locations/us-central1/registries/my-registry``. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.iot_v1.types.DeviceRegistry` - update_mask (Union[dict, ~google.cloud.iot_v1.types.FieldMask]): Required. Only updates the ``device_registry`` fields indicated by - this mask. The field mask must not be empty, and it must not contain - fields that are immutable or only set by the server. Mutable top-level - fields: ``event_notification_config``, ``http_config``, ``mqtt_config``, - and ``state_notification_config``. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.iot_v1.types.FieldMask` - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.iot_v1.types.DeviceRegistry` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "update_device_registry" not in self._inner_api_calls: - self._inner_api_calls[ - "update_device_registry" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.update_device_registry, - default_retry=self._method_configs["UpdateDeviceRegistry"].retry, - default_timeout=self._method_configs["UpdateDeviceRegistry"].timeout, - client_info=self._client_info, - ) - - request = device_manager_pb2.UpdateDeviceRegistryRequest( - device_registry=device_registry, update_mask=update_mask, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("device_registry.name", device_registry.name)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["update_device_registry"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def list_device_registries( - self, - parent, - page_size=None, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Lists device registries. - - Example: - >>> from google.cloud import iot_v1 - >>> - >>> client = iot_v1.DeviceManagerClient() - >>> - >>> parent = client.location_path('[PROJECT]', '[LOCATION]') - >>> - >>> # Iterate over all results - >>> for element in client.list_device_registries(parent): - ... # process element - ... pass - >>> - >>> - >>> # Alternatively: - >>> - >>> # Iterate over results one page at a time - >>> for page in client.list_device_registries(parent).pages: - ... for element in page: - ... # process element - ... pass - - Args: - parent (str): Required. The project and cloud region path. For example, - ``projects/example-project/locations/us-central1``. - page_size (int): The maximum number of resources contained in the - underlying API response. If page streaming is performed per- - resource, this parameter does not affect the return value. If page - streaming is performed per-page, this determines the maximum number - of resources in a page. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.api_core.page_iterator.PageIterator` instance. - An iterable of :class:`~google.cloud.iot_v1.types.DeviceRegistry` instances. - You can also iterate over the pages of the response - using its `pages` property. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "list_device_registries" not in self._inner_api_calls: - self._inner_api_calls[ - "list_device_registries" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.list_device_registries, - default_retry=self._method_configs["ListDeviceRegistries"].retry, - default_timeout=self._method_configs["ListDeviceRegistries"].timeout, - client_info=self._client_info, - ) - - request = device_manager_pb2.ListDeviceRegistriesRequest( - parent=parent, page_size=page_size, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("parent", parent)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - iterator = google.api_core.page_iterator.GRPCIterator( - client=None, - method=functools.partial( - self._inner_api_calls["list_device_registries"], - retry=retry, - timeout=timeout, - metadata=metadata, - ), - request=request, - items_field="device_registries", - request_token_field="page_token", - response_token_field="next_page_token", - ) - return iterator - - def create_device( - self, - parent, - device, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Creates a device in a device registry. - - Example: - >>> from google.cloud import iot_v1 - >>> - >>> client = iot_v1.DeviceManagerClient() - >>> - >>> parent = client.registry_path('[PROJECT]', '[LOCATION]', '[REGISTRY]') - >>> - >>> # TODO: Initialize `device`: - >>> device = {} - >>> - >>> response = client.create_device(parent, device) - - Args: - parent (str): Required. The name of the device registry where this device should - be created. For example, - ``projects/example-project/locations/us-central1/registries/my-registry``. - device (Union[dict, ~google.cloud.iot_v1.types.Device]): Required. The device registration details. The field ``name`` must - be empty. The server generates ``name`` from the device registry ``id`` - and the ``parent`` field. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.iot_v1.types.Device` - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.iot_v1.types.Device` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "create_device" not in self._inner_api_calls: - self._inner_api_calls[ - "create_device" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.create_device, - default_retry=self._method_configs["CreateDevice"].retry, - default_timeout=self._method_configs["CreateDevice"].timeout, - client_info=self._client_info, - ) - - request = device_manager_pb2.CreateDeviceRequest(parent=parent, device=device,) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("parent", parent)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["create_device"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def get_device( - self, - name, - field_mask=None, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Gets details about a device. - - Example: - >>> from google.cloud import iot_v1 - >>> - >>> client = iot_v1.DeviceManagerClient() - >>> - >>> name = client.device_path('[PROJECT]', '[LOCATION]', '[REGISTRY]', '[DEVICE]') - >>> - >>> response = client.get_device(name) - - Args: - name (str): Required. The name of the device. For example, - ``projects/p0/locations/us-central1/registries/registry0/devices/device0`` - or - ``projects/p0/locations/us-central1/registries/registry0/devices/{num_id}``. - field_mask (Union[dict, ~google.cloud.iot_v1.types.FieldMask]): The fields of the ``Device`` resource to be returned in the - response. If the field mask is unset or empty, all fields are returned. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.iot_v1.types.FieldMask` - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.iot_v1.types.Device` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "get_device" not in self._inner_api_calls: - self._inner_api_calls[ - "get_device" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.get_device, - default_retry=self._method_configs["GetDevice"].retry, - default_timeout=self._method_configs["GetDevice"].timeout, - client_info=self._client_info, - ) - - request = device_manager_pb2.GetDeviceRequest(name=name, field_mask=field_mask,) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("name", name)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["get_device"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def update_device( - self, - device, - update_mask, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Updates a device. - - Example: - >>> from google.cloud import iot_v1 - >>> - >>> client = iot_v1.DeviceManagerClient() - >>> - >>> # TODO: Initialize `device`: - >>> device = {} - >>> - >>> # TODO: Initialize `update_mask`: - >>> update_mask = {} - >>> - >>> response = client.update_device(device, update_mask) - - Args: - device (Union[dict, ~google.cloud.iot_v1.types.Device]): Required. The new values for the device. The ``id`` and ``num_id`` - fields must be empty, and the field ``name`` must specify the name path. - For example, - ``projects/p0/locations/us-central1/registries/registry0/devices/device0``\ or - ``projects/p0/locations/us-central1/registries/registry0/devices/{num_id}``. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.iot_v1.types.Device` - update_mask (Union[dict, ~google.cloud.iot_v1.types.FieldMask]): Required. Only updates the ``device`` fields indicated by this mask. - The field mask must not be empty, and it must not contain fields that - are immutable or only set by the server. Mutable top-level fields: - ``credentials``, ``blocked``, and ``metadata`` - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.iot_v1.types.FieldMask` - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.iot_v1.types.Device` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "update_device" not in self._inner_api_calls: - self._inner_api_calls[ - "update_device" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.update_device, - default_retry=self._method_configs["UpdateDevice"].retry, - default_timeout=self._method_configs["UpdateDevice"].timeout, - client_info=self._client_info, - ) - - request = device_manager_pb2.UpdateDeviceRequest( - device=device, update_mask=update_mask, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("device.name", device.name)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["update_device"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def list_devices( - self, - parent, - device_num_ids=None, - device_ids=None, - field_mask=None, - gateway_list_options=None, - page_size=None, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - List devices in a device registry. - - Example: - >>> from google.cloud import iot_v1 - >>> - >>> client = iot_v1.DeviceManagerClient() - >>> - >>> parent = client.registry_path('[PROJECT]', '[LOCATION]', '[REGISTRY]') - >>> - >>> # Iterate over all results - >>> for element in client.list_devices(parent): - ... # process element - ... pass - >>> - >>> - >>> # Alternatively: - >>> - >>> # Iterate over results one page at a time - >>> for page in client.list_devices(parent).pages: - ... for element in page: - ... # process element - ... pass - - Args: - parent (str): Required. The device registry path. Required. For example, - ``projects/my-project/locations/us-central1/registries/my-registry``. - device_num_ids (list[long]): A list of device numeric IDs. If empty, this field is ignored. Maximum - IDs: 10,000. - device_ids (list[str]): A list of device string IDs. For example, - ``['device0', 'device12']``. If empty, this field is ignored. Maximum - IDs: 10,000 - field_mask (Union[dict, ~google.cloud.iot_v1.types.FieldMask]): The fields of the ``Device`` resource to be returned in the - response. The fields ``id`` and ``num_id`` are always returned, along - with any other fields specified. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.iot_v1.types.FieldMask` - gateway_list_options (Union[dict, ~google.cloud.iot_v1.types.GatewayListOptions]): Options related to gateways. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.iot_v1.types.GatewayListOptions` - page_size (int): The maximum number of resources contained in the - underlying API response. If page streaming is performed per- - resource, this parameter does not affect the return value. If page - streaming is performed per-page, this determines the maximum number - of resources in a page. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.api_core.page_iterator.PageIterator` instance. - An iterable of :class:`~google.cloud.iot_v1.types.Device` instances. - You can also iterate over the pages of the response - using its `pages` property. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "list_devices" not in self._inner_api_calls: - self._inner_api_calls[ - "list_devices" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.list_devices, - default_retry=self._method_configs["ListDevices"].retry, - default_timeout=self._method_configs["ListDevices"].timeout, - client_info=self._client_info, - ) - - request = device_manager_pb2.ListDevicesRequest( - parent=parent, - device_num_ids=device_num_ids, - device_ids=device_ids, - field_mask=field_mask, - gateway_list_options=gateway_list_options, - page_size=page_size, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("parent", parent)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - iterator = google.api_core.page_iterator.GRPCIterator( - client=None, - method=functools.partial( - self._inner_api_calls["list_devices"], - retry=retry, - timeout=timeout, - metadata=metadata, - ), - request=request, - items_field="devices", - request_token_field="page_token", - response_token_field="next_page_token", - ) - return iterator - - def list_device_config_versions( - self, - name, - num_versions=None, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Lists the last few versions of the device configuration in descending - order (i.e.: newest first). - - Example: - >>> from google.cloud import iot_v1 - >>> - >>> client = iot_v1.DeviceManagerClient() - >>> - >>> name = client.device_path('[PROJECT]', '[LOCATION]', '[REGISTRY]', '[DEVICE]') - >>> - >>> response = client.list_device_config_versions(name) - - Args: - name (str): Required. The name of the device. For example, - ``projects/p0/locations/us-central1/registries/registry0/devices/device0`` - or - ``projects/p0/locations/us-central1/registries/registry0/devices/{num_id}``. - num_versions (int): The number of versions to list. Versions are listed in decreasing order of - the version number. The maximum number of versions retained is 10. If this - value is zero, it will return all the versions available. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.iot_v1.types.ListDeviceConfigVersionsResponse` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "list_device_config_versions" not in self._inner_api_calls: - self._inner_api_calls[ - "list_device_config_versions" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.list_device_config_versions, - default_retry=self._method_configs["ListDeviceConfigVersions"].retry, - default_timeout=self._method_configs[ - "ListDeviceConfigVersions" - ].timeout, - client_info=self._client_info, - ) - - request = device_manager_pb2.ListDeviceConfigVersionsRequest( - name=name, num_versions=num_versions, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("name", name)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["list_device_config_versions"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def list_device_states( - self, - name, - num_states=None, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Lists the last few versions of the device state in descending order (i.e.: - newest first). - - Example: - >>> from google.cloud import iot_v1 - >>> - >>> client = iot_v1.DeviceManagerClient() - >>> - >>> name = client.device_path('[PROJECT]', '[LOCATION]', '[REGISTRY]', '[DEVICE]') - >>> - >>> response = client.list_device_states(name) - - Args: - name (str): Required. The name of the device. For example, - ``projects/p0/locations/us-central1/registries/registry0/devices/device0`` - or - ``projects/p0/locations/us-central1/registries/registry0/devices/{num_id}``. - num_states (int): The number of states to list. States are listed in descending order of - update time. The maximum number of states retained is 10. If this - value is zero, it will return all the states available. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.iot_v1.types.ListDeviceStatesResponse` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "list_device_states" not in self._inner_api_calls: - self._inner_api_calls[ - "list_device_states" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.list_device_states, - default_retry=self._method_configs["ListDeviceStates"].retry, - default_timeout=self._method_configs["ListDeviceStates"].timeout, - client_info=self._client_info, - ) - - request = device_manager_pb2.ListDeviceStatesRequest( - name=name, num_states=num_states, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("name", name)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["list_device_states"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def set_iam_policy( - self, - resource, - policy, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Sets the access control policy on the specified resource. Replaces any - existing policy. - - Example: - >>> from google.cloud import iot_v1 - >>> - >>> client = iot_v1.DeviceManagerClient() - >>> - >>> # TODO: Initialize `resource`: - >>> resource = '' - >>> - >>> # TODO: Initialize `policy`: - >>> policy = {} - >>> - >>> response = client.set_iam_policy(resource, policy) - - Args: - resource (str): REQUIRED: The resource for which the policy is being specified. - See the operation documentation for the appropriate value for this field. - policy (Union[dict, ~google.cloud.iot_v1.types.Policy]): REQUIRED: The complete policy to be applied to the ``resource``. The - size of the policy is limited to a few 10s of KB. An empty policy is a - valid policy but certain Cloud Platform services (such as Projects) - might reject them. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.iot_v1.types.Policy` - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.iot_v1.types.Policy` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "set_iam_policy" not in self._inner_api_calls: - self._inner_api_calls[ - "set_iam_policy" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.set_iam_policy, - default_retry=self._method_configs["SetIamPolicy"].retry, - default_timeout=self._method_configs["SetIamPolicy"].timeout, - client_info=self._client_info, - ) - - request = iam_policy_pb2.SetIamPolicyRequest(resource=resource, policy=policy,) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("resource", resource)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["set_iam_policy"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def get_iam_policy( - self, - resource, - options_=None, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Gets the access control policy for a resource. - Returns an empty policy if the resource exists and does not have a policy - set. - - Example: - >>> from google.cloud import iot_v1 - >>> - >>> client = iot_v1.DeviceManagerClient() - >>> - >>> # TODO: Initialize `resource`: - >>> resource = '' - >>> - >>> response = client.get_iam_policy(resource) - - Args: - resource (str): REQUIRED: The resource for which the policy is being requested. - See the operation documentation for the appropriate value for this field. - options_ (Union[dict, ~google.cloud.iot_v1.types.GetPolicyOptions]): OPTIONAL: A ``GetPolicyOptions`` object for specifying options to - ``GetIamPolicy``. This field is only used by Cloud IAM. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.iot_v1.types.GetPolicyOptions` - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.iot_v1.types.Policy` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "get_iam_policy" not in self._inner_api_calls: - self._inner_api_calls[ - "get_iam_policy" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.get_iam_policy, - default_retry=self._method_configs["GetIamPolicy"].retry, - default_timeout=self._method_configs["GetIamPolicy"].timeout, - client_info=self._client_info, - ) - - request = iam_policy_pb2.GetIamPolicyRequest( - resource=resource, options=options_, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("resource", resource)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["get_iam_policy"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def test_iam_permissions( - self, - resource, - permissions, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Returns permissions that a caller has on the specified resource. If - the resource does not exist, this will return an empty set of - permissions, not a NOT_FOUND error. - - Example: - >>> from google.cloud import iot_v1 - >>> - >>> client = iot_v1.DeviceManagerClient() - >>> - >>> # TODO: Initialize `resource`: - >>> resource = '' - >>> - >>> # TODO: Initialize `permissions`: - >>> permissions = [] - >>> - >>> response = client.test_iam_permissions(resource, permissions) - - Args: - resource (str): REQUIRED: The resource for which the policy detail is being requested. - See the operation documentation for the appropriate value for this field. - permissions (list[str]): The set of permissions to check for the ``resource``. Permissions - with wildcards (such as '*' or 'storage.*') are not allowed. For more - information see `IAM - Overview `__. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.iot_v1.types.TestIamPermissionsResponse` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "test_iam_permissions" not in self._inner_api_calls: - self._inner_api_calls[ - "test_iam_permissions" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.test_iam_permissions, - default_retry=self._method_configs["TestIamPermissions"].retry, - default_timeout=self._method_configs["TestIamPermissions"].timeout, - client_info=self._client_info, - ) - - request = iam_policy_pb2.TestIamPermissionsRequest( - resource=resource, permissions=permissions, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("resource", resource)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["test_iam_permissions"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def bind_device_to_gateway( - self, - parent, - gateway_id, - device_id, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Associates the device with the gateway. - - Example: - >>> from google.cloud import iot_v1 - >>> - >>> client = iot_v1.DeviceManagerClient() - >>> - >>> parent = client.registry_path('[PROJECT]', '[LOCATION]', '[REGISTRY]') - >>> - >>> # TODO: Initialize `gateway_id`: - >>> gateway_id = '' - >>> - >>> # TODO: Initialize `device_id`: - >>> device_id = '' - >>> - >>> response = client.bind_device_to_gateway(parent, gateway_id, device_id) - - Args: - parent (str): Required. The name of the registry. For example, - ``projects/example-project/locations/us-central1/registries/my-registry``. - gateway_id (str): Required. The value of ``gateway_id`` can be either the device - numeric ID or the user-defined device identifier. - device_id (str): Required. The device to associate with the specified gateway. The - value of ``device_id`` can be either the device numeric ID or the - user-defined device identifier. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.iot_v1.types.BindDeviceToGatewayResponse` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "bind_device_to_gateway" not in self._inner_api_calls: - self._inner_api_calls[ - "bind_device_to_gateway" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.bind_device_to_gateway, - default_retry=self._method_configs["BindDeviceToGateway"].retry, - default_timeout=self._method_configs["BindDeviceToGateway"].timeout, - client_info=self._client_info, - ) - - request = device_manager_pb2.BindDeviceToGatewayRequest( - parent=parent, gateway_id=gateway_id, device_id=device_id, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("parent", parent)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["bind_device_to_gateway"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def unbind_device_from_gateway( - self, - parent, - gateway_id, - device_id, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Deletes the association between the device and the gateway. - - Example: - >>> from google.cloud import iot_v1 - >>> - >>> client = iot_v1.DeviceManagerClient() - >>> - >>> parent = client.registry_path('[PROJECT]', '[LOCATION]', '[REGISTRY]') - >>> - >>> # TODO: Initialize `gateway_id`: - >>> gateway_id = '' - >>> - >>> # TODO: Initialize `device_id`: - >>> device_id = '' - >>> - >>> response = client.unbind_device_from_gateway(parent, gateway_id, device_id) - - Args: - parent (str): Required. The name of the registry. For example, - ``projects/example-project/locations/us-central1/registries/my-registry``. - gateway_id (str): Required. The value of ``gateway_id`` can be either the device - numeric ID or the user-defined device identifier. - device_id (str): Required. The device to disassociate from the specified gateway. The - value of ``device_id`` can be either the device numeric ID or the - user-defined device identifier. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.iot_v1.types.UnbindDeviceFromGatewayResponse` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "unbind_device_from_gateway" not in self._inner_api_calls: - self._inner_api_calls[ - "unbind_device_from_gateway" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.unbind_device_from_gateway, - default_retry=self._method_configs["UnbindDeviceFromGateway"].retry, - default_timeout=self._method_configs["UnbindDeviceFromGateway"].timeout, - client_info=self._client_info, - ) - - request = device_manager_pb2.UnbindDeviceFromGatewayRequest( - parent=parent, gateway_id=gateway_id, device_id=device_id, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("parent", parent)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["unbind_device_from_gateway"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) diff --git a/google/cloud/iot_v1/gapic/device_manager_client_config.py b/google/cloud/iot_v1/gapic/device_manager_client_config.py deleted file mode 100644 index 84d8883c..00000000 --- a/google/cloud/iot_v1/gapic/device_manager_client_config.py +++ /dev/null @@ -1,132 +0,0 @@ -config = { - "interfaces": { - "google.cloud.iot.v1.DeviceManager": { - "retry_codes": { - "idempotent": ["DEADLINE_EXCEEDED", "UNAVAILABLE"], - "non_idempotent": [], - "rate_limited_aware": [ - "DEADLINE_EXCEEDED", - "RESOURCE_EXHAUSTED", - "UNAVAILABLE", - ], - }, - "retry_params": { - "default": { - "initial_retry_delay_millis": 100, - "retry_delay_multiplier": 1.3, - "max_retry_delay_millis": 60000, - "initial_rpc_timeout_millis": 20000, - "rpc_timeout_multiplier": 1.0, - "max_rpc_timeout_millis": 20000, - "total_timeout_millis": 120000, - }, - "rate_limited_aware": { - "initial_retry_delay_millis": 1000, - "retry_delay_multiplier": 1.3, - "max_retry_delay_millis": 60000, - "initial_rpc_timeout_millis": 20000, - "rpc_timeout_multiplier": 1.0, - "max_rpc_timeout_millis": 20000, - "total_timeout_millis": 120000, - }, - }, - "methods": { - "DeleteDeviceRegistry": { - "timeout_millis": 60000, - "retry_codes_name": "idempotent", - "retry_params_name": "default", - }, - "DeleteDevice": { - "timeout_millis": 60000, - "retry_codes_name": "idempotent", - "retry_params_name": "default", - }, - "ModifyCloudToDeviceConfig": { - "timeout_millis": 60000, - "retry_codes_name": "rate_limited_aware", - "retry_params_name": "rate_limited_aware", - }, - "SendCommandToDevice": { - "timeout_millis": 60000, - "retry_codes_name": "rate_limited_aware", - "retry_params_name": "rate_limited_aware", - }, - "CreateDeviceRegistry": { - "timeout_millis": 60000, - "retry_codes_name": "non_idempotent", - "retry_params_name": "default", - }, - "GetDeviceRegistry": { - "timeout_millis": 60000, - "retry_codes_name": "idempotent", - "retry_params_name": "default", - }, - "UpdateDeviceRegistry": { - "timeout_millis": 60000, - "retry_codes_name": "non_idempotent", - "retry_params_name": "default", - }, - "ListDeviceRegistries": { - "timeout_millis": 60000, - "retry_codes_name": "idempotent", - "retry_params_name": "default", - }, - "CreateDevice": { - "timeout_millis": 60000, - "retry_codes_name": "non_idempotent", - "retry_params_name": "default", - }, - "GetDevice": { - "timeout_millis": 60000, - "retry_codes_name": "idempotent", - "retry_params_name": "default", - }, - "UpdateDevice": { - "timeout_millis": 60000, - "retry_codes_name": "non_idempotent", - "retry_params_name": "default", - }, - "ListDevices": { - "timeout_millis": 60000, - "retry_codes_name": "idempotent", - "retry_params_name": "default", - }, - "ListDeviceConfigVersions": { - "timeout_millis": 60000, - "retry_codes_name": "idempotent", - "retry_params_name": "default", - }, - "ListDeviceStates": { - "timeout_millis": 60000, - "retry_codes_name": "idempotent", - "retry_params_name": "default", - }, - "SetIamPolicy": { - "timeout_millis": 60000, - "retry_codes_name": "non_idempotent", - "retry_params_name": "default", - }, - "GetIamPolicy": { - "timeout_millis": 60000, - "retry_codes_name": "non_idempotent", - "retry_params_name": "default", - }, - "TestIamPermissions": { - "timeout_millis": 60000, - "retry_codes_name": "non_idempotent", - "retry_params_name": "default", - }, - "BindDeviceToGateway": { - "timeout_millis": 60000, - "retry_codes_name": "non_idempotent", - "retry_params_name": "default", - }, - "UnbindDeviceFromGateway": { - "timeout_millis": 60000, - "retry_codes_name": "non_idempotent", - "retry_params_name": "default", - }, - }, - } - } -} diff --git a/google/cloud/iot_v1/gapic/enums.py b/google/cloud/iot_v1/gapic/enums.py deleted file mode 100644 index cb5d17f8..00000000 --- a/google/cloud/iot_v1/gapic/enums.py +++ /dev/null @@ -1,167 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Wrappers for protocol buffer enum types.""" - -import enum - - -class GatewayAuthMethod(enum.IntEnum): - """ - The gateway authorization/authentication method. This setting determines how - Cloud IoT Core authorizes/authenticate devices to access the gateway. - - Attributes: - GATEWAY_AUTH_METHOD_UNSPECIFIED (int): No authentication/authorization method specified. No devices are allowed to - access the gateway. - ASSOCIATION_ONLY (int): The device is authenticated through the gateway association only. Device - credentials are ignored even if provided. - DEVICE_AUTH_TOKEN_ONLY (int): The device is authenticated through its own credentials. Gateway - association is not checked. - ASSOCIATION_AND_DEVICE_AUTH_TOKEN (int): The device is authenticated through both device credentials and gateway - association. The device must be bound to the gateway and must provide its - own credentials. - """ - - GATEWAY_AUTH_METHOD_UNSPECIFIED = 0 - ASSOCIATION_ONLY = 1 - DEVICE_AUTH_TOKEN_ONLY = 2 - ASSOCIATION_AND_DEVICE_AUTH_TOKEN = 3 - - -class GatewayType(enum.IntEnum): - """ - Gateway type. - - Attributes: - GATEWAY_TYPE_UNSPECIFIED (int): If unspecified, the device is considered a non-gateway device. - GATEWAY (int): The device is a gateway. - NON_GATEWAY (int): The device is not a gateway. - """ - - GATEWAY_TYPE_UNSPECIFIED = 0 - GATEWAY = 1 - NON_GATEWAY = 2 - - -class HttpState(enum.IntEnum): - """ - Indicates whether DeviceService (HTTP) is enabled or disabled for the - registry. See the field description for details. - - Attributes: - HTTP_STATE_UNSPECIFIED (int): No HTTP state specified. If not specified, DeviceService will be - enabled by default. - HTTP_ENABLED (int): Enables DeviceService (HTTP) service for the registry. - HTTP_DISABLED (int): Disables DeviceService (HTTP) service for the registry. - """ - - HTTP_STATE_UNSPECIFIED = 0 - HTTP_ENABLED = 1 - HTTP_DISABLED = 2 - - -class LogLevel(enum.IntEnum): - """ - **Beta Feature** - - The logging verbosity for device activity. Specifies which events should - be written to logs. For example, if the LogLevel is ERROR, only events - that terminate in errors will be logged. LogLevel is inclusive; enabling - INFO logging will also enable ERROR logging. - - Attributes: - LOG_LEVEL_UNSPECIFIED (int): No logging specified. If not specified, logging will be disabled. - NONE (int): Disables logging. - ERROR (int): Error events will be logged. - INFO (int): Informational events will be logged, such as connections and - disconnections. - DEBUG (int): All events will be logged. - """ - - LOG_LEVEL_UNSPECIFIED = 0 - NONE = 10 - ERROR = 20 - INFO = 30 - DEBUG = 40 - - -class MqttState(enum.IntEnum): - """ - Indicates whether an MQTT connection is enabled or disabled. See the field - description for details. - - Attributes: - MQTT_STATE_UNSPECIFIED (int): No MQTT state specified. If not specified, MQTT will be enabled by default. - MQTT_ENABLED (int): Enables a MQTT connection. - MQTT_DISABLED (int): Disables a MQTT connection. - """ - - MQTT_STATE_UNSPECIFIED = 0 - MQTT_ENABLED = 1 - MQTT_DISABLED = 2 - - -class PublicKeyCertificateFormat(enum.IntEnum): - """ - The supported formats for the public key. - - Attributes: - UNSPECIFIED_PUBLIC_KEY_CERTIFICATE_FORMAT (int): The format has not been specified. This is an invalid default value and - must not be used. - X509_CERTIFICATE_PEM (int): An X.509v3 certificate - (`RFC5280 `__), encoded in base64, - and wrapped by ``-----BEGIN CERTIFICATE-----`` and - ``-----END CERTIFICATE-----``. - """ - - UNSPECIFIED_PUBLIC_KEY_CERTIFICATE_FORMAT = 0 - X509_CERTIFICATE_PEM = 1 - - -class PublicKeyFormat(enum.IntEnum): - """ - The supported formats for the public key. - - Attributes: - UNSPECIFIED_PUBLIC_KEY_FORMAT (int): The format has not been specified. This is an invalid default value and - must not be used. - RSA_PEM (int): An RSA public key encoded in base64, and wrapped by - ``-----BEGIN PUBLIC KEY-----`` and ``-----END PUBLIC KEY-----``. This - can be used to verify ``RS256`` signatures in JWT tokens - (`RFC7518 `__). - RSA_X509_PEM (int): As RSA_PEM, but wrapped in an X.509v3 certificate - (`RFC5280 `__), encoded in base64, - and wrapped by ``-----BEGIN CERTIFICATE-----`` and - ``-----END CERTIFICATE-----``. - ES256_PEM (int): Public key for the ECDSA algorithm using P-256 and SHA-256, encoded - in base64, and wrapped by ``-----BEGIN PUBLIC KEY-----`` and - ``-----END PUBLIC KEY-----``. This can be used to verify JWT tokens with - the ``ES256`` algorithm - (`RFC7518 `__). This curve is - defined in `OpenSSL `__ as the ``prime256v1`` - curve. - ES256_X509_PEM (int): As ES256_PEM, but wrapped in an X.509v3 certificate - (`RFC5280 `__), encoded in base64, - and wrapped by ``-----BEGIN CERTIFICATE-----`` and - ``-----END CERTIFICATE-----``. - """ - - UNSPECIFIED_PUBLIC_KEY_FORMAT = 0 - RSA_PEM = 3 - RSA_X509_PEM = 1 - ES256_PEM = 2 - ES256_X509_PEM = 4 diff --git a/google/cloud/iot_v1/gapic/transports/__init__.py b/google/cloud/iot_v1/gapic/transports/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/google/cloud/iot_v1/gapic/transports/device_manager_grpc_transport.py b/google/cloud/iot_v1/gapic/transports/device_manager_grpc_transport.py deleted file mode 100644 index 8deb721d..00000000 --- a/google/cloud/iot_v1/gapic/transports/device_manager_grpc_transport.py +++ /dev/null @@ -1,381 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -import google.api_core.grpc_helpers - -from google.cloud.iot_v1.proto import device_manager_pb2_grpc - - -class DeviceManagerGrpcTransport(object): - """gRPC transport class providing stubs for - google.cloud.iot.v1 DeviceManager API. - - The transport provides access to the raw gRPC stubs, - which can be used to take advantage of advanced - features of gRPC. - """ - - # The scopes needed to make gRPC calls to all of the methods defined - # in this service. - _OAUTH_SCOPES = ( - "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/cloudiot", - ) - - def __init__( - self, channel=None, credentials=None, address="cloudiot.googleapis.com:443" - ): - """Instantiate the transport class. - - Args: - channel (grpc.Channel): A ``Channel`` instance through - which to make calls. This argument is mutually exclusive - with ``credentials``; providing both will raise an exception. - credentials (google.auth.credentials.Credentials): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If none - are specified, the client will attempt to ascertain the - credentials from the environment. - address (str): The address where the service is hosted. - """ - # If both `channel` and `credentials` are specified, raise an - # exception (channels come with credentials baked in already). - if channel is not None and credentials is not None: - raise ValueError( - "The `channel` and `credentials` arguments are mutually " "exclusive.", - ) - - # Create the channel. - if channel is None: - channel = self.create_channel( - address=address, - credentials=credentials, - options={ - "grpc.max_send_message_length": -1, - "grpc.max_receive_message_length": -1, - }.items(), - ) - - self._channel = channel - - # gRPC uses objects called "stubs" that are bound to the - # channel and provide a basic method for each RPC. - self._stubs = { - "device_manager_stub": device_manager_pb2_grpc.DeviceManagerStub(channel), - } - - @classmethod - def create_channel( - cls, address="cloudiot.googleapis.com:443", credentials=None, **kwargs - ): - """Create and return a gRPC channel object. - - Args: - address (str): The host for the channel to use. - credentials (~.Credentials): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - kwargs (dict): Keyword arguments, which are passed to the - channel creation. - - Returns: - grpc.Channel: A gRPC channel object. - """ - return google.api_core.grpc_helpers.create_channel( - address, credentials=credentials, scopes=cls._OAUTH_SCOPES, **kwargs - ) - - @property - def channel(self): - """The gRPC channel used by the transport. - - Returns: - grpc.Channel: A gRPC channel object. - """ - return self._channel - - @property - def delete_device_registry(self): - """Return the gRPC stub for :meth:`DeviceManagerClient.delete_device_registry`. - - Deletes a device registry configuration. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["device_manager_stub"].DeleteDeviceRegistry - - @property - def delete_device(self): - """Return the gRPC stub for :meth:`DeviceManagerClient.delete_device`. - - Deletes a device. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["device_manager_stub"].DeleteDevice - - @property - def modify_cloud_to_device_config(self): - """Return the gRPC stub for :meth:`DeviceManagerClient.modify_cloud_to_device_config`. - - Modifies the configuration for the device, which is eventually sent from - the Cloud IoT Core servers. Returns the modified configuration version and - its metadata. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["device_manager_stub"].ModifyCloudToDeviceConfig - - @property - def send_command_to_device(self): - """Return the gRPC stub for :meth:`DeviceManagerClient.send_command_to_device`. - - Sends a command to the specified device. In order for a device to be - able to receive commands, it must: - - 1) be connected to Cloud IoT Core using the MQTT protocol, and - 2) be subscribed to the group of MQTT topics specified by - /devices/{device-id}/commands/#. This subscription will receive - commands at the top-level topic /devices/{device-id}/commands as well - as commands for subfolders, like - /devices/{device-id}/commands/subfolder. Note that subscribing to - specific subfolders is not supported. If the command could not be - delivered to the device, this method will return an error; in - particular, if the device is not subscribed, this method will return - FAILED_PRECONDITION. Otherwise, this method will return OK. If the - subscription is QoS 1, at least once delivery will be guaranteed; for - QoS 0, no acknowledgment will be expected from the device. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["device_manager_stub"].SendCommandToDevice - - @property - def create_device_registry(self): - """Return the gRPC stub for :meth:`DeviceManagerClient.create_device_registry`. - - Creates a device registry that contains devices. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["device_manager_stub"].CreateDeviceRegistry - - @property - def get_device_registry(self): - """Return the gRPC stub for :meth:`DeviceManagerClient.get_device_registry`. - - Gets a device registry configuration. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["device_manager_stub"].GetDeviceRegistry - - @property - def update_device_registry(self): - """Return the gRPC stub for :meth:`DeviceManagerClient.update_device_registry`. - - Updates a device registry configuration. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["device_manager_stub"].UpdateDeviceRegistry - - @property - def list_device_registries(self): - """Return the gRPC stub for :meth:`DeviceManagerClient.list_device_registries`. - - Lists device registries. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["device_manager_stub"].ListDeviceRegistries - - @property - def create_device(self): - """Return the gRPC stub for :meth:`DeviceManagerClient.create_device`. - - Creates a device in a device registry. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["device_manager_stub"].CreateDevice - - @property - def get_device(self): - """Return the gRPC stub for :meth:`DeviceManagerClient.get_device`. - - Gets details about a device. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["device_manager_stub"].GetDevice - - @property - def update_device(self): - """Return the gRPC stub for :meth:`DeviceManagerClient.update_device`. - - Updates a device. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["device_manager_stub"].UpdateDevice - - @property - def list_devices(self): - """Return the gRPC stub for :meth:`DeviceManagerClient.list_devices`. - - List devices in a device registry. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["device_manager_stub"].ListDevices - - @property - def list_device_config_versions(self): - """Return the gRPC stub for :meth:`DeviceManagerClient.list_device_config_versions`. - - Lists the last few versions of the device configuration in descending - order (i.e.: newest first). - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["device_manager_stub"].ListDeviceConfigVersions - - @property - def list_device_states(self): - """Return the gRPC stub for :meth:`DeviceManagerClient.list_device_states`. - - Lists the last few versions of the device state in descending order (i.e.: - newest first). - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["device_manager_stub"].ListDeviceStates - - @property - def set_iam_policy(self): - """Return the gRPC stub for :meth:`DeviceManagerClient.set_iam_policy`. - - Sets the access control policy on the specified resource. Replaces any - existing policy. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["device_manager_stub"].SetIamPolicy - - @property - def get_iam_policy(self): - """Return the gRPC stub for :meth:`DeviceManagerClient.get_iam_policy`. - - Gets the access control policy for a resource. - Returns an empty policy if the resource exists and does not have a policy - set. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["device_manager_stub"].GetIamPolicy - - @property - def test_iam_permissions(self): - """Return the gRPC stub for :meth:`DeviceManagerClient.test_iam_permissions`. - - Returns permissions that a caller has on the specified resource. If - the resource does not exist, this will return an empty set of - permissions, not a NOT_FOUND error. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["device_manager_stub"].TestIamPermissions - - @property - def bind_device_to_gateway(self): - """Return the gRPC stub for :meth:`DeviceManagerClient.bind_device_to_gateway`. - - Associates the device with the gateway. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["device_manager_stub"].BindDeviceToGateway - - @property - def unbind_device_from_gateway(self): - """Return the gRPC stub for :meth:`DeviceManagerClient.unbind_device_from_gateway`. - - Deletes the association between the device and the gateway. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["device_manager_stub"].UnbindDeviceFromGateway diff --git a/google/cloud/iot_v1/proto/__init__.py b/google/cloud/iot_v1/proto/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/google/cloud/iot_v1/proto/device_manager_pb2.py b/google/cloud/iot_v1/proto/device_manager_pb2.py deleted file mode 100644 index c728deca..00000000 --- a/google/cloud/iot_v1/proto/device_manager_pb2.py +++ /dev/null @@ -1,2425 +0,0 @@ -# -*- coding: utf-8 -*- -# Generated by the protocol buffer compiler. DO NOT EDIT! -# source: google/cloud/iot_v1/proto/device_manager.proto - -from google.protobuf import descriptor as _descriptor -from google.protobuf import message as _message -from google.protobuf import reflection as _reflection -from google.protobuf import symbol_database as _symbol_database - -# @@protoc_insertion_point(imports) - -_sym_db = _symbol_database.Default() - - -from google.api import annotations_pb2 as google_dot_api_dot_annotations__pb2 -from google.api import client_pb2 as google_dot_api_dot_client__pb2 -from google.api import field_behavior_pb2 as google_dot_api_dot_field__behavior__pb2 -from google.api import resource_pb2 as google_dot_api_dot_resource__pb2 -from google.cloud.iot_v1.proto import ( - resources_pb2 as google_dot_cloud_dot_iot__v1_dot_proto_dot_resources__pb2, -) -from google.iam.v1 import iam_policy_pb2 as google_dot_iam_dot_v1_dot_iam__policy__pb2 -from google.iam.v1 import policy_pb2 as google_dot_iam_dot_v1_dot_policy__pb2 -from google.protobuf import empty_pb2 as google_dot_protobuf_dot_empty__pb2 -from google.protobuf import field_mask_pb2 as google_dot_protobuf_dot_field__mask__pb2 -from google.rpc import status_pb2 as google_dot_rpc_dot_status__pb2 - - -DESCRIPTOR = _descriptor.FileDescriptor( - name="google/cloud/iot_v1/proto/device_manager.proto", - package="google.cloud.iot.v1", - syntax="proto3", - serialized_options=b"\n\027com.google.cloud.iot.v1B\022DeviceManagerProtoP\001Z6google.golang.org/genproto/googleapis/cloud/iot/v1;iot\370\001\001", - create_key=_descriptor._internal_create_key, - serialized_pb=b'\n.google/cloud/iot_v1/proto/device_manager.proto\x12\x13google.cloud.iot.v1\x1a\x1cgoogle/api/annotations.proto\x1a\x17google/api/client.proto\x1a\x1fgoogle/api/field_behavior.proto\x1a\x19google/api/resource.proto\x1a)google/cloud/iot_v1/proto/resources.proto\x1a\x1egoogle/iam/v1/iam_policy.proto\x1a\x1agoogle/iam/v1/policy.proto\x1a\x1bgoogle/protobuf/empty.proto\x1a google/protobuf/field_mask.proto\x1a\x17google/rpc/status.proto"\x9b\x01\n\x1b\x43reateDeviceRegistryRequest\x12\x39\n\x06parent\x18\x01 \x01(\tB)\xe0\x41\x02\xfa\x41#\n!locations.googleapis.com/Location\x12\x41\n\x0f\x64\x65vice_registry\x18\x02 \x01(\x0b\x32#.google.cloud.iot.v1.DeviceRegistryB\x03\xe0\x41\x02"R\n\x18GetDeviceRegistryRequest\x12\x36\n\x04name\x18\x01 \x01(\tB(\xe0\x41\x02\xfa\x41"\n cloudiot.googleapis.com/Registry"U\n\x1b\x44\x65leteDeviceRegistryRequest\x12\x36\n\x04name\x18\x01 \x01(\tB(\xe0\x41\x02\xfa\x41"\n cloudiot.googleapis.com/Registry"\x96\x01\n\x1bUpdateDeviceRegistryRequest\x12\x41\n\x0f\x64\x65vice_registry\x18\x01 \x01(\x0b\x32#.google.cloud.iot.v1.DeviceRegistryB\x03\xe0\x41\x02\x12\x34\n\x0bupdate_mask\x18\x02 \x01(\x0b\x32\x1a.google.protobuf.FieldMaskB\x03\xe0\x41\x02"\x7f\n\x1bListDeviceRegistriesRequest\x12\x39\n\x06parent\x18\x01 \x01(\tB)\xe0\x41\x02\xfa\x41#\n!locations.googleapis.com/Location\x12\x11\n\tpage_size\x18\x02 \x01(\x05\x12\x12\n\npage_token\x18\x03 \x01(\t"w\n\x1cListDeviceRegistriesResponse\x12>\n\x11\x64\x65vice_registries\x18\x01 \x03(\x0b\x32#.google.cloud.iot.v1.DeviceRegistry\x12\x17\n\x0fnext_page_token\x18\x02 \x01(\t"\x81\x01\n\x13\x43reateDeviceRequest\x12\x38\n\x06parent\x18\x01 \x01(\tB(\xe0\x41\x02\xfa\x41"\n cloudiot.googleapis.com/Registry\x12\x30\n\x06\x64\x65vice\x18\x02 \x01(\x0b\x32\x1b.google.cloud.iot.v1.DeviceB\x03\xe0\x41\x02"x\n\x10GetDeviceRequest\x12\x34\n\x04name\x18\x01 \x01(\tB&\xe0\x41\x02\xfa\x41 \n\x1e\x63loudiot.googleapis.com/Device\x12.\n\nfield_mask\x18\x02 \x01(\x0b\x32\x1a.google.protobuf.FieldMask"}\n\x13UpdateDeviceRequest\x12\x30\n\x06\x64\x65vice\x18\x02 \x01(\x0b\x32\x1b.google.cloud.iot.v1.DeviceB\x03\xe0\x41\x02\x12\x34\n\x0bupdate_mask\x18\x03 \x01(\x0b\x32\x1a.google.protobuf.FieldMaskB\x03\xe0\x41\x02"K\n\x13\x44\x65leteDeviceRequest\x12\x34\n\x04name\x18\x01 \x01(\tB&\xe0\x41\x02\xfa\x41 \n\x1e\x63loudiot.googleapis.com/Device"\x98\x02\n\x12ListDevicesRequest\x12\x38\n\x06parent\x18\x01 \x01(\tB(\xe0\x41\x02\xfa\x41"\n cloudiot.googleapis.com/Registry\x12\x16\n\x0e\x64\x65vice_num_ids\x18\x02 \x03(\x04\x12\x12\n\ndevice_ids\x18\x03 \x03(\t\x12.\n\nfield_mask\x18\x04 \x01(\x0b\x32\x1a.google.protobuf.FieldMask\x12\x45\n\x14gateway_list_options\x18\x06 \x01(\x0b\x32\'.google.cloud.iot.v1.GatewayListOptions\x12\x11\n\tpage_size\x18\x64 \x01(\x05\x12\x12\n\npage_token\x18\x65 \x01(\t"\x9d\x01\n\x12GatewayListOptions\x12\x38\n\x0cgateway_type\x18\x01 \x01(\x0e\x32 .google.cloud.iot.v1.GatewayTypeH\x00\x12!\n\x17\x61ssociations_gateway_id\x18\x02 \x01(\tH\x00\x12 \n\x16\x61ssociations_device_id\x18\x03 \x01(\tH\x00\x42\x08\n\x06\x66ilter"\\\n\x13ListDevicesResponse\x12,\n\x07\x64\x65vices\x18\x01 \x03(\x0b\x32\x1b.google.cloud.iot.v1.Device\x12\x17\n\x0fnext_page_token\x18\x02 \x01(\t"\x8d\x01\n ModifyCloudToDeviceConfigRequest\x12\x34\n\x04name\x18\x01 \x01(\tB&\xe0\x41\x02\xfa\x41 \n\x1e\x63loudiot.googleapis.com/Device\x12\x19\n\x11version_to_update\x18\x02 \x01(\x03\x12\x18\n\x0b\x62inary_data\x18\x03 \x01(\x0c\x42\x03\xe0\x41\x02"m\n\x1fListDeviceConfigVersionsRequest\x12\x34\n\x04name\x18\x01 \x01(\tB&\xe0\x41\x02\xfa\x41 \n\x1e\x63loudiot.googleapis.com/Device\x12\x14\n\x0cnum_versions\x18\x02 \x01(\x05"]\n ListDeviceConfigVersionsResponse\x12\x39\n\x0e\x64\x65vice_configs\x18\x01 \x03(\x0b\x32!.google.cloud.iot.v1.DeviceConfig"c\n\x17ListDeviceStatesRequest\x12\x34\n\x04name\x18\x01 \x01(\tB&\xe0\x41\x02\xfa\x41 \n\x1e\x63loudiot.googleapis.com/Device\x12\x12\n\nnum_states\x18\x02 \x01(\x05"S\n\x18ListDeviceStatesResponse\x12\x37\n\rdevice_states\x18\x01 \x03(\x0b\x32 .google.cloud.iot.v1.DeviceState"\x7f\n\x1aSendCommandToDeviceRequest\x12\x34\n\x04name\x18\x01 \x01(\tB&\xe0\x41\x02\xfa\x41 \n\x1e\x63loudiot.googleapis.com/Device\x12\x18\n\x0b\x62inary_data\x18\x02 \x01(\x0c\x42\x03\xe0\x41\x02\x12\x11\n\tsubfolder\x18\x03 \x01(\t"\x1d\n\x1bSendCommandToDeviceResponse"\x87\x01\n\x1a\x42indDeviceToGatewayRequest\x12\x38\n\x06parent\x18\x01 \x01(\tB(\xe0\x41\x02\xfa\x41"\n cloudiot.googleapis.com/Registry\x12\x17\n\ngateway_id\x18\x02 \x01(\tB\x03\xe0\x41\x02\x12\x16\n\tdevice_id\x18\x03 \x01(\tB\x03\xe0\x41\x02"\x1d\n\x1b\x42indDeviceToGatewayResponse"\x8b\x01\n\x1eUnbindDeviceFromGatewayRequest\x12\x38\n\x06parent\x18\x01 \x01(\tB(\xe0\x41\x02\xfa\x41"\n cloudiot.googleapis.com/Registry\x12\x17\n\ngateway_id\x18\x02 \x01(\tB\x03\xe0\x41\x02\x12\x16\n\tdevice_id\x18\x03 \x01(\tB\x03\xe0\x41\x02"!\n\x1fUnbindDeviceFromGatewayResponse2\xa6&\n\rDeviceManager\x12\xcf\x01\n\x14\x43reateDeviceRegistry\x12\x30.google.cloud.iot.v1.CreateDeviceRegistryRequest\x1a#.google.cloud.iot.v1.DeviceRegistry"`\x82\xd3\xe4\x93\x02\x41"./v1/{parent=projects/*/locations/*}/registries:\x0f\x64\x65vice_registry\xda\x41\x16parent,device_registry\x12\xa6\x01\n\x11GetDeviceRegistry\x12-.google.cloud.iot.v1.GetDeviceRegistryRequest\x1a#.google.cloud.iot.v1.DeviceRegistry"=\x82\xd3\xe4\x93\x02\x30\x12./v1/{name=projects/*/locations/*/registries/*}\xda\x41\x04name\x12\xe4\x01\n\x14UpdateDeviceRegistry\x12\x30.google.cloud.iot.v1.UpdateDeviceRegistryRequest\x1a#.google.cloud.iot.v1.DeviceRegistry"u\x82\xd3\xe4\x93\x02Q2>/v1/{device_registry.name=projects/*/locations/*/registries/*}:\x0f\x64\x65vice_registry\xda\x41\x1b\x64\x65vice_registry,update_mask\x12\x9f\x01\n\x14\x44\x65leteDeviceRegistry\x12\x30.google.cloud.iot.v1.DeleteDeviceRegistryRequest\x1a\x16.google.protobuf.Empty"=\x82\xd3\xe4\x93\x02\x30*./v1/{name=projects/*/locations/*/registries/*}\xda\x41\x04name\x12\xbc\x01\n\x14ListDeviceRegistries\x12\x30.google.cloud.iot.v1.ListDeviceRegistriesRequest\x1a\x31.google.cloud.iot.v1.ListDeviceRegistriesResponse"?\x82\xd3\xe4\x93\x02\x30\x12./v1/{parent=projects/*/locations/*}/registries\xda\x41\x06parent\x12\xaf\x01\n\x0c\x43reateDevice\x12(.google.cloud.iot.v1.CreateDeviceRequest\x1a\x1b.google.cloud.iot.v1.Device"X\x82\xd3\xe4\x93\x02\x42"8/v1/{parent=projects/*/locations/*/registries/*}/devices:\x06\x64\x65vice\xda\x41\rparent,device\x12\xde\x01\n\tGetDevice\x12%.google.cloud.iot.v1.GetDeviceRequest\x1a\x1b.google.cloud.iot.v1.Device"\x8c\x01\x82\xd3\xe4\x93\x02\x7f\x12\x38/v1/{name=projects/*/locations/*/registries/*/devices/*}ZC\x12\x41/v1/{name=projects/*/locations/*/registries/*/groups/*/devices/*}\xda\x41\x04name\x12\x91\x02\n\x0cUpdateDevice\x12(.google.cloud.iot.v1.UpdateDeviceRequest\x1a\x1b.google.cloud.iot.v1.Device"\xb9\x01\x82\xd3\xe4\x93\x02\x9d\x01\x32?/v1/{device.name=projects/*/locations/*/registries/*/devices/*}:\x06\x64\x65viceZR2H/v1/{device.name=projects/*/locations/*/registries/*/groups/*/devices/*}:\x06\x64\x65vice\xda\x41\x12\x64\x65vice,update_mask\x12\x99\x01\n\x0c\x44\x65leteDevice\x12(.google.cloud.iot.v1.DeleteDeviceRequest\x1a\x16.google.protobuf.Empty"G\x82\xd3\xe4\x93\x02:*8/v1/{name=projects/*/locations/*/registries/*/devices/*}\xda\x41\x04name\x12\xf1\x01\n\x0bListDevices\x12\'.google.cloud.iot.v1.ListDevicesRequest\x1a(.google.cloud.iot.v1.ListDevicesResponse"\x8e\x01\x82\xd3\xe4\x93\x02\x7f\x12\x38/v1/{parent=projects/*/locations/*/registries/*}/devicesZC\x12\x41/v1/{parent=projects/*/locations/*/registries/*/groups/*}/devices\xda\x41\x06parent\x12\xcb\x02\n\x19ModifyCloudToDeviceConfig\x12\x35.google.cloud.iot.v1.ModifyCloudToDeviceConfigRequest\x1a!.google.cloud.iot.v1.DeviceConfig"\xd3\x01\x82\xd3\xe4\x93\x02\xb9\x01"R/v1/{name=projects/*/locations/*/registries/*/devices/*}:modifyCloudToDeviceConfig:\x01*Z`"[/v1/{name=projects/*/locations/*/registries/*/groups/*/devices/*}:modifyCloudToDeviceConfig:\x01*\xda\x41\x10name,binary_data\x12\xb5\x02\n\x18ListDeviceConfigVersions\x12\x34.google.cloud.iot.v1.ListDeviceConfigVersionsRequest\x1a\x35.google.cloud.iot.v1.ListDeviceConfigVersionsResponse"\xab\x01\x82\xd3\xe4\x93\x02\x9d\x01\x12G/v1/{name=projects/*/locations/*/registries/*/devices/*}/configVersionsZR\x12P/v1/{name=projects/*/locations/*/registries/*/groups/*/devices/*}/configVersions\xda\x41\x04name\x12\x8d\x02\n\x10ListDeviceStates\x12,.google.cloud.iot.v1.ListDeviceStatesRequest\x1a-.google.cloud.iot.v1.ListDeviceStatesResponse"\x9b\x01\x82\xd3\xe4\x93\x02\x8d\x01\x12?/v1/{name=projects/*/locations/*/registries/*/devices/*}/statesZJ\x12H/v1/{name=projects/*/locations/*/registries/*/groups/*/devices/*}/states\xda\x41\x04name\x12\xf8\x01\n\x0cSetIamPolicy\x12".google.iam.v1.SetIamPolicyRequest\x1a\x15.google.iam.v1.Policy"\xac\x01\x82\xd3\xe4\x93\x02\x93\x01"?/v1/{resource=projects/*/locations/*/registries/*}:setIamPolicy:\x01*ZM"H/v1/{resource=projects/*/locations/*/registries/*/groups/*}:setIamPolicy:\x01*\xda\x41\x0fresource,policy\x12\xf1\x01\n\x0cGetIamPolicy\x12".google.iam.v1.GetIamPolicyRequest\x1a\x15.google.iam.v1.Policy"\xa5\x01\x82\xd3\xe4\x93\x02\x93\x01"?/v1/{resource=projects/*/locations/*/registries/*}:getIamPolicy:\x01*ZM"H/v1/{resource=projects/*/locations/*/registries/*/groups/*}:getIamPolicy:\x01*\xda\x41\x08resource\x12\xa9\x02\n\x12TestIamPermissions\x12(.google.iam.v1.TestIamPermissionsRequest\x1a).google.iam.v1.TestIamPermissionsResponse"\xbd\x01\x82\xd3\xe4\x93\x02\x9f\x01"E/v1/{resource=projects/*/locations/*/registries/*}:testIamPermissions:\x01*ZS"N/v1/{resource=projects/*/locations/*/registries/*/groups/*}:testIamPermissions:\x01*\xda\x41\x14resource,permissions\x12\xdf\x02\n\x13SendCommandToDevice\x12/.google.cloud.iot.v1.SendCommandToDeviceRequest\x1a\x30.google.cloud.iot.v1.SendCommandToDeviceResponse"\xe4\x01\x82\xd3\xe4\x93\x02\xad\x01"L/v1/{name=projects/*/locations/*/registries/*/devices/*}:sendCommandToDevice:\x01*ZZ"U/v1/{name=projects/*/locations/*/registries/*/groups/*/devices/*}:sendCommandToDevice:\x01*\xda\x41\x10name,binary_data\xda\x41\x1aname,binary_data,subfolder\x12\xbd\x02\n\x13\x42indDeviceToGateway\x12/.google.cloud.iot.v1.BindDeviceToGatewayRequest\x1a\x30.google.cloud.iot.v1.BindDeviceToGatewayResponse"\xc2\x01\x82\xd3\xe4\x93\x02\x9d\x01"D/v1/{parent=projects/*/locations/*/registries/*}:bindDeviceToGateway:\x01*ZR"M/v1/{parent=projects/*/locations/*/registries/*/groups/*}:bindDeviceToGateway:\x01*\xda\x41\x1bparent,gateway_id,device_id\x12\xd1\x02\n\x17UnbindDeviceFromGateway\x12\x33.google.cloud.iot.v1.UnbindDeviceFromGatewayRequest\x1a\x34.google.cloud.iot.v1.UnbindDeviceFromGatewayResponse"\xca\x01\x82\xd3\xe4\x93\x02\xa5\x01"H/v1/{parent=projects/*/locations/*/registries/*}:unbindDeviceFromGateway:\x01*ZV"Q/v1/{parent=projects/*/locations/*/registries/*/groups/*}:unbindDeviceFromGateway:\x01*\xda\x41\x1bparent,gateway_id,device_id\x1at\xca\x41\x17\x63loudiot.googleapis.com\xd2\x41Whttps://www.googleapis.com/auth/cloud-platform,https://www.googleapis.com/auth/cloudiotBj\n\x17\x63om.google.cloud.iot.v1B\x12\x44\x65viceManagerProtoP\x01Z6google.golang.org/genproto/googleapis/cloud/iot/v1;iot\xf8\x01\x01\x62\x06proto3', - dependencies=[ - google_dot_api_dot_annotations__pb2.DESCRIPTOR, - google_dot_api_dot_client__pb2.DESCRIPTOR, - google_dot_api_dot_field__behavior__pb2.DESCRIPTOR, - google_dot_api_dot_resource__pb2.DESCRIPTOR, - google_dot_cloud_dot_iot__v1_dot_proto_dot_resources__pb2.DESCRIPTOR, - google_dot_iam_dot_v1_dot_iam__policy__pb2.DESCRIPTOR, - google_dot_iam_dot_v1_dot_policy__pb2.DESCRIPTOR, - google_dot_protobuf_dot_empty__pb2.DESCRIPTOR, - google_dot_protobuf_dot_field__mask__pb2.DESCRIPTOR, - google_dot_rpc_dot_status__pb2.DESCRIPTOR, - ], -) - - -_CREATEDEVICEREGISTRYREQUEST = _descriptor.Descriptor( - name="CreateDeviceRegistryRequest", - full_name="google.cloud.iot.v1.CreateDeviceRegistryRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="parent", - full_name="google.cloud.iot.v1.CreateDeviceRegistryRequest.parent", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002\372A#\n!locations.googleapis.com/Location", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="device_registry", - full_name="google.cloud.iot.v1.CreateDeviceRegistryRequest.device_registry", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=378, - serialized_end=533, -) - - -_GETDEVICEREGISTRYREQUEST = _descriptor.Descriptor( - name="GetDeviceRegistryRequest", - full_name="google.cloud.iot.v1.GetDeviceRegistryRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.iot.v1.GetDeviceRegistryRequest.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b'\340A\002\372A"\n cloudiot.googleapis.com/Registry', - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=535, - serialized_end=617, -) - - -_DELETEDEVICEREGISTRYREQUEST = _descriptor.Descriptor( - name="DeleteDeviceRegistryRequest", - full_name="google.cloud.iot.v1.DeleteDeviceRegistryRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.iot.v1.DeleteDeviceRegistryRequest.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b'\340A\002\372A"\n cloudiot.googleapis.com/Registry', - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=619, - serialized_end=704, -) - - -_UPDATEDEVICEREGISTRYREQUEST = _descriptor.Descriptor( - name="UpdateDeviceRegistryRequest", - full_name="google.cloud.iot.v1.UpdateDeviceRegistryRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="device_registry", - full_name="google.cloud.iot.v1.UpdateDeviceRegistryRequest.device_registry", - index=0, - number=1, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="update_mask", - full_name="google.cloud.iot.v1.UpdateDeviceRegistryRequest.update_mask", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=707, - serialized_end=857, -) - - -_LISTDEVICEREGISTRIESREQUEST = _descriptor.Descriptor( - name="ListDeviceRegistriesRequest", - full_name="google.cloud.iot.v1.ListDeviceRegistriesRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="parent", - full_name="google.cloud.iot.v1.ListDeviceRegistriesRequest.parent", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002\372A#\n!locations.googleapis.com/Location", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="page_size", - full_name="google.cloud.iot.v1.ListDeviceRegistriesRequest.page_size", - index=1, - number=2, - type=5, - cpp_type=1, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="page_token", - full_name="google.cloud.iot.v1.ListDeviceRegistriesRequest.page_token", - index=2, - number=3, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=859, - serialized_end=986, -) - - -_LISTDEVICEREGISTRIESRESPONSE = _descriptor.Descriptor( - name="ListDeviceRegistriesResponse", - full_name="google.cloud.iot.v1.ListDeviceRegistriesResponse", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="device_registries", - full_name="google.cloud.iot.v1.ListDeviceRegistriesResponse.device_registries", - index=0, - number=1, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="next_page_token", - full_name="google.cloud.iot.v1.ListDeviceRegistriesResponse.next_page_token", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=988, - serialized_end=1107, -) - - -_CREATEDEVICEREQUEST = _descriptor.Descriptor( - name="CreateDeviceRequest", - full_name="google.cloud.iot.v1.CreateDeviceRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="parent", - full_name="google.cloud.iot.v1.CreateDeviceRequest.parent", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b'\340A\002\372A"\n cloudiot.googleapis.com/Registry', - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="device", - full_name="google.cloud.iot.v1.CreateDeviceRequest.device", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1110, - serialized_end=1239, -) - - -_GETDEVICEREQUEST = _descriptor.Descriptor( - name="GetDeviceRequest", - full_name="google.cloud.iot.v1.GetDeviceRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.iot.v1.GetDeviceRequest.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002\372A \n\036cloudiot.googleapis.com/Device", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="field_mask", - full_name="google.cloud.iot.v1.GetDeviceRequest.field_mask", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1241, - serialized_end=1361, -) - - -_UPDATEDEVICEREQUEST = _descriptor.Descriptor( - name="UpdateDeviceRequest", - full_name="google.cloud.iot.v1.UpdateDeviceRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="device", - full_name="google.cloud.iot.v1.UpdateDeviceRequest.device", - index=0, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="update_mask", - full_name="google.cloud.iot.v1.UpdateDeviceRequest.update_mask", - index=1, - number=3, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1363, - serialized_end=1488, -) - - -_DELETEDEVICEREQUEST = _descriptor.Descriptor( - name="DeleteDeviceRequest", - full_name="google.cloud.iot.v1.DeleteDeviceRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.iot.v1.DeleteDeviceRequest.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002\372A \n\036cloudiot.googleapis.com/Device", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1490, - serialized_end=1565, -) - - -_LISTDEVICESREQUEST = _descriptor.Descriptor( - name="ListDevicesRequest", - full_name="google.cloud.iot.v1.ListDevicesRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="parent", - full_name="google.cloud.iot.v1.ListDevicesRequest.parent", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b'\340A\002\372A"\n cloudiot.googleapis.com/Registry', - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="device_num_ids", - full_name="google.cloud.iot.v1.ListDevicesRequest.device_num_ids", - index=1, - number=2, - type=4, - cpp_type=4, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="device_ids", - full_name="google.cloud.iot.v1.ListDevicesRequest.device_ids", - index=2, - number=3, - type=9, - cpp_type=9, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="field_mask", - full_name="google.cloud.iot.v1.ListDevicesRequest.field_mask", - index=3, - number=4, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="gateway_list_options", - full_name="google.cloud.iot.v1.ListDevicesRequest.gateway_list_options", - index=4, - number=6, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="page_size", - full_name="google.cloud.iot.v1.ListDevicesRequest.page_size", - index=5, - number=100, - type=5, - cpp_type=1, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="page_token", - full_name="google.cloud.iot.v1.ListDevicesRequest.page_token", - index=6, - number=101, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1568, - serialized_end=1848, -) - - -_GATEWAYLISTOPTIONS = _descriptor.Descriptor( - name="GatewayListOptions", - full_name="google.cloud.iot.v1.GatewayListOptions", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="gateway_type", - full_name="google.cloud.iot.v1.GatewayListOptions.gateway_type", - index=0, - number=1, - type=14, - cpp_type=8, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="associations_gateway_id", - full_name="google.cloud.iot.v1.GatewayListOptions.associations_gateway_id", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="associations_device_id", - full_name="google.cloud.iot.v1.GatewayListOptions.associations_device_id", - index=2, - number=3, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[ - _descriptor.OneofDescriptor( - name="filter", - full_name="google.cloud.iot.v1.GatewayListOptions.filter", - index=0, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[], - ), - ], - serialized_start=1851, - serialized_end=2008, -) - - -_LISTDEVICESRESPONSE = _descriptor.Descriptor( - name="ListDevicesResponse", - full_name="google.cloud.iot.v1.ListDevicesResponse", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="devices", - full_name="google.cloud.iot.v1.ListDevicesResponse.devices", - index=0, - number=1, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="next_page_token", - full_name="google.cloud.iot.v1.ListDevicesResponse.next_page_token", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=2010, - serialized_end=2102, -) - - -_MODIFYCLOUDTODEVICECONFIGREQUEST = _descriptor.Descriptor( - name="ModifyCloudToDeviceConfigRequest", - full_name="google.cloud.iot.v1.ModifyCloudToDeviceConfigRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.iot.v1.ModifyCloudToDeviceConfigRequest.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002\372A \n\036cloudiot.googleapis.com/Device", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="version_to_update", - full_name="google.cloud.iot.v1.ModifyCloudToDeviceConfigRequest.version_to_update", - index=1, - number=2, - type=3, - cpp_type=2, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="binary_data", - full_name="google.cloud.iot.v1.ModifyCloudToDeviceConfigRequest.binary_data", - index=2, - number=3, - type=12, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"", - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=2105, - serialized_end=2246, -) - - -_LISTDEVICECONFIGVERSIONSREQUEST = _descriptor.Descriptor( - name="ListDeviceConfigVersionsRequest", - full_name="google.cloud.iot.v1.ListDeviceConfigVersionsRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.iot.v1.ListDeviceConfigVersionsRequest.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002\372A \n\036cloudiot.googleapis.com/Device", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="num_versions", - full_name="google.cloud.iot.v1.ListDeviceConfigVersionsRequest.num_versions", - index=1, - number=2, - type=5, - cpp_type=1, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=2248, - serialized_end=2357, -) - - -_LISTDEVICECONFIGVERSIONSRESPONSE = _descriptor.Descriptor( - name="ListDeviceConfigVersionsResponse", - full_name="google.cloud.iot.v1.ListDeviceConfigVersionsResponse", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="device_configs", - full_name="google.cloud.iot.v1.ListDeviceConfigVersionsResponse.device_configs", - index=0, - number=1, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=2359, - serialized_end=2452, -) - - -_LISTDEVICESTATESREQUEST = _descriptor.Descriptor( - name="ListDeviceStatesRequest", - full_name="google.cloud.iot.v1.ListDeviceStatesRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.iot.v1.ListDeviceStatesRequest.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002\372A \n\036cloudiot.googleapis.com/Device", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="num_states", - full_name="google.cloud.iot.v1.ListDeviceStatesRequest.num_states", - index=1, - number=2, - type=5, - cpp_type=1, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=2454, - serialized_end=2553, -) - - -_LISTDEVICESTATESRESPONSE = _descriptor.Descriptor( - name="ListDeviceStatesResponse", - full_name="google.cloud.iot.v1.ListDeviceStatesResponse", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="device_states", - full_name="google.cloud.iot.v1.ListDeviceStatesResponse.device_states", - index=0, - number=1, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=2555, - serialized_end=2638, -) - - -_SENDCOMMANDTODEVICEREQUEST = _descriptor.Descriptor( - name="SendCommandToDeviceRequest", - full_name="google.cloud.iot.v1.SendCommandToDeviceRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.iot.v1.SendCommandToDeviceRequest.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002\372A \n\036cloudiot.googleapis.com/Device", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="binary_data", - full_name="google.cloud.iot.v1.SendCommandToDeviceRequest.binary_data", - index=1, - number=2, - type=12, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"", - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="subfolder", - full_name="google.cloud.iot.v1.SendCommandToDeviceRequest.subfolder", - index=2, - number=3, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=2640, - serialized_end=2767, -) - - -_SENDCOMMANDTODEVICERESPONSE = _descriptor.Descriptor( - name="SendCommandToDeviceResponse", - full_name="google.cloud.iot.v1.SendCommandToDeviceResponse", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=2769, - serialized_end=2798, -) - - -_BINDDEVICETOGATEWAYREQUEST = _descriptor.Descriptor( - name="BindDeviceToGatewayRequest", - full_name="google.cloud.iot.v1.BindDeviceToGatewayRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="parent", - full_name="google.cloud.iot.v1.BindDeviceToGatewayRequest.parent", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b'\340A\002\372A"\n cloudiot.googleapis.com/Registry', - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="gateway_id", - full_name="google.cloud.iot.v1.BindDeviceToGatewayRequest.gateway_id", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="device_id", - full_name="google.cloud.iot.v1.BindDeviceToGatewayRequest.device_id", - index=2, - number=3, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=2801, - serialized_end=2936, -) - - -_BINDDEVICETOGATEWAYRESPONSE = _descriptor.Descriptor( - name="BindDeviceToGatewayResponse", - full_name="google.cloud.iot.v1.BindDeviceToGatewayResponse", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=2938, - serialized_end=2967, -) - - -_UNBINDDEVICEFROMGATEWAYREQUEST = _descriptor.Descriptor( - name="UnbindDeviceFromGatewayRequest", - full_name="google.cloud.iot.v1.UnbindDeviceFromGatewayRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="parent", - full_name="google.cloud.iot.v1.UnbindDeviceFromGatewayRequest.parent", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b'\340A\002\372A"\n cloudiot.googleapis.com/Registry', - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="gateway_id", - full_name="google.cloud.iot.v1.UnbindDeviceFromGatewayRequest.gateway_id", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="device_id", - full_name="google.cloud.iot.v1.UnbindDeviceFromGatewayRequest.device_id", - index=2, - number=3, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=2970, - serialized_end=3109, -) - - -_UNBINDDEVICEFROMGATEWAYRESPONSE = _descriptor.Descriptor( - name="UnbindDeviceFromGatewayResponse", - full_name="google.cloud.iot.v1.UnbindDeviceFromGatewayResponse", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=3111, - serialized_end=3144, -) - -_CREATEDEVICEREGISTRYREQUEST.fields_by_name[ - "device_registry" -].message_type = ( - google_dot_cloud_dot_iot__v1_dot_proto_dot_resources__pb2._DEVICEREGISTRY -) -_UPDATEDEVICEREGISTRYREQUEST.fields_by_name[ - "device_registry" -].message_type = ( - google_dot_cloud_dot_iot__v1_dot_proto_dot_resources__pb2._DEVICEREGISTRY -) -_UPDATEDEVICEREGISTRYREQUEST.fields_by_name[ - "update_mask" -].message_type = google_dot_protobuf_dot_field__mask__pb2._FIELDMASK -_LISTDEVICEREGISTRIESRESPONSE.fields_by_name[ - "device_registries" -].message_type = ( - google_dot_cloud_dot_iot__v1_dot_proto_dot_resources__pb2._DEVICEREGISTRY -) -_CREATEDEVICEREQUEST.fields_by_name[ - "device" -].message_type = google_dot_cloud_dot_iot__v1_dot_proto_dot_resources__pb2._DEVICE -_GETDEVICEREQUEST.fields_by_name[ - "field_mask" -].message_type = google_dot_protobuf_dot_field__mask__pb2._FIELDMASK -_UPDATEDEVICEREQUEST.fields_by_name[ - "device" -].message_type = google_dot_cloud_dot_iot__v1_dot_proto_dot_resources__pb2._DEVICE -_UPDATEDEVICEREQUEST.fields_by_name[ - "update_mask" -].message_type = google_dot_protobuf_dot_field__mask__pb2._FIELDMASK -_LISTDEVICESREQUEST.fields_by_name[ - "field_mask" -].message_type = google_dot_protobuf_dot_field__mask__pb2._FIELDMASK -_LISTDEVICESREQUEST.fields_by_name[ - "gateway_list_options" -].message_type = _GATEWAYLISTOPTIONS -_GATEWAYLISTOPTIONS.fields_by_name[ - "gateway_type" -].enum_type = google_dot_cloud_dot_iot__v1_dot_proto_dot_resources__pb2._GATEWAYTYPE -_GATEWAYLISTOPTIONS.oneofs_by_name["filter"].fields.append( - _GATEWAYLISTOPTIONS.fields_by_name["gateway_type"] -) -_GATEWAYLISTOPTIONS.fields_by_name[ - "gateway_type" -].containing_oneof = _GATEWAYLISTOPTIONS.oneofs_by_name["filter"] -_GATEWAYLISTOPTIONS.oneofs_by_name["filter"].fields.append( - _GATEWAYLISTOPTIONS.fields_by_name["associations_gateway_id"] -) -_GATEWAYLISTOPTIONS.fields_by_name[ - "associations_gateway_id" -].containing_oneof = _GATEWAYLISTOPTIONS.oneofs_by_name["filter"] -_GATEWAYLISTOPTIONS.oneofs_by_name["filter"].fields.append( - _GATEWAYLISTOPTIONS.fields_by_name["associations_device_id"] -) -_GATEWAYLISTOPTIONS.fields_by_name[ - "associations_device_id" -].containing_oneof = _GATEWAYLISTOPTIONS.oneofs_by_name["filter"] -_LISTDEVICESRESPONSE.fields_by_name[ - "devices" -].message_type = google_dot_cloud_dot_iot__v1_dot_proto_dot_resources__pb2._DEVICE -_LISTDEVICECONFIGVERSIONSRESPONSE.fields_by_name[ - "device_configs" -].message_type = google_dot_cloud_dot_iot__v1_dot_proto_dot_resources__pb2._DEVICECONFIG -_LISTDEVICESTATESRESPONSE.fields_by_name[ - "device_states" -].message_type = google_dot_cloud_dot_iot__v1_dot_proto_dot_resources__pb2._DEVICESTATE -DESCRIPTOR.message_types_by_name[ - "CreateDeviceRegistryRequest" -] = _CREATEDEVICEREGISTRYREQUEST -DESCRIPTOR.message_types_by_name["GetDeviceRegistryRequest"] = _GETDEVICEREGISTRYREQUEST -DESCRIPTOR.message_types_by_name[ - "DeleteDeviceRegistryRequest" -] = _DELETEDEVICEREGISTRYREQUEST -DESCRIPTOR.message_types_by_name[ - "UpdateDeviceRegistryRequest" -] = _UPDATEDEVICEREGISTRYREQUEST -DESCRIPTOR.message_types_by_name[ - "ListDeviceRegistriesRequest" -] = _LISTDEVICEREGISTRIESREQUEST -DESCRIPTOR.message_types_by_name[ - "ListDeviceRegistriesResponse" -] = _LISTDEVICEREGISTRIESRESPONSE -DESCRIPTOR.message_types_by_name["CreateDeviceRequest"] = _CREATEDEVICEREQUEST -DESCRIPTOR.message_types_by_name["GetDeviceRequest"] = _GETDEVICEREQUEST -DESCRIPTOR.message_types_by_name["UpdateDeviceRequest"] = _UPDATEDEVICEREQUEST -DESCRIPTOR.message_types_by_name["DeleteDeviceRequest"] = _DELETEDEVICEREQUEST -DESCRIPTOR.message_types_by_name["ListDevicesRequest"] = _LISTDEVICESREQUEST -DESCRIPTOR.message_types_by_name["GatewayListOptions"] = _GATEWAYLISTOPTIONS -DESCRIPTOR.message_types_by_name["ListDevicesResponse"] = _LISTDEVICESRESPONSE -DESCRIPTOR.message_types_by_name[ - "ModifyCloudToDeviceConfigRequest" -] = _MODIFYCLOUDTODEVICECONFIGREQUEST -DESCRIPTOR.message_types_by_name[ - "ListDeviceConfigVersionsRequest" -] = _LISTDEVICECONFIGVERSIONSREQUEST -DESCRIPTOR.message_types_by_name[ - "ListDeviceConfigVersionsResponse" -] = _LISTDEVICECONFIGVERSIONSRESPONSE -DESCRIPTOR.message_types_by_name["ListDeviceStatesRequest"] = _LISTDEVICESTATESREQUEST -DESCRIPTOR.message_types_by_name["ListDeviceStatesResponse"] = _LISTDEVICESTATESRESPONSE -DESCRIPTOR.message_types_by_name[ - "SendCommandToDeviceRequest" -] = _SENDCOMMANDTODEVICEREQUEST -DESCRIPTOR.message_types_by_name[ - "SendCommandToDeviceResponse" -] = _SENDCOMMANDTODEVICERESPONSE -DESCRIPTOR.message_types_by_name[ - "BindDeviceToGatewayRequest" -] = _BINDDEVICETOGATEWAYREQUEST -DESCRIPTOR.message_types_by_name[ - "BindDeviceToGatewayResponse" -] = _BINDDEVICETOGATEWAYRESPONSE -DESCRIPTOR.message_types_by_name[ - "UnbindDeviceFromGatewayRequest" -] = _UNBINDDEVICEFROMGATEWAYREQUEST -DESCRIPTOR.message_types_by_name[ - "UnbindDeviceFromGatewayResponse" -] = _UNBINDDEVICEFROMGATEWAYRESPONSE -_sym_db.RegisterFileDescriptor(DESCRIPTOR) - -CreateDeviceRegistryRequest = _reflection.GeneratedProtocolMessageType( - "CreateDeviceRegistryRequest", - (_message.Message,), - { - "DESCRIPTOR": _CREATEDEVICEREGISTRYREQUEST, - "__module__": "google.cloud.iot_v1.proto.device_manager_pb2", - "__doc__": """Request for ``CreateDeviceRegistry``. - - Attributes: - parent: - Required. The project and cloud region where this device - registry must be created. For example, ``projects/example- - project/locations/us-central1``. - device_registry: - Required. The device registry. The field ``name`` must be - empty. The server will generate that field from the device - registry ``id`` provided and the ``parent`` field. - """, - # @@protoc_insertion_point(class_scope:google.cloud.iot.v1.CreateDeviceRegistryRequest) - }, -) -_sym_db.RegisterMessage(CreateDeviceRegistryRequest) - -GetDeviceRegistryRequest = _reflection.GeneratedProtocolMessageType( - "GetDeviceRegistryRequest", - (_message.Message,), - { - "DESCRIPTOR": _GETDEVICEREGISTRYREQUEST, - "__module__": "google.cloud.iot_v1.proto.device_manager_pb2", - "__doc__": """Request for ``GetDeviceRegistry``. - - Attributes: - name: - Required. The name of the device registry. For example, - ``projects/example-project/locations/us- - central1/registries/my-registry``. - """, - # @@protoc_insertion_point(class_scope:google.cloud.iot.v1.GetDeviceRegistryRequest) - }, -) -_sym_db.RegisterMessage(GetDeviceRegistryRequest) - -DeleteDeviceRegistryRequest = _reflection.GeneratedProtocolMessageType( - "DeleteDeviceRegistryRequest", - (_message.Message,), - { - "DESCRIPTOR": _DELETEDEVICEREGISTRYREQUEST, - "__module__": "google.cloud.iot_v1.proto.device_manager_pb2", - "__doc__": """Request for ``DeleteDeviceRegistry``. - - Attributes: - name: - Required. The name of the device registry. For example, - ``projects/example-project/locations/us- - central1/registries/my-registry``. - """, - # @@protoc_insertion_point(class_scope:google.cloud.iot.v1.DeleteDeviceRegistryRequest) - }, -) -_sym_db.RegisterMessage(DeleteDeviceRegistryRequest) - -UpdateDeviceRegistryRequest = _reflection.GeneratedProtocolMessageType( - "UpdateDeviceRegistryRequest", - (_message.Message,), - { - "DESCRIPTOR": _UPDATEDEVICEREGISTRYREQUEST, - "__module__": "google.cloud.iot_v1.proto.device_manager_pb2", - "__doc__": """Request for ``UpdateDeviceRegistry``. - - Attributes: - device_registry: - Required. The new values for the device registry. The ``id`` - field must be empty, and the ``name`` field must indicate the - path of the resource. For example, ``projects/example- - project/locations/us-central1/registries/my-registry``. - update_mask: - Required. Only updates the ``device_registry`` fields - indicated by this mask. The field mask must not be empty, and - it must not contain fields that are immutable or only set by - the server. Mutable top-level fields: - ``event_notification_config``, ``http_config``, - ``mqtt_config``, and ``state_notification_config``. - """, - # @@protoc_insertion_point(class_scope:google.cloud.iot.v1.UpdateDeviceRegistryRequest) - }, -) -_sym_db.RegisterMessage(UpdateDeviceRegistryRequest) - -ListDeviceRegistriesRequest = _reflection.GeneratedProtocolMessageType( - "ListDeviceRegistriesRequest", - (_message.Message,), - { - "DESCRIPTOR": _LISTDEVICEREGISTRIESREQUEST, - "__module__": "google.cloud.iot_v1.proto.device_manager_pb2", - "__doc__": """Request for ``ListDeviceRegistries``. - - Attributes: - parent: - Required. The project and cloud region path. For example, - ``projects/example-project/locations/us-central1``. - page_size: - The maximum number of registries to return in the response. If - this value is zero, the service will select a default size. A - call may return fewer objects than requested. A non-empty - ``next_page_token`` in the response indicates that more data - is available. - page_token: - The value returned by the last - ``ListDeviceRegistriesResponse``; indicates that this is a - continuation of a prior ``ListDeviceRegistries`` call and the - system should return the next page of data. - """, - # @@protoc_insertion_point(class_scope:google.cloud.iot.v1.ListDeviceRegistriesRequest) - }, -) -_sym_db.RegisterMessage(ListDeviceRegistriesRequest) - -ListDeviceRegistriesResponse = _reflection.GeneratedProtocolMessageType( - "ListDeviceRegistriesResponse", - (_message.Message,), - { - "DESCRIPTOR": _LISTDEVICEREGISTRIESRESPONSE, - "__module__": "google.cloud.iot_v1.proto.device_manager_pb2", - "__doc__": """Response for ``ListDeviceRegistries``. - - Attributes: - device_registries: - The registries that matched the query. - next_page_token: - If not empty, indicates that there may be more registries that - match the request; this value should be passed in a new - ``ListDeviceRegistriesRequest``. - """, - # @@protoc_insertion_point(class_scope:google.cloud.iot.v1.ListDeviceRegistriesResponse) - }, -) -_sym_db.RegisterMessage(ListDeviceRegistriesResponse) - -CreateDeviceRequest = _reflection.GeneratedProtocolMessageType( - "CreateDeviceRequest", - (_message.Message,), - { - "DESCRIPTOR": _CREATEDEVICEREQUEST, - "__module__": "google.cloud.iot_v1.proto.device_manager_pb2", - "__doc__": """Request for ``CreateDevice``. - - Attributes: - parent: - Required. The name of the device registry where this device - should be created. For example, ``projects/example- - project/locations/us-central1/registries/my-registry``. - device: - Required. The device registration details. The field ``name`` - must be empty. The server generates ``name`` from the device - registry ``id`` and the ``parent`` field. - """, - # @@protoc_insertion_point(class_scope:google.cloud.iot.v1.CreateDeviceRequest) - }, -) -_sym_db.RegisterMessage(CreateDeviceRequest) - -GetDeviceRequest = _reflection.GeneratedProtocolMessageType( - "GetDeviceRequest", - (_message.Message,), - { - "DESCRIPTOR": _GETDEVICEREQUEST, - "__module__": "google.cloud.iot_v1.proto.device_manager_pb2", - "__doc__": """Request for ``GetDevice``. - - Attributes: - name: - Required. The name of the device. For example, - ``projects/p0/locations/us- - central1/registries/registry0/devices/device0`` or - ``projects/p0/locations/us- - central1/registries/registry0/devices/{num_id}``. - field_mask: - The fields of the ``Device`` resource to be returned in the - response. If the field mask is unset or empty, all fields are - returned. - """, - # @@protoc_insertion_point(class_scope:google.cloud.iot.v1.GetDeviceRequest) - }, -) -_sym_db.RegisterMessage(GetDeviceRequest) - -UpdateDeviceRequest = _reflection.GeneratedProtocolMessageType( - "UpdateDeviceRequest", - (_message.Message,), - { - "DESCRIPTOR": _UPDATEDEVICEREQUEST, - "__module__": "google.cloud.iot_v1.proto.device_manager_pb2", - "__doc__": """Request for ``UpdateDevice``. - - Attributes: - device: - Required. The new values for the device. The ``id`` and - ``num_id`` fields must be empty, and the field ``name`` must - specify the name path. For example, - ``projects/p0/locations/us- - central1/registries/registry0/devices/device0``\ or - ``projects/p0/locations/us- - central1/registries/registry0/devices/{num_id}``. - update_mask: - Required. Only updates the ``device`` fields indicated by this - mask. The field mask must not be empty, and it must not - contain fields that are immutable or only set by the server. - Mutable top-level fields: ``credentials``, ``blocked``, and - ``metadata`` - """, - # @@protoc_insertion_point(class_scope:google.cloud.iot.v1.UpdateDeviceRequest) - }, -) -_sym_db.RegisterMessage(UpdateDeviceRequest) - -DeleteDeviceRequest = _reflection.GeneratedProtocolMessageType( - "DeleteDeviceRequest", - (_message.Message,), - { - "DESCRIPTOR": _DELETEDEVICEREQUEST, - "__module__": "google.cloud.iot_v1.proto.device_manager_pb2", - "__doc__": """Request for ``DeleteDevice``. - - Attributes: - name: - Required. The name of the device. For example, - ``projects/p0/locations/us- - central1/registries/registry0/devices/device0`` or - ``projects/p0/locations/us- - central1/registries/registry0/devices/{num_id}``. - """, - # @@protoc_insertion_point(class_scope:google.cloud.iot.v1.DeleteDeviceRequest) - }, -) -_sym_db.RegisterMessage(DeleteDeviceRequest) - -ListDevicesRequest = _reflection.GeneratedProtocolMessageType( - "ListDevicesRequest", - (_message.Message,), - { - "DESCRIPTOR": _LISTDEVICESREQUEST, - "__module__": "google.cloud.iot_v1.proto.device_manager_pb2", - "__doc__": """Request for ``ListDevices``. - - Attributes: - parent: - Required. The device registry path. Required. For example, - ``projects/my-project/locations/us-central1/registries/my- - registry``. - device_num_ids: - A list of device numeric IDs. If empty, this field is ignored. - Maximum IDs: 10,000. - device_ids: - A list of device string IDs. For example, ``['device0', - 'device12']``. If empty, this field is ignored. Maximum IDs: - 10,000 - field_mask: - The fields of the ``Device`` resource to be returned in the - response. The fields ``id`` and ``num_id`` are always - returned, along with any other fields specified. - gateway_list_options: - Options related to gateways. - page_size: - The maximum number of devices to return in the response. If - this value is zero, the service will select a default size. A - call may return fewer objects than requested. A non-empty - ``next_page_token`` in the response indicates that more data - is available. - page_token: - The value returned by the last ``ListDevicesResponse``; - indicates that this is a continuation of a prior - ``ListDevices`` call and the system should return the next - page of data. - """, - # @@protoc_insertion_point(class_scope:google.cloud.iot.v1.ListDevicesRequest) - }, -) -_sym_db.RegisterMessage(ListDevicesRequest) - -GatewayListOptions = _reflection.GeneratedProtocolMessageType( - "GatewayListOptions", - (_message.Message,), - { - "DESCRIPTOR": _GATEWAYLISTOPTIONS, - "__module__": "google.cloud.iot_v1.proto.device_manager_pb2", - "__doc__": """Options for limiting the list based on gateway type and associations. - - Attributes: - filter: - If not set, all devices and gateways are returned. If set, the - list is filtered based on gateway type and associations. - gateway_type: - If ``GATEWAY`` is specified, only gateways are returned. If - ``NON_GATEWAY`` is specified, only non-gateway devices are - returned. If ``GATEWAY_TYPE_UNSPECIFIED`` is specified, all - devices are returned. - associations_gateway_id: - If set, only devices associated with the specified gateway are - returned. The gateway ID can be numeric (``num_id``) or the - user-defined string (``id``). For example, if ``123`` is - specified, only devices bound to the gateway with ``num_id`` - 123 are returned. - associations_device_id: - If set, returns only the gateways with which the specified - device is associated. The device ID can be numeric - (``num_id``) or the user-defined string (``id``). For example, - if ``456`` is specified, returns only the gateways to which - the device with ``num_id`` 456 is bound. - """, - # @@protoc_insertion_point(class_scope:google.cloud.iot.v1.GatewayListOptions) - }, -) -_sym_db.RegisterMessage(GatewayListOptions) - -ListDevicesResponse = _reflection.GeneratedProtocolMessageType( - "ListDevicesResponse", - (_message.Message,), - { - "DESCRIPTOR": _LISTDEVICESRESPONSE, - "__module__": "google.cloud.iot_v1.proto.device_manager_pb2", - "__doc__": """Response for ``ListDevices``. - - Attributes: - devices: - The devices that match the request. - next_page_token: - If not empty, indicates that there may be more devices that - match the request; this value should be passed in a new - ``ListDevicesRequest``. - """, - # @@protoc_insertion_point(class_scope:google.cloud.iot.v1.ListDevicesResponse) - }, -) -_sym_db.RegisterMessage(ListDevicesResponse) - -ModifyCloudToDeviceConfigRequest = _reflection.GeneratedProtocolMessageType( - "ModifyCloudToDeviceConfigRequest", - (_message.Message,), - { - "DESCRIPTOR": _MODIFYCLOUDTODEVICECONFIGREQUEST, - "__module__": "google.cloud.iot_v1.proto.device_manager_pb2", - "__doc__": """Request for ``ModifyCloudToDeviceConfig``. - - Attributes: - name: - Required. The name of the device. For example, - ``projects/p0/locations/us- - central1/registries/registry0/devices/device0`` or - ``projects/p0/locations/us- - central1/registries/registry0/devices/{num_id}``. - version_to_update: - The version number to update. If this value is zero, it will - not check the version number of the server and will always - update the current version; otherwise, this update will fail - if the version number found on the server does not match this - version number. This is used to support multiple simultaneous - updates without losing data. - binary_data: - Required. The configuration data for the device. - """, - # @@protoc_insertion_point(class_scope:google.cloud.iot.v1.ModifyCloudToDeviceConfigRequest) - }, -) -_sym_db.RegisterMessage(ModifyCloudToDeviceConfigRequest) - -ListDeviceConfigVersionsRequest = _reflection.GeneratedProtocolMessageType( - "ListDeviceConfigVersionsRequest", - (_message.Message,), - { - "DESCRIPTOR": _LISTDEVICECONFIGVERSIONSREQUEST, - "__module__": "google.cloud.iot_v1.proto.device_manager_pb2", - "__doc__": """Request for ``ListDeviceConfigVersions``. - - Attributes: - name: - Required. The name of the device. For example, - ``projects/p0/locations/us- - central1/registries/registry0/devices/device0`` or - ``projects/p0/locations/us- - central1/registries/registry0/devices/{num_id}``. - num_versions: - The number of versions to list. Versions are listed in - decreasing order of the version number. The maximum number of - versions retained is 10. If this value is zero, it will return - all the versions available. - """, - # @@protoc_insertion_point(class_scope:google.cloud.iot.v1.ListDeviceConfigVersionsRequest) - }, -) -_sym_db.RegisterMessage(ListDeviceConfigVersionsRequest) - -ListDeviceConfigVersionsResponse = _reflection.GeneratedProtocolMessageType( - "ListDeviceConfigVersionsResponse", - (_message.Message,), - { - "DESCRIPTOR": _LISTDEVICECONFIGVERSIONSRESPONSE, - "__module__": "google.cloud.iot_v1.proto.device_manager_pb2", - "__doc__": """Response for ``ListDeviceConfigVersions``. - - Attributes: - device_configs: - The device configuration for the last few versions. Versions - are listed in decreasing order, starting from the most recent - one. - """, - # @@protoc_insertion_point(class_scope:google.cloud.iot.v1.ListDeviceConfigVersionsResponse) - }, -) -_sym_db.RegisterMessage(ListDeviceConfigVersionsResponse) - -ListDeviceStatesRequest = _reflection.GeneratedProtocolMessageType( - "ListDeviceStatesRequest", - (_message.Message,), - { - "DESCRIPTOR": _LISTDEVICESTATESREQUEST, - "__module__": "google.cloud.iot_v1.proto.device_manager_pb2", - "__doc__": """Request for ``ListDeviceStates``. - - Attributes: - name: - Required. The name of the device. For example, - ``projects/p0/locations/us- - central1/registries/registry0/devices/device0`` or - ``projects/p0/locations/us- - central1/registries/registry0/devices/{num_id}``. - num_states: - The number of states to list. States are listed in descending - order of update time. The maximum number of states retained is - 10. If this value is zero, it will return all the states - available. - """, - # @@protoc_insertion_point(class_scope:google.cloud.iot.v1.ListDeviceStatesRequest) - }, -) -_sym_db.RegisterMessage(ListDeviceStatesRequest) - -ListDeviceStatesResponse = _reflection.GeneratedProtocolMessageType( - "ListDeviceStatesResponse", - (_message.Message,), - { - "DESCRIPTOR": _LISTDEVICESTATESRESPONSE, - "__module__": "google.cloud.iot_v1.proto.device_manager_pb2", - "__doc__": """Response for ``ListDeviceStates``. - - Attributes: - device_states: - The last few device states. States are listed in descending - order of server update time, starting from the most recent - one. - """, - # @@protoc_insertion_point(class_scope:google.cloud.iot.v1.ListDeviceStatesResponse) - }, -) -_sym_db.RegisterMessage(ListDeviceStatesResponse) - -SendCommandToDeviceRequest = _reflection.GeneratedProtocolMessageType( - "SendCommandToDeviceRequest", - (_message.Message,), - { - "DESCRIPTOR": _SENDCOMMANDTODEVICEREQUEST, - "__module__": "google.cloud.iot_v1.proto.device_manager_pb2", - "__doc__": """Request for ``SendCommandToDevice``. - - Attributes: - name: - Required. The name of the device. For example, - ``projects/p0/locations/us- - central1/registries/registry0/devices/device0`` or - ``projects/p0/locations/us- - central1/registries/registry0/devices/{num_id}``. - binary_data: - Required. The command data to send to the device. - subfolder: - Optional subfolder for the command. If empty, the command will - be delivered to the /devices/{device-id}/commands topic, - otherwise it will be delivered to the /devices/{device- - id}/commands/{subfolder} topic. Multi-level subfolders are - allowed. This field must not have more than 256 characters, - and must not contain any MQTT wildcards (“+” or “#”) or null - characters. - """, - # @@protoc_insertion_point(class_scope:google.cloud.iot.v1.SendCommandToDeviceRequest) - }, -) -_sym_db.RegisterMessage(SendCommandToDeviceRequest) - -SendCommandToDeviceResponse = _reflection.GeneratedProtocolMessageType( - "SendCommandToDeviceResponse", - (_message.Message,), - { - "DESCRIPTOR": _SENDCOMMANDTODEVICERESPONSE, - "__module__": "google.cloud.iot_v1.proto.device_manager_pb2", - "__doc__": """Response for ``SendCommandToDevice``.""", - # @@protoc_insertion_point(class_scope:google.cloud.iot.v1.SendCommandToDeviceResponse) - }, -) -_sym_db.RegisterMessage(SendCommandToDeviceResponse) - -BindDeviceToGatewayRequest = _reflection.GeneratedProtocolMessageType( - "BindDeviceToGatewayRequest", - (_message.Message,), - { - "DESCRIPTOR": _BINDDEVICETOGATEWAYREQUEST, - "__module__": "google.cloud.iot_v1.proto.device_manager_pb2", - "__doc__": """Request for ``BindDeviceToGateway``. - - Attributes: - parent: - Required. The name of the registry. For example, - ``projects/example-project/locations/us- - central1/registries/my-registry``. - gateway_id: - Required. The value of ``gateway_id`` can be either the device - numeric ID or the user-defined device identifier. - device_id: - Required. The device to associate with the specified gateway. - The value of ``device_id`` can be either the device numeric ID - or the user-defined device identifier. - """, - # @@protoc_insertion_point(class_scope:google.cloud.iot.v1.BindDeviceToGatewayRequest) - }, -) -_sym_db.RegisterMessage(BindDeviceToGatewayRequest) - -BindDeviceToGatewayResponse = _reflection.GeneratedProtocolMessageType( - "BindDeviceToGatewayResponse", - (_message.Message,), - { - "DESCRIPTOR": _BINDDEVICETOGATEWAYRESPONSE, - "__module__": "google.cloud.iot_v1.proto.device_manager_pb2", - "__doc__": """Response for ``BindDeviceToGateway``.""", - # @@protoc_insertion_point(class_scope:google.cloud.iot.v1.BindDeviceToGatewayResponse) - }, -) -_sym_db.RegisterMessage(BindDeviceToGatewayResponse) - -UnbindDeviceFromGatewayRequest = _reflection.GeneratedProtocolMessageType( - "UnbindDeviceFromGatewayRequest", - (_message.Message,), - { - "DESCRIPTOR": _UNBINDDEVICEFROMGATEWAYREQUEST, - "__module__": "google.cloud.iot_v1.proto.device_manager_pb2", - "__doc__": """Request for ``UnbindDeviceFromGateway``. - - Attributes: - parent: - Required. The name of the registry. For example, - ``projects/example-project/locations/us- - central1/registries/my-registry``. - gateway_id: - Required. The value of ``gateway_id`` can be either the device - numeric ID or the user-defined device identifier. - device_id: - Required. The device to disassociate from the specified - gateway. The value of ``device_id`` can be either the device - numeric ID or the user-defined device identifier. - """, - # @@protoc_insertion_point(class_scope:google.cloud.iot.v1.UnbindDeviceFromGatewayRequest) - }, -) -_sym_db.RegisterMessage(UnbindDeviceFromGatewayRequest) - -UnbindDeviceFromGatewayResponse = _reflection.GeneratedProtocolMessageType( - "UnbindDeviceFromGatewayResponse", - (_message.Message,), - { - "DESCRIPTOR": _UNBINDDEVICEFROMGATEWAYRESPONSE, - "__module__": "google.cloud.iot_v1.proto.device_manager_pb2", - "__doc__": """Response for ``UnbindDeviceFromGateway``.""", - # @@protoc_insertion_point(class_scope:google.cloud.iot.v1.UnbindDeviceFromGatewayResponse) - }, -) -_sym_db.RegisterMessage(UnbindDeviceFromGatewayResponse) - - -DESCRIPTOR._options = None -_CREATEDEVICEREGISTRYREQUEST.fields_by_name["parent"]._options = None -_CREATEDEVICEREGISTRYREQUEST.fields_by_name["device_registry"]._options = None -_GETDEVICEREGISTRYREQUEST.fields_by_name["name"]._options = None -_DELETEDEVICEREGISTRYREQUEST.fields_by_name["name"]._options = None -_UPDATEDEVICEREGISTRYREQUEST.fields_by_name["device_registry"]._options = None -_UPDATEDEVICEREGISTRYREQUEST.fields_by_name["update_mask"]._options = None -_LISTDEVICEREGISTRIESREQUEST.fields_by_name["parent"]._options = None -_CREATEDEVICEREQUEST.fields_by_name["parent"]._options = None -_CREATEDEVICEREQUEST.fields_by_name["device"]._options = None -_GETDEVICEREQUEST.fields_by_name["name"]._options = None -_UPDATEDEVICEREQUEST.fields_by_name["device"]._options = None -_UPDATEDEVICEREQUEST.fields_by_name["update_mask"]._options = None -_DELETEDEVICEREQUEST.fields_by_name["name"]._options = None -_LISTDEVICESREQUEST.fields_by_name["parent"]._options = None -_MODIFYCLOUDTODEVICECONFIGREQUEST.fields_by_name["name"]._options = None -_MODIFYCLOUDTODEVICECONFIGREQUEST.fields_by_name["binary_data"]._options = None -_LISTDEVICECONFIGVERSIONSREQUEST.fields_by_name["name"]._options = None -_LISTDEVICESTATESREQUEST.fields_by_name["name"]._options = None -_SENDCOMMANDTODEVICEREQUEST.fields_by_name["name"]._options = None -_SENDCOMMANDTODEVICEREQUEST.fields_by_name["binary_data"]._options = None -_BINDDEVICETOGATEWAYREQUEST.fields_by_name["parent"]._options = None -_BINDDEVICETOGATEWAYREQUEST.fields_by_name["gateway_id"]._options = None -_BINDDEVICETOGATEWAYREQUEST.fields_by_name["device_id"]._options = None -_UNBINDDEVICEFROMGATEWAYREQUEST.fields_by_name["parent"]._options = None -_UNBINDDEVICEFROMGATEWAYREQUEST.fields_by_name["gateway_id"]._options = None -_UNBINDDEVICEFROMGATEWAYREQUEST.fields_by_name["device_id"]._options = None - -_DEVICEMANAGER = _descriptor.ServiceDescriptor( - name="DeviceManager", - full_name="google.cloud.iot.v1.DeviceManager", - file=DESCRIPTOR, - index=0, - serialized_options=b"\312A\027cloudiot.googleapis.com\322AWhttps://www.googleapis.com/auth/cloud-platform,https://www.googleapis.com/auth/cloudiot", - create_key=_descriptor._internal_create_key, - serialized_start=3147, - serialized_end=8049, - methods=[ - _descriptor.MethodDescriptor( - name="CreateDeviceRegistry", - full_name="google.cloud.iot.v1.DeviceManager.CreateDeviceRegistry", - index=0, - containing_service=None, - input_type=_CREATEDEVICEREGISTRYREQUEST, - output_type=google_dot_cloud_dot_iot__v1_dot_proto_dot_resources__pb2._DEVICEREGISTRY, - serialized_options=b'\202\323\344\223\002A"./v1/{parent=projects/*/locations/*}/registries:\017device_registry\332A\026parent,device_registry', - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="GetDeviceRegistry", - full_name="google.cloud.iot.v1.DeviceManager.GetDeviceRegistry", - index=1, - containing_service=None, - input_type=_GETDEVICEREGISTRYREQUEST, - output_type=google_dot_cloud_dot_iot__v1_dot_proto_dot_resources__pb2._DEVICEREGISTRY, - serialized_options=b"\202\323\344\223\0020\022./v1/{name=projects/*/locations/*/registries/*}\332A\004name", - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="UpdateDeviceRegistry", - full_name="google.cloud.iot.v1.DeviceManager.UpdateDeviceRegistry", - index=2, - containing_service=None, - input_type=_UPDATEDEVICEREGISTRYREQUEST, - output_type=google_dot_cloud_dot_iot__v1_dot_proto_dot_resources__pb2._DEVICEREGISTRY, - serialized_options=b"\202\323\344\223\002Q2>/v1/{device_registry.name=projects/*/locations/*/registries/*}:\017device_registry\332A\033device_registry,update_mask", - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="DeleteDeviceRegistry", - full_name="google.cloud.iot.v1.DeviceManager.DeleteDeviceRegistry", - index=3, - containing_service=None, - input_type=_DELETEDEVICEREGISTRYREQUEST, - output_type=google_dot_protobuf_dot_empty__pb2._EMPTY, - serialized_options=b"\202\323\344\223\0020*./v1/{name=projects/*/locations/*/registries/*}\332A\004name", - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="ListDeviceRegistries", - full_name="google.cloud.iot.v1.DeviceManager.ListDeviceRegistries", - index=4, - containing_service=None, - input_type=_LISTDEVICEREGISTRIESREQUEST, - output_type=_LISTDEVICEREGISTRIESRESPONSE, - serialized_options=b"\202\323\344\223\0020\022./v1/{parent=projects/*/locations/*}/registries\332A\006parent", - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="CreateDevice", - full_name="google.cloud.iot.v1.DeviceManager.CreateDevice", - index=5, - containing_service=None, - input_type=_CREATEDEVICEREQUEST, - output_type=google_dot_cloud_dot_iot__v1_dot_proto_dot_resources__pb2._DEVICE, - serialized_options=b'\202\323\344\223\002B"8/v1/{parent=projects/*/locations/*/registries/*}/devices:\006device\332A\rparent,device', - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="GetDevice", - full_name="google.cloud.iot.v1.DeviceManager.GetDevice", - index=6, - containing_service=None, - input_type=_GETDEVICEREQUEST, - output_type=google_dot_cloud_dot_iot__v1_dot_proto_dot_resources__pb2._DEVICE, - serialized_options=b"\202\323\344\223\002\177\0228/v1/{name=projects/*/locations/*/registries/*/devices/*}ZC\022A/v1/{name=projects/*/locations/*/registries/*/groups/*/devices/*}\332A\004name", - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="UpdateDevice", - full_name="google.cloud.iot.v1.DeviceManager.UpdateDevice", - index=7, - containing_service=None, - input_type=_UPDATEDEVICEREQUEST, - output_type=google_dot_cloud_dot_iot__v1_dot_proto_dot_resources__pb2._DEVICE, - serialized_options=b"\202\323\344\223\002\235\0012?/v1/{device.name=projects/*/locations/*/registries/*/devices/*}:\006deviceZR2H/v1/{device.name=projects/*/locations/*/registries/*/groups/*/devices/*}:\006device\332A\022device,update_mask", - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="DeleteDevice", - full_name="google.cloud.iot.v1.DeviceManager.DeleteDevice", - index=8, - containing_service=None, - input_type=_DELETEDEVICEREQUEST, - output_type=google_dot_protobuf_dot_empty__pb2._EMPTY, - serialized_options=b"\202\323\344\223\002:*8/v1/{name=projects/*/locations/*/registries/*/devices/*}\332A\004name", - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="ListDevices", - full_name="google.cloud.iot.v1.DeviceManager.ListDevices", - index=9, - containing_service=None, - input_type=_LISTDEVICESREQUEST, - output_type=_LISTDEVICESRESPONSE, - serialized_options=b"\202\323\344\223\002\177\0228/v1/{parent=projects/*/locations/*/registries/*}/devicesZC\022A/v1/{parent=projects/*/locations/*/registries/*/groups/*}/devices\332A\006parent", - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="ModifyCloudToDeviceConfig", - full_name="google.cloud.iot.v1.DeviceManager.ModifyCloudToDeviceConfig", - index=10, - containing_service=None, - input_type=_MODIFYCLOUDTODEVICECONFIGREQUEST, - output_type=google_dot_cloud_dot_iot__v1_dot_proto_dot_resources__pb2._DEVICECONFIG, - serialized_options=b'\202\323\344\223\002\271\001"R/v1/{name=projects/*/locations/*/registries/*/devices/*}:modifyCloudToDeviceConfig:\001*Z`"[/v1/{name=projects/*/locations/*/registries/*/groups/*/devices/*}:modifyCloudToDeviceConfig:\001*\332A\020name,binary_data', - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="ListDeviceConfigVersions", - full_name="google.cloud.iot.v1.DeviceManager.ListDeviceConfigVersions", - index=11, - containing_service=None, - input_type=_LISTDEVICECONFIGVERSIONSREQUEST, - output_type=_LISTDEVICECONFIGVERSIONSRESPONSE, - serialized_options=b"\202\323\344\223\002\235\001\022G/v1/{name=projects/*/locations/*/registries/*/devices/*}/configVersionsZR\022P/v1/{name=projects/*/locations/*/registries/*/groups/*/devices/*}/configVersions\332A\004name", - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="ListDeviceStates", - full_name="google.cloud.iot.v1.DeviceManager.ListDeviceStates", - index=12, - containing_service=None, - input_type=_LISTDEVICESTATESREQUEST, - output_type=_LISTDEVICESTATESRESPONSE, - serialized_options=b"\202\323\344\223\002\215\001\022?/v1/{name=projects/*/locations/*/registries/*/devices/*}/statesZJ\022H/v1/{name=projects/*/locations/*/registries/*/groups/*/devices/*}/states\332A\004name", - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="SetIamPolicy", - full_name="google.cloud.iot.v1.DeviceManager.SetIamPolicy", - index=13, - containing_service=None, - input_type=google_dot_iam_dot_v1_dot_iam__policy__pb2._SETIAMPOLICYREQUEST, - output_type=google_dot_iam_dot_v1_dot_policy__pb2._POLICY, - serialized_options=b'\202\323\344\223\002\223\001"?/v1/{resource=projects/*/locations/*/registries/*}:setIamPolicy:\001*ZM"H/v1/{resource=projects/*/locations/*/registries/*/groups/*}:setIamPolicy:\001*\332A\017resource,policy', - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="GetIamPolicy", - full_name="google.cloud.iot.v1.DeviceManager.GetIamPolicy", - index=14, - containing_service=None, - input_type=google_dot_iam_dot_v1_dot_iam__policy__pb2._GETIAMPOLICYREQUEST, - output_type=google_dot_iam_dot_v1_dot_policy__pb2._POLICY, - serialized_options=b'\202\323\344\223\002\223\001"?/v1/{resource=projects/*/locations/*/registries/*}:getIamPolicy:\001*ZM"H/v1/{resource=projects/*/locations/*/registries/*/groups/*}:getIamPolicy:\001*\332A\010resource', - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="TestIamPermissions", - full_name="google.cloud.iot.v1.DeviceManager.TestIamPermissions", - index=15, - containing_service=None, - input_type=google_dot_iam_dot_v1_dot_iam__policy__pb2._TESTIAMPERMISSIONSREQUEST, - output_type=google_dot_iam_dot_v1_dot_iam__policy__pb2._TESTIAMPERMISSIONSRESPONSE, - serialized_options=b'\202\323\344\223\002\237\001"E/v1/{resource=projects/*/locations/*/registries/*}:testIamPermissions:\001*ZS"N/v1/{resource=projects/*/locations/*/registries/*/groups/*}:testIamPermissions:\001*\332A\024resource,permissions', - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="SendCommandToDevice", - full_name="google.cloud.iot.v1.DeviceManager.SendCommandToDevice", - index=16, - containing_service=None, - input_type=_SENDCOMMANDTODEVICEREQUEST, - output_type=_SENDCOMMANDTODEVICERESPONSE, - serialized_options=b'\202\323\344\223\002\255\001"L/v1/{name=projects/*/locations/*/registries/*/devices/*}:sendCommandToDevice:\001*ZZ"U/v1/{name=projects/*/locations/*/registries/*/groups/*/devices/*}:sendCommandToDevice:\001*\332A\020name,binary_data\332A\032name,binary_data,subfolder', - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="BindDeviceToGateway", - full_name="google.cloud.iot.v1.DeviceManager.BindDeviceToGateway", - index=17, - containing_service=None, - input_type=_BINDDEVICETOGATEWAYREQUEST, - output_type=_BINDDEVICETOGATEWAYRESPONSE, - serialized_options=b'\202\323\344\223\002\235\001"D/v1/{parent=projects/*/locations/*/registries/*}:bindDeviceToGateway:\001*ZR"M/v1/{parent=projects/*/locations/*/registries/*/groups/*}:bindDeviceToGateway:\001*\332A\033parent,gateway_id,device_id', - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="UnbindDeviceFromGateway", - full_name="google.cloud.iot.v1.DeviceManager.UnbindDeviceFromGateway", - index=18, - containing_service=None, - input_type=_UNBINDDEVICEFROMGATEWAYREQUEST, - output_type=_UNBINDDEVICEFROMGATEWAYRESPONSE, - serialized_options=b'\202\323\344\223\002\245\001"H/v1/{parent=projects/*/locations/*/registries/*}:unbindDeviceFromGateway:\001*ZV"Q/v1/{parent=projects/*/locations/*/registries/*/groups/*}:unbindDeviceFromGateway:\001*\332A\033parent,gateway_id,device_id', - create_key=_descriptor._internal_create_key, - ), - ], -) -_sym_db.RegisterServiceDescriptor(_DEVICEMANAGER) - -DESCRIPTOR.services_by_name["DeviceManager"] = _DEVICEMANAGER - -# @@protoc_insertion_point(module_scope) diff --git a/google/cloud/iot_v1/proto/device_manager_pb2_grpc.py b/google/cloud/iot_v1/proto/device_manager_pb2_grpc.py deleted file mode 100644 index 2b16c303..00000000 --- a/google/cloud/iot_v1/proto/device_manager_pb2_grpc.py +++ /dev/null @@ -1,382 +0,0 @@ -# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! -import grpc - -from google.cloud.iot_v1.proto import ( - device_manager_pb2 as google_dot_cloud_dot_iot__v1_dot_proto_dot_device__manager__pb2, -) -from google.cloud.iot_v1.proto import ( - resources_pb2 as google_dot_cloud_dot_iot__v1_dot_proto_dot_resources__pb2, -) -from google.iam.v1 import iam_policy_pb2 as google_dot_iam_dot_v1_dot_iam__policy__pb2 -from google.iam.v1 import policy_pb2 as google_dot_iam_dot_v1_dot_policy__pb2 -from google.protobuf import empty_pb2 as google_dot_protobuf_dot_empty__pb2 - - -class DeviceManagerStub(object): - """Internet of Things (IoT) service. Securely connect and manage IoT devices. - """ - - def __init__(self, channel): - """Constructor. - - Args: - channel: A grpc.Channel. - """ - self.CreateDeviceRegistry = channel.unary_unary( - "/google.cloud.iot.v1.DeviceManager/CreateDeviceRegistry", - request_serializer=google_dot_cloud_dot_iot__v1_dot_proto_dot_device__manager__pb2.CreateDeviceRegistryRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_iot__v1_dot_proto_dot_resources__pb2.DeviceRegistry.FromString, - ) - self.GetDeviceRegistry = channel.unary_unary( - "/google.cloud.iot.v1.DeviceManager/GetDeviceRegistry", - request_serializer=google_dot_cloud_dot_iot__v1_dot_proto_dot_device__manager__pb2.GetDeviceRegistryRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_iot__v1_dot_proto_dot_resources__pb2.DeviceRegistry.FromString, - ) - self.UpdateDeviceRegistry = channel.unary_unary( - "/google.cloud.iot.v1.DeviceManager/UpdateDeviceRegistry", - request_serializer=google_dot_cloud_dot_iot__v1_dot_proto_dot_device__manager__pb2.UpdateDeviceRegistryRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_iot__v1_dot_proto_dot_resources__pb2.DeviceRegistry.FromString, - ) - self.DeleteDeviceRegistry = channel.unary_unary( - "/google.cloud.iot.v1.DeviceManager/DeleteDeviceRegistry", - request_serializer=google_dot_cloud_dot_iot__v1_dot_proto_dot_device__manager__pb2.DeleteDeviceRegistryRequest.SerializeToString, - response_deserializer=google_dot_protobuf_dot_empty__pb2.Empty.FromString, - ) - self.ListDeviceRegistries = channel.unary_unary( - "/google.cloud.iot.v1.DeviceManager/ListDeviceRegistries", - request_serializer=google_dot_cloud_dot_iot__v1_dot_proto_dot_device__manager__pb2.ListDeviceRegistriesRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_iot__v1_dot_proto_dot_device__manager__pb2.ListDeviceRegistriesResponse.FromString, - ) - self.CreateDevice = channel.unary_unary( - "/google.cloud.iot.v1.DeviceManager/CreateDevice", - request_serializer=google_dot_cloud_dot_iot__v1_dot_proto_dot_device__manager__pb2.CreateDeviceRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_iot__v1_dot_proto_dot_resources__pb2.Device.FromString, - ) - self.GetDevice = channel.unary_unary( - "/google.cloud.iot.v1.DeviceManager/GetDevice", - request_serializer=google_dot_cloud_dot_iot__v1_dot_proto_dot_device__manager__pb2.GetDeviceRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_iot__v1_dot_proto_dot_resources__pb2.Device.FromString, - ) - self.UpdateDevice = channel.unary_unary( - "/google.cloud.iot.v1.DeviceManager/UpdateDevice", - request_serializer=google_dot_cloud_dot_iot__v1_dot_proto_dot_device__manager__pb2.UpdateDeviceRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_iot__v1_dot_proto_dot_resources__pb2.Device.FromString, - ) - self.DeleteDevice = channel.unary_unary( - "/google.cloud.iot.v1.DeviceManager/DeleteDevice", - request_serializer=google_dot_cloud_dot_iot__v1_dot_proto_dot_device__manager__pb2.DeleteDeviceRequest.SerializeToString, - response_deserializer=google_dot_protobuf_dot_empty__pb2.Empty.FromString, - ) - self.ListDevices = channel.unary_unary( - "/google.cloud.iot.v1.DeviceManager/ListDevices", - request_serializer=google_dot_cloud_dot_iot__v1_dot_proto_dot_device__manager__pb2.ListDevicesRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_iot__v1_dot_proto_dot_device__manager__pb2.ListDevicesResponse.FromString, - ) - self.ModifyCloudToDeviceConfig = channel.unary_unary( - "/google.cloud.iot.v1.DeviceManager/ModifyCloudToDeviceConfig", - request_serializer=google_dot_cloud_dot_iot__v1_dot_proto_dot_device__manager__pb2.ModifyCloudToDeviceConfigRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_iot__v1_dot_proto_dot_resources__pb2.DeviceConfig.FromString, - ) - self.ListDeviceConfigVersions = channel.unary_unary( - "/google.cloud.iot.v1.DeviceManager/ListDeviceConfigVersions", - request_serializer=google_dot_cloud_dot_iot__v1_dot_proto_dot_device__manager__pb2.ListDeviceConfigVersionsRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_iot__v1_dot_proto_dot_device__manager__pb2.ListDeviceConfigVersionsResponse.FromString, - ) - self.ListDeviceStates = channel.unary_unary( - "/google.cloud.iot.v1.DeviceManager/ListDeviceStates", - request_serializer=google_dot_cloud_dot_iot__v1_dot_proto_dot_device__manager__pb2.ListDeviceStatesRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_iot__v1_dot_proto_dot_device__manager__pb2.ListDeviceStatesResponse.FromString, - ) - self.SetIamPolicy = channel.unary_unary( - "/google.cloud.iot.v1.DeviceManager/SetIamPolicy", - request_serializer=google_dot_iam_dot_v1_dot_iam__policy__pb2.SetIamPolicyRequest.SerializeToString, - response_deserializer=google_dot_iam_dot_v1_dot_policy__pb2.Policy.FromString, - ) - self.GetIamPolicy = channel.unary_unary( - "/google.cloud.iot.v1.DeviceManager/GetIamPolicy", - request_serializer=google_dot_iam_dot_v1_dot_iam__policy__pb2.GetIamPolicyRequest.SerializeToString, - response_deserializer=google_dot_iam_dot_v1_dot_policy__pb2.Policy.FromString, - ) - self.TestIamPermissions = channel.unary_unary( - "/google.cloud.iot.v1.DeviceManager/TestIamPermissions", - request_serializer=google_dot_iam_dot_v1_dot_iam__policy__pb2.TestIamPermissionsRequest.SerializeToString, - response_deserializer=google_dot_iam_dot_v1_dot_iam__policy__pb2.TestIamPermissionsResponse.FromString, - ) - self.SendCommandToDevice = channel.unary_unary( - "/google.cloud.iot.v1.DeviceManager/SendCommandToDevice", - request_serializer=google_dot_cloud_dot_iot__v1_dot_proto_dot_device__manager__pb2.SendCommandToDeviceRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_iot__v1_dot_proto_dot_device__manager__pb2.SendCommandToDeviceResponse.FromString, - ) - self.BindDeviceToGateway = channel.unary_unary( - "/google.cloud.iot.v1.DeviceManager/BindDeviceToGateway", - request_serializer=google_dot_cloud_dot_iot__v1_dot_proto_dot_device__manager__pb2.BindDeviceToGatewayRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_iot__v1_dot_proto_dot_device__manager__pb2.BindDeviceToGatewayResponse.FromString, - ) - self.UnbindDeviceFromGateway = channel.unary_unary( - "/google.cloud.iot.v1.DeviceManager/UnbindDeviceFromGateway", - request_serializer=google_dot_cloud_dot_iot__v1_dot_proto_dot_device__manager__pb2.UnbindDeviceFromGatewayRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_iot__v1_dot_proto_dot_device__manager__pb2.UnbindDeviceFromGatewayResponse.FromString, - ) - - -class DeviceManagerServicer(object): - """Internet of Things (IoT) service. Securely connect and manage IoT devices. - """ - - def CreateDeviceRegistry(self, request, context): - """Creates a device registry that contains devices. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def GetDeviceRegistry(self, request, context): - """Gets a device registry configuration. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def UpdateDeviceRegistry(self, request, context): - """Updates a device registry configuration. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def DeleteDeviceRegistry(self, request, context): - """Deletes a device registry configuration. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def ListDeviceRegistries(self, request, context): - """Lists device registries. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def CreateDevice(self, request, context): - """Creates a device in a device registry. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def GetDevice(self, request, context): - """Gets details about a device. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def UpdateDevice(self, request, context): - """Updates a device. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def DeleteDevice(self, request, context): - """Deletes a device. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def ListDevices(self, request, context): - """List devices in a device registry. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def ModifyCloudToDeviceConfig(self, request, context): - """Modifies the configuration for the device, which is eventually sent from - the Cloud IoT Core servers. Returns the modified configuration version and - its metadata. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def ListDeviceConfigVersions(self, request, context): - """Lists the last few versions of the device configuration in descending - order (i.e.: newest first). - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def ListDeviceStates(self, request, context): - """Lists the last few versions of the device state in descending order (i.e.: - newest first). - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def SetIamPolicy(self, request, context): - """Sets the access control policy on the specified resource. Replaces any - existing policy. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def GetIamPolicy(self, request, context): - """Gets the access control policy for a resource. - Returns an empty policy if the resource exists and does not have a policy - set. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def TestIamPermissions(self, request, context): - """Returns permissions that a caller has on the specified resource. - If the resource does not exist, this will return an empty set of - permissions, not a NOT_FOUND error. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def SendCommandToDevice(self, request, context): - """Sends a command to the specified device. In order for a device to be able - to receive commands, it must: - 1) be connected to Cloud IoT Core using the MQTT protocol, and - 2) be subscribed to the group of MQTT topics specified by - /devices/{device-id}/commands/#. This subscription will receive commands - at the top-level topic /devices/{device-id}/commands as well as commands - for subfolders, like /devices/{device-id}/commands/subfolder. - Note that subscribing to specific subfolders is not supported. - If the command could not be delivered to the device, this method will - return an error; in particular, if the device is not subscribed, this - method will return FAILED_PRECONDITION. Otherwise, this method will - return OK. If the subscription is QoS 1, at least once delivery will be - guaranteed; for QoS 0, no acknowledgment will be expected from the device. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def BindDeviceToGateway(self, request, context): - """Associates the device with the gateway. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def UnbindDeviceFromGateway(self, request, context): - """Deletes the association between the device and the gateway. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - -def add_DeviceManagerServicer_to_server(servicer, server): - rpc_method_handlers = { - "CreateDeviceRegistry": grpc.unary_unary_rpc_method_handler( - servicer.CreateDeviceRegistry, - request_deserializer=google_dot_cloud_dot_iot__v1_dot_proto_dot_device__manager__pb2.CreateDeviceRegistryRequest.FromString, - response_serializer=google_dot_cloud_dot_iot__v1_dot_proto_dot_resources__pb2.DeviceRegistry.SerializeToString, - ), - "GetDeviceRegistry": grpc.unary_unary_rpc_method_handler( - servicer.GetDeviceRegistry, - request_deserializer=google_dot_cloud_dot_iot__v1_dot_proto_dot_device__manager__pb2.GetDeviceRegistryRequest.FromString, - response_serializer=google_dot_cloud_dot_iot__v1_dot_proto_dot_resources__pb2.DeviceRegistry.SerializeToString, - ), - "UpdateDeviceRegistry": grpc.unary_unary_rpc_method_handler( - servicer.UpdateDeviceRegistry, - request_deserializer=google_dot_cloud_dot_iot__v1_dot_proto_dot_device__manager__pb2.UpdateDeviceRegistryRequest.FromString, - response_serializer=google_dot_cloud_dot_iot__v1_dot_proto_dot_resources__pb2.DeviceRegistry.SerializeToString, - ), - "DeleteDeviceRegistry": grpc.unary_unary_rpc_method_handler( - servicer.DeleteDeviceRegistry, - request_deserializer=google_dot_cloud_dot_iot__v1_dot_proto_dot_device__manager__pb2.DeleteDeviceRegistryRequest.FromString, - response_serializer=google_dot_protobuf_dot_empty__pb2.Empty.SerializeToString, - ), - "ListDeviceRegistries": grpc.unary_unary_rpc_method_handler( - servicer.ListDeviceRegistries, - request_deserializer=google_dot_cloud_dot_iot__v1_dot_proto_dot_device__manager__pb2.ListDeviceRegistriesRequest.FromString, - response_serializer=google_dot_cloud_dot_iot__v1_dot_proto_dot_device__manager__pb2.ListDeviceRegistriesResponse.SerializeToString, - ), - "CreateDevice": grpc.unary_unary_rpc_method_handler( - servicer.CreateDevice, - request_deserializer=google_dot_cloud_dot_iot__v1_dot_proto_dot_device__manager__pb2.CreateDeviceRequest.FromString, - response_serializer=google_dot_cloud_dot_iot__v1_dot_proto_dot_resources__pb2.Device.SerializeToString, - ), - "GetDevice": grpc.unary_unary_rpc_method_handler( - servicer.GetDevice, - request_deserializer=google_dot_cloud_dot_iot__v1_dot_proto_dot_device__manager__pb2.GetDeviceRequest.FromString, - response_serializer=google_dot_cloud_dot_iot__v1_dot_proto_dot_resources__pb2.Device.SerializeToString, - ), - "UpdateDevice": grpc.unary_unary_rpc_method_handler( - servicer.UpdateDevice, - request_deserializer=google_dot_cloud_dot_iot__v1_dot_proto_dot_device__manager__pb2.UpdateDeviceRequest.FromString, - response_serializer=google_dot_cloud_dot_iot__v1_dot_proto_dot_resources__pb2.Device.SerializeToString, - ), - "DeleteDevice": grpc.unary_unary_rpc_method_handler( - servicer.DeleteDevice, - request_deserializer=google_dot_cloud_dot_iot__v1_dot_proto_dot_device__manager__pb2.DeleteDeviceRequest.FromString, - response_serializer=google_dot_protobuf_dot_empty__pb2.Empty.SerializeToString, - ), - "ListDevices": grpc.unary_unary_rpc_method_handler( - servicer.ListDevices, - request_deserializer=google_dot_cloud_dot_iot__v1_dot_proto_dot_device__manager__pb2.ListDevicesRequest.FromString, - response_serializer=google_dot_cloud_dot_iot__v1_dot_proto_dot_device__manager__pb2.ListDevicesResponse.SerializeToString, - ), - "ModifyCloudToDeviceConfig": grpc.unary_unary_rpc_method_handler( - servicer.ModifyCloudToDeviceConfig, - request_deserializer=google_dot_cloud_dot_iot__v1_dot_proto_dot_device__manager__pb2.ModifyCloudToDeviceConfigRequest.FromString, - response_serializer=google_dot_cloud_dot_iot__v1_dot_proto_dot_resources__pb2.DeviceConfig.SerializeToString, - ), - "ListDeviceConfigVersions": grpc.unary_unary_rpc_method_handler( - servicer.ListDeviceConfigVersions, - request_deserializer=google_dot_cloud_dot_iot__v1_dot_proto_dot_device__manager__pb2.ListDeviceConfigVersionsRequest.FromString, - response_serializer=google_dot_cloud_dot_iot__v1_dot_proto_dot_device__manager__pb2.ListDeviceConfigVersionsResponse.SerializeToString, - ), - "ListDeviceStates": grpc.unary_unary_rpc_method_handler( - servicer.ListDeviceStates, - request_deserializer=google_dot_cloud_dot_iot__v1_dot_proto_dot_device__manager__pb2.ListDeviceStatesRequest.FromString, - response_serializer=google_dot_cloud_dot_iot__v1_dot_proto_dot_device__manager__pb2.ListDeviceStatesResponse.SerializeToString, - ), - "SetIamPolicy": grpc.unary_unary_rpc_method_handler( - servicer.SetIamPolicy, - request_deserializer=google_dot_iam_dot_v1_dot_iam__policy__pb2.SetIamPolicyRequest.FromString, - response_serializer=google_dot_iam_dot_v1_dot_policy__pb2.Policy.SerializeToString, - ), - "GetIamPolicy": grpc.unary_unary_rpc_method_handler( - servicer.GetIamPolicy, - request_deserializer=google_dot_iam_dot_v1_dot_iam__policy__pb2.GetIamPolicyRequest.FromString, - response_serializer=google_dot_iam_dot_v1_dot_policy__pb2.Policy.SerializeToString, - ), - "TestIamPermissions": grpc.unary_unary_rpc_method_handler( - servicer.TestIamPermissions, - request_deserializer=google_dot_iam_dot_v1_dot_iam__policy__pb2.TestIamPermissionsRequest.FromString, - response_serializer=google_dot_iam_dot_v1_dot_iam__policy__pb2.TestIamPermissionsResponse.SerializeToString, - ), - "SendCommandToDevice": grpc.unary_unary_rpc_method_handler( - servicer.SendCommandToDevice, - request_deserializer=google_dot_cloud_dot_iot__v1_dot_proto_dot_device__manager__pb2.SendCommandToDeviceRequest.FromString, - response_serializer=google_dot_cloud_dot_iot__v1_dot_proto_dot_device__manager__pb2.SendCommandToDeviceResponse.SerializeToString, - ), - "BindDeviceToGateway": grpc.unary_unary_rpc_method_handler( - servicer.BindDeviceToGateway, - request_deserializer=google_dot_cloud_dot_iot__v1_dot_proto_dot_device__manager__pb2.BindDeviceToGatewayRequest.FromString, - response_serializer=google_dot_cloud_dot_iot__v1_dot_proto_dot_device__manager__pb2.BindDeviceToGatewayResponse.SerializeToString, - ), - "UnbindDeviceFromGateway": grpc.unary_unary_rpc_method_handler( - servicer.UnbindDeviceFromGateway, - request_deserializer=google_dot_cloud_dot_iot__v1_dot_proto_dot_device__manager__pb2.UnbindDeviceFromGatewayRequest.FromString, - response_serializer=google_dot_cloud_dot_iot__v1_dot_proto_dot_device__manager__pb2.UnbindDeviceFromGatewayResponse.SerializeToString, - ), - } - generic_handler = grpc.method_handlers_generic_handler( - "google.cloud.iot.v1.DeviceManager", rpc_method_handlers - ) - server.add_generic_rpc_handlers((generic_handler,)) diff --git a/google/cloud/iot_v1/proto/resources_pb2.py b/google/cloud/iot_v1/proto/resources_pb2.py deleted file mode 100644 index 110f647a..00000000 --- a/google/cloud/iot_v1/proto/resources_pb2.py +++ /dev/null @@ -1,2362 +0,0 @@ -# -*- coding: utf-8 -*- -# Generated by the protocol buffer compiler. DO NOT EDIT! -# source: google/cloud/iot_v1/proto/resources.proto - -from google.protobuf.internal import enum_type_wrapper -from google.protobuf import descriptor as _descriptor -from google.protobuf import message as _message -from google.protobuf import reflection as _reflection -from google.protobuf import symbol_database as _symbol_database - -# @@protoc_insertion_point(imports) - -_sym_db = _symbol_database.Default() - - -from google.api import resource_pb2 as google_dot_api_dot_resource__pb2 -from google.protobuf import timestamp_pb2 as google_dot_protobuf_dot_timestamp__pb2 -from google.rpc import status_pb2 as google_dot_rpc_dot_status__pb2 - - -DESCRIPTOR = _descriptor.FileDescriptor( - name="google/cloud/iot_v1/proto/resources.proto", - package="google.cloud.iot.v1", - syntax="proto3", - serialized_options=b"\n\027com.google.cloud.iot.v1B\016ResourcesProtoP\001Z6google.golang.org/genproto/googleapis/cloud/iot/v1;iot\370\001\001", - create_key=_descriptor._internal_create_key, - serialized_pb=b'\n)google/cloud/iot_v1/proto/resources.proto\x12\x13google.cloud.iot.v1\x1a\x19google/api/resource.proto\x1a\x1fgoogle/protobuf/timestamp.proto\x1a\x17google/rpc/status.proto"\xb0\x07\n\x06\x44\x65vice\x12\n\n\x02id\x18\x01 \x01(\t\x12\x0c\n\x04name\x18\x02 \x01(\t\x12\x0e\n\x06num_id\x18\x03 \x01(\x04\x12:\n\x0b\x63redentials\x18\x0c \x03(\x0b\x32%.google.cloud.iot.v1.DeviceCredential\x12\x37\n\x13last_heartbeat_time\x18\x07 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x33\n\x0flast_event_time\x18\x08 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x33\n\x0flast_state_time\x18\x14 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x38\n\x14last_config_ack_time\x18\x0e \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x39\n\x15last_config_send_time\x18\x12 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x0f\n\x07\x62locked\x18\x13 \x01(\x08\x12\x33\n\x0flast_error_time\x18\n \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12-\n\x11last_error_status\x18\x0b \x01(\x0b\x32\x12.google.rpc.Status\x12\x31\n\x06\x63onfig\x18\r \x01(\x0b\x32!.google.cloud.iot.v1.DeviceConfig\x12/\n\x05state\x18\x10 \x01(\x0b\x32 .google.cloud.iot.v1.DeviceState\x12\x30\n\tlog_level\x18\x15 \x01(\x0e\x32\x1d.google.cloud.iot.v1.LogLevel\x12;\n\x08metadata\x18\x11 \x03(\x0b\x32).google.cloud.iot.v1.Device.MetadataEntry\x12:\n\x0egateway_config\x18\x18 \x01(\x0b\x32".google.cloud.iot.v1.GatewayConfig\x1a/\n\rMetadataEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01:s\xea\x41p\n\x1e\x63loudiot.googleapis.com/Device\x12Nprojects/{project}/locations/{location}/registries/{registry}/devices/{device}"\xee\x01\n\rGatewayConfig\x12\x36\n\x0cgateway_type\x18\x01 \x01(\x0e\x32 .google.cloud.iot.v1.GatewayType\x12\x43\n\x13gateway_auth_method\x18\x02 \x01(\x0e\x32&.google.cloud.iot.v1.GatewayAuthMethod\x12 \n\x18last_accessed_gateway_id\x18\x03 \x01(\t\x12>\n\x1alast_accessed_gateway_time\x18\x04 \x01(\x0b\x32\x1a.google.protobuf.Timestamp"\x8f\x04\n\x0e\x44\x65viceRegistry\x12\n\n\x02id\x18\x01 \x01(\t\x12\x0c\n\x04name\x18\x02 \x01(\t\x12P\n\x1a\x65vent_notification_configs\x18\n \x03(\x0b\x32,.google.cloud.iot.v1.EventNotificationConfig\x12O\n\x19state_notification_config\x18\x07 \x01(\x0b\x32,.google.cloud.iot.v1.StateNotificationConfig\x12\x34\n\x0bmqtt_config\x18\x04 \x01(\x0b\x32\x1f.google.cloud.iot.v1.MqttConfig\x12\x34\n\x0bhttp_config\x18\t \x01(\x0b\x32\x1f.google.cloud.iot.v1.HttpConfig\x12\x30\n\tlog_level\x18\x0b \x01(\x0e\x32\x1d.google.cloud.iot.v1.LogLevel\x12<\n\x0b\x63redentials\x18\x08 \x03(\x0b\x32\'.google.cloud.iot.v1.RegistryCredential:d\xea\x41\x61\n cloudiot.googleapis.com/Registry\x12=projects/{project}/locations/{location}/registries/{registry}"H\n\nMqttConfig\x12:\n\x12mqtt_enabled_state\x18\x01 \x01(\x0e\x32\x1e.google.cloud.iot.v1.MqttState"H\n\nHttpConfig\x12:\n\x12http_enabled_state\x18\x01 \x01(\x0e\x32\x1e.google.cloud.iot.v1.HttpState"O\n\x17\x45ventNotificationConfig\x12\x19\n\x11subfolder_matches\x18\x02 \x01(\t\x12\x19\n\x11pubsub_topic_name\x18\x01 \x01(\t"4\n\x17StateNotificationConfig\x12\x19\n\x11pubsub_topic_name\x18\x01 \x01(\t"o\n\x12RegistryCredential\x12K\n\x16public_key_certificate\x18\x01 \x01(\x0b\x32).google.cloud.iot.v1.PublicKeyCertificateH\x00\x42\x0c\n\ncredential"\xd0\x01\n\x16X509CertificateDetails\x12\x0e\n\x06issuer\x18\x01 \x01(\t\x12\x0f\n\x07subject\x18\x02 \x01(\t\x12.\n\nstart_time\x18\x03 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12/\n\x0b\x65xpiry_time\x18\x04 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x1b\n\x13signature_algorithm\x18\x05 \x01(\t\x12\x17\n\x0fpublic_key_type\x18\x06 \x01(\t"\xaf\x01\n\x14PublicKeyCertificate\x12?\n\x06\x66ormat\x18\x01 \x01(\x0e\x32/.google.cloud.iot.v1.PublicKeyCertificateFormat\x12\x13\n\x0b\x63\x65rtificate\x18\x02 \x01(\t\x12\x41\n\x0cx509_details\x18\x03 \x01(\x0b\x32+.google.cloud.iot.v1.X509CertificateDetails"\x95\x01\n\x10\x44\x65viceCredential\x12>\n\npublic_key\x18\x02 \x01(\x0b\x32(.google.cloud.iot.v1.PublicKeyCredentialH\x00\x12\x33\n\x0f\x65xpiration_time\x18\x06 \x01(\x0b\x32\x1a.google.protobuf.TimestampB\x0c\n\ncredential"X\n\x13PublicKeyCredential\x12\x34\n\x06\x66ormat\x18\x01 \x01(\x0e\x32$.google.cloud.iot.v1.PublicKeyFormat\x12\x0b\n\x03key\x18\x02 \x01(\t"\xa0\x01\n\x0c\x44\x65viceConfig\x12\x0f\n\x07version\x18\x01 \x01(\x03\x12\x35\n\x11\x63loud_update_time\x18\x02 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x33\n\x0f\x64\x65vice_ack_time\x18\x03 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x13\n\x0b\x62inary_data\x18\x04 \x01(\x0c"S\n\x0b\x44\x65viceState\x12/\n\x0bupdate_time\x18\x01 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x13\n\x0b\x62inary_data\x18\x02 \x01(\x0c*L\n\tMqttState\x12\x1a\n\x16MQTT_STATE_UNSPECIFIED\x10\x00\x12\x10\n\x0cMQTT_ENABLED\x10\x01\x12\x11\n\rMQTT_DISABLED\x10\x02*L\n\tHttpState\x12\x1a\n\x16HTTP_STATE_UNSPECIFIED\x10\x00\x12\x10\n\x0cHTTP_ENABLED\x10\x01\x12\x11\n\rHTTP_DISABLED\x10\x02*O\n\x08LogLevel\x12\x19\n\x15LOG_LEVEL_UNSPECIFIED\x10\x00\x12\x08\n\x04NONE\x10\n\x12\t\n\x05\x45RROR\x10\x14\x12\x08\n\x04INFO\x10\x1e\x12\t\n\x05\x44\x45\x42UG\x10(*I\n\x0bGatewayType\x12\x1c\n\x18GATEWAY_TYPE_UNSPECIFIED\x10\x00\x12\x0b\n\x07GATEWAY\x10\x01\x12\x0f\n\x0bNON_GATEWAY\x10\x02*\x91\x01\n\x11GatewayAuthMethod\x12#\n\x1fGATEWAY_AUTH_METHOD_UNSPECIFIED\x10\x00\x12\x14\n\x10\x41SSOCIATION_ONLY\x10\x01\x12\x1a\n\x16\x44\x45VICE_AUTH_TOKEN_ONLY\x10\x02\x12%\n!ASSOCIATION_AND_DEVICE_AUTH_TOKEN\x10\x03*e\n\x1aPublicKeyCertificateFormat\x12-\n)UNSPECIFIED_PUBLIC_KEY_CERTIFICATE_FORMAT\x10\x00\x12\x18\n\x14X509_CERTIFICATE_PEM\x10\x01*v\n\x0fPublicKeyFormat\x12!\n\x1dUNSPECIFIED_PUBLIC_KEY_FORMAT\x10\x00\x12\x0b\n\x07RSA_PEM\x10\x03\x12\x10\n\x0cRSA_X509_PEM\x10\x01\x12\r\n\tES256_PEM\x10\x02\x12\x12\n\x0e\x45S256_X509_PEM\x10\x04\x42\x66\n\x17\x63om.google.cloud.iot.v1B\x0eResourcesProtoP\x01Z6google.golang.org/genproto/googleapis/cloud/iot/v1;iot\xf8\x01\x01\x62\x06proto3', - dependencies=[ - google_dot_api_dot_resource__pb2.DESCRIPTOR, - google_dot_protobuf_dot_timestamp__pb2.DESCRIPTOR, - google_dot_rpc_dot_status__pb2.DESCRIPTOR, - ], -) - -_MQTTSTATE = _descriptor.EnumDescriptor( - name="MqttState", - full_name="google.cloud.iot.v1.MqttState", - filename=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - values=[ - _descriptor.EnumValueDescriptor( - name="MQTT_STATE_UNSPECIFIED", - index=0, - number=0, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="MQTT_ENABLED", - index=1, - number=1, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="MQTT_DISABLED", - index=2, - number=2, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - ], - containing_type=None, - serialized_options=None, - serialized_start=3144, - serialized_end=3220, -) -_sym_db.RegisterEnumDescriptor(_MQTTSTATE) - -MqttState = enum_type_wrapper.EnumTypeWrapper(_MQTTSTATE) -_HTTPSTATE = _descriptor.EnumDescriptor( - name="HttpState", - full_name="google.cloud.iot.v1.HttpState", - filename=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - values=[ - _descriptor.EnumValueDescriptor( - name="HTTP_STATE_UNSPECIFIED", - index=0, - number=0, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="HTTP_ENABLED", - index=1, - number=1, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="HTTP_DISABLED", - index=2, - number=2, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - ], - containing_type=None, - serialized_options=None, - serialized_start=3222, - serialized_end=3298, -) -_sym_db.RegisterEnumDescriptor(_HTTPSTATE) - -HttpState = enum_type_wrapper.EnumTypeWrapper(_HTTPSTATE) -_LOGLEVEL = _descriptor.EnumDescriptor( - name="LogLevel", - full_name="google.cloud.iot.v1.LogLevel", - filename=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - values=[ - _descriptor.EnumValueDescriptor( - name="LOG_LEVEL_UNSPECIFIED", - index=0, - number=0, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="NONE", - index=1, - number=10, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="ERROR", - index=2, - number=20, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="INFO", - index=3, - number=30, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="DEBUG", - index=4, - number=40, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - ], - containing_type=None, - serialized_options=None, - serialized_start=3300, - serialized_end=3379, -) -_sym_db.RegisterEnumDescriptor(_LOGLEVEL) - -LogLevel = enum_type_wrapper.EnumTypeWrapper(_LOGLEVEL) -_GATEWAYTYPE = _descriptor.EnumDescriptor( - name="GatewayType", - full_name="google.cloud.iot.v1.GatewayType", - filename=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - values=[ - _descriptor.EnumValueDescriptor( - name="GATEWAY_TYPE_UNSPECIFIED", - index=0, - number=0, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="GATEWAY", - index=1, - number=1, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="NON_GATEWAY", - index=2, - number=2, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - ], - containing_type=None, - serialized_options=None, - serialized_start=3381, - serialized_end=3454, -) -_sym_db.RegisterEnumDescriptor(_GATEWAYTYPE) - -GatewayType = enum_type_wrapper.EnumTypeWrapper(_GATEWAYTYPE) -_GATEWAYAUTHMETHOD = _descriptor.EnumDescriptor( - name="GatewayAuthMethod", - full_name="google.cloud.iot.v1.GatewayAuthMethod", - filename=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - values=[ - _descriptor.EnumValueDescriptor( - name="GATEWAY_AUTH_METHOD_UNSPECIFIED", - index=0, - number=0, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="ASSOCIATION_ONLY", - index=1, - number=1, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="DEVICE_AUTH_TOKEN_ONLY", - index=2, - number=2, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="ASSOCIATION_AND_DEVICE_AUTH_TOKEN", - index=3, - number=3, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - ], - containing_type=None, - serialized_options=None, - serialized_start=3457, - serialized_end=3602, -) -_sym_db.RegisterEnumDescriptor(_GATEWAYAUTHMETHOD) - -GatewayAuthMethod = enum_type_wrapper.EnumTypeWrapper(_GATEWAYAUTHMETHOD) -_PUBLICKEYCERTIFICATEFORMAT = _descriptor.EnumDescriptor( - name="PublicKeyCertificateFormat", - full_name="google.cloud.iot.v1.PublicKeyCertificateFormat", - filename=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - values=[ - _descriptor.EnumValueDescriptor( - name="UNSPECIFIED_PUBLIC_KEY_CERTIFICATE_FORMAT", - index=0, - number=0, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="X509_CERTIFICATE_PEM", - index=1, - number=1, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - ], - containing_type=None, - serialized_options=None, - serialized_start=3604, - serialized_end=3705, -) -_sym_db.RegisterEnumDescriptor(_PUBLICKEYCERTIFICATEFORMAT) - -PublicKeyCertificateFormat = enum_type_wrapper.EnumTypeWrapper( - _PUBLICKEYCERTIFICATEFORMAT -) -_PUBLICKEYFORMAT = _descriptor.EnumDescriptor( - name="PublicKeyFormat", - full_name="google.cloud.iot.v1.PublicKeyFormat", - filename=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - values=[ - _descriptor.EnumValueDescriptor( - name="UNSPECIFIED_PUBLIC_KEY_FORMAT", - index=0, - number=0, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="RSA_PEM", - index=1, - number=3, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="RSA_X509_PEM", - index=2, - number=1, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="ES256_PEM", - index=3, - number=2, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="ES256_X509_PEM", - index=4, - number=4, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - ], - containing_type=None, - serialized_options=None, - serialized_start=3707, - serialized_end=3825, -) -_sym_db.RegisterEnumDescriptor(_PUBLICKEYFORMAT) - -PublicKeyFormat = enum_type_wrapper.EnumTypeWrapper(_PUBLICKEYFORMAT) -MQTT_STATE_UNSPECIFIED = 0 -MQTT_ENABLED = 1 -MQTT_DISABLED = 2 -HTTP_STATE_UNSPECIFIED = 0 -HTTP_ENABLED = 1 -HTTP_DISABLED = 2 -LOG_LEVEL_UNSPECIFIED = 0 -NONE = 10 -ERROR = 20 -INFO = 30 -DEBUG = 40 -GATEWAY_TYPE_UNSPECIFIED = 0 -GATEWAY = 1 -NON_GATEWAY = 2 -GATEWAY_AUTH_METHOD_UNSPECIFIED = 0 -ASSOCIATION_ONLY = 1 -DEVICE_AUTH_TOKEN_ONLY = 2 -ASSOCIATION_AND_DEVICE_AUTH_TOKEN = 3 -UNSPECIFIED_PUBLIC_KEY_CERTIFICATE_FORMAT = 0 -X509_CERTIFICATE_PEM = 1 -UNSPECIFIED_PUBLIC_KEY_FORMAT = 0 -RSA_PEM = 3 -RSA_X509_PEM = 1 -ES256_PEM = 2 -ES256_X509_PEM = 4 - - -_DEVICE_METADATAENTRY = _descriptor.Descriptor( - name="MetadataEntry", - full_name="google.cloud.iot.v1.Device.MetadataEntry", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="key", - full_name="google.cloud.iot.v1.Device.MetadataEntry.key", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="value", - full_name="google.cloud.iot.v1.Device.MetadataEntry.value", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=b"8\001", - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=932, - serialized_end=979, -) - -_DEVICE = _descriptor.Descriptor( - name="Device", - full_name="google.cloud.iot.v1.Device", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="id", - full_name="google.cloud.iot.v1.Device.id", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.iot.v1.Device.name", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="num_id", - full_name="google.cloud.iot.v1.Device.num_id", - index=2, - number=3, - type=4, - cpp_type=4, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="credentials", - full_name="google.cloud.iot.v1.Device.credentials", - index=3, - number=12, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="last_heartbeat_time", - full_name="google.cloud.iot.v1.Device.last_heartbeat_time", - index=4, - number=7, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="last_event_time", - full_name="google.cloud.iot.v1.Device.last_event_time", - index=5, - number=8, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="last_state_time", - full_name="google.cloud.iot.v1.Device.last_state_time", - index=6, - number=20, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="last_config_ack_time", - full_name="google.cloud.iot.v1.Device.last_config_ack_time", - index=7, - number=14, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="last_config_send_time", - full_name="google.cloud.iot.v1.Device.last_config_send_time", - index=8, - number=18, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="blocked", - full_name="google.cloud.iot.v1.Device.blocked", - index=9, - number=19, - type=8, - cpp_type=7, - label=1, - has_default_value=False, - default_value=False, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="last_error_time", - full_name="google.cloud.iot.v1.Device.last_error_time", - index=10, - number=10, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="last_error_status", - full_name="google.cloud.iot.v1.Device.last_error_status", - index=11, - number=11, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="config", - full_name="google.cloud.iot.v1.Device.config", - index=12, - number=13, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="state", - full_name="google.cloud.iot.v1.Device.state", - index=13, - number=16, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="log_level", - full_name="google.cloud.iot.v1.Device.log_level", - index=14, - number=21, - type=14, - cpp_type=8, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="metadata", - full_name="google.cloud.iot.v1.Device.metadata", - index=15, - number=17, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="gateway_config", - full_name="google.cloud.iot.v1.Device.gateway_config", - index=16, - number=24, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[_DEVICE_METADATAENTRY,], - enum_types=[], - serialized_options=b"\352Ap\n\036cloudiot.googleapis.com/Device\022Nprojects/{project}/locations/{location}/registries/{registry}/devices/{device}", - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=152, - serialized_end=1096, -) - - -_GATEWAYCONFIG = _descriptor.Descriptor( - name="GatewayConfig", - full_name="google.cloud.iot.v1.GatewayConfig", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="gateway_type", - full_name="google.cloud.iot.v1.GatewayConfig.gateway_type", - index=0, - number=1, - type=14, - cpp_type=8, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="gateway_auth_method", - full_name="google.cloud.iot.v1.GatewayConfig.gateway_auth_method", - index=1, - number=2, - type=14, - cpp_type=8, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="last_accessed_gateway_id", - full_name="google.cloud.iot.v1.GatewayConfig.last_accessed_gateway_id", - index=2, - number=3, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="last_accessed_gateway_time", - full_name="google.cloud.iot.v1.GatewayConfig.last_accessed_gateway_time", - index=3, - number=4, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1099, - serialized_end=1337, -) - - -_DEVICEREGISTRY = _descriptor.Descriptor( - name="DeviceRegistry", - full_name="google.cloud.iot.v1.DeviceRegistry", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="id", - full_name="google.cloud.iot.v1.DeviceRegistry.id", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.iot.v1.DeviceRegistry.name", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="event_notification_configs", - full_name="google.cloud.iot.v1.DeviceRegistry.event_notification_configs", - index=2, - number=10, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="state_notification_config", - full_name="google.cloud.iot.v1.DeviceRegistry.state_notification_config", - index=3, - number=7, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="mqtt_config", - full_name="google.cloud.iot.v1.DeviceRegistry.mqtt_config", - index=4, - number=4, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="http_config", - full_name="google.cloud.iot.v1.DeviceRegistry.http_config", - index=5, - number=9, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="log_level", - full_name="google.cloud.iot.v1.DeviceRegistry.log_level", - index=6, - number=11, - type=14, - cpp_type=8, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="credentials", - full_name="google.cloud.iot.v1.DeviceRegistry.credentials", - index=7, - number=8, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=b"\352Aa\n cloudiot.googleapis.com/Registry\022=projects/{project}/locations/{location}/registries/{registry}", - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1340, - serialized_end=1867, -) - - -_MQTTCONFIG = _descriptor.Descriptor( - name="MqttConfig", - full_name="google.cloud.iot.v1.MqttConfig", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="mqtt_enabled_state", - full_name="google.cloud.iot.v1.MqttConfig.mqtt_enabled_state", - index=0, - number=1, - type=14, - cpp_type=8, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1869, - serialized_end=1941, -) - - -_HTTPCONFIG = _descriptor.Descriptor( - name="HttpConfig", - full_name="google.cloud.iot.v1.HttpConfig", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="http_enabled_state", - full_name="google.cloud.iot.v1.HttpConfig.http_enabled_state", - index=0, - number=1, - type=14, - cpp_type=8, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1943, - serialized_end=2015, -) - - -_EVENTNOTIFICATIONCONFIG = _descriptor.Descriptor( - name="EventNotificationConfig", - full_name="google.cloud.iot.v1.EventNotificationConfig", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="subfolder_matches", - full_name="google.cloud.iot.v1.EventNotificationConfig.subfolder_matches", - index=0, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="pubsub_topic_name", - full_name="google.cloud.iot.v1.EventNotificationConfig.pubsub_topic_name", - index=1, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=2017, - serialized_end=2096, -) - - -_STATENOTIFICATIONCONFIG = _descriptor.Descriptor( - name="StateNotificationConfig", - full_name="google.cloud.iot.v1.StateNotificationConfig", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="pubsub_topic_name", - full_name="google.cloud.iot.v1.StateNotificationConfig.pubsub_topic_name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=2098, - serialized_end=2150, -) - - -_REGISTRYCREDENTIAL = _descriptor.Descriptor( - name="RegistryCredential", - full_name="google.cloud.iot.v1.RegistryCredential", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="public_key_certificate", - full_name="google.cloud.iot.v1.RegistryCredential.public_key_certificate", - index=0, - number=1, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[ - _descriptor.OneofDescriptor( - name="credential", - full_name="google.cloud.iot.v1.RegistryCredential.credential", - index=0, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[], - ), - ], - serialized_start=2152, - serialized_end=2263, -) - - -_X509CERTIFICATEDETAILS = _descriptor.Descriptor( - name="X509CertificateDetails", - full_name="google.cloud.iot.v1.X509CertificateDetails", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="issuer", - full_name="google.cloud.iot.v1.X509CertificateDetails.issuer", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="subject", - full_name="google.cloud.iot.v1.X509CertificateDetails.subject", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="start_time", - full_name="google.cloud.iot.v1.X509CertificateDetails.start_time", - index=2, - number=3, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="expiry_time", - full_name="google.cloud.iot.v1.X509CertificateDetails.expiry_time", - index=3, - number=4, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="signature_algorithm", - full_name="google.cloud.iot.v1.X509CertificateDetails.signature_algorithm", - index=4, - number=5, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="public_key_type", - full_name="google.cloud.iot.v1.X509CertificateDetails.public_key_type", - index=5, - number=6, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=2266, - serialized_end=2474, -) - - -_PUBLICKEYCERTIFICATE = _descriptor.Descriptor( - name="PublicKeyCertificate", - full_name="google.cloud.iot.v1.PublicKeyCertificate", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="format", - full_name="google.cloud.iot.v1.PublicKeyCertificate.format", - index=0, - number=1, - type=14, - cpp_type=8, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="certificate", - full_name="google.cloud.iot.v1.PublicKeyCertificate.certificate", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="x509_details", - full_name="google.cloud.iot.v1.PublicKeyCertificate.x509_details", - index=2, - number=3, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=2477, - serialized_end=2652, -) - - -_DEVICECREDENTIAL = _descriptor.Descriptor( - name="DeviceCredential", - full_name="google.cloud.iot.v1.DeviceCredential", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="public_key", - full_name="google.cloud.iot.v1.DeviceCredential.public_key", - index=0, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="expiration_time", - full_name="google.cloud.iot.v1.DeviceCredential.expiration_time", - index=1, - number=6, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[ - _descriptor.OneofDescriptor( - name="credential", - full_name="google.cloud.iot.v1.DeviceCredential.credential", - index=0, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[], - ), - ], - serialized_start=2655, - serialized_end=2804, -) - - -_PUBLICKEYCREDENTIAL = _descriptor.Descriptor( - name="PublicKeyCredential", - full_name="google.cloud.iot.v1.PublicKeyCredential", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="format", - full_name="google.cloud.iot.v1.PublicKeyCredential.format", - index=0, - number=1, - type=14, - cpp_type=8, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="key", - full_name="google.cloud.iot.v1.PublicKeyCredential.key", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=2806, - serialized_end=2894, -) - - -_DEVICECONFIG = _descriptor.Descriptor( - name="DeviceConfig", - full_name="google.cloud.iot.v1.DeviceConfig", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="version", - full_name="google.cloud.iot.v1.DeviceConfig.version", - index=0, - number=1, - type=3, - cpp_type=2, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="cloud_update_time", - full_name="google.cloud.iot.v1.DeviceConfig.cloud_update_time", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="device_ack_time", - full_name="google.cloud.iot.v1.DeviceConfig.device_ack_time", - index=2, - number=3, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="binary_data", - full_name="google.cloud.iot.v1.DeviceConfig.binary_data", - index=3, - number=4, - type=12, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"", - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=2897, - serialized_end=3057, -) - - -_DEVICESTATE = _descriptor.Descriptor( - name="DeviceState", - full_name="google.cloud.iot.v1.DeviceState", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="update_time", - full_name="google.cloud.iot.v1.DeviceState.update_time", - index=0, - number=1, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="binary_data", - full_name="google.cloud.iot.v1.DeviceState.binary_data", - index=1, - number=2, - type=12, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"", - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=3059, - serialized_end=3142, -) - -_DEVICE_METADATAENTRY.containing_type = _DEVICE -_DEVICE.fields_by_name["credentials"].message_type = _DEVICECREDENTIAL -_DEVICE.fields_by_name[ - "last_heartbeat_time" -].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP -_DEVICE.fields_by_name[ - "last_event_time" -].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP -_DEVICE.fields_by_name[ - "last_state_time" -].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP -_DEVICE.fields_by_name[ - "last_config_ack_time" -].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP -_DEVICE.fields_by_name[ - "last_config_send_time" -].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP -_DEVICE.fields_by_name[ - "last_error_time" -].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP -_DEVICE.fields_by_name[ - "last_error_status" -].message_type = google_dot_rpc_dot_status__pb2._STATUS -_DEVICE.fields_by_name["config"].message_type = _DEVICECONFIG -_DEVICE.fields_by_name["state"].message_type = _DEVICESTATE -_DEVICE.fields_by_name["log_level"].enum_type = _LOGLEVEL -_DEVICE.fields_by_name["metadata"].message_type = _DEVICE_METADATAENTRY -_DEVICE.fields_by_name["gateway_config"].message_type = _GATEWAYCONFIG -_GATEWAYCONFIG.fields_by_name["gateway_type"].enum_type = _GATEWAYTYPE -_GATEWAYCONFIG.fields_by_name["gateway_auth_method"].enum_type = _GATEWAYAUTHMETHOD -_GATEWAYCONFIG.fields_by_name[ - "last_accessed_gateway_time" -].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP -_DEVICEREGISTRY.fields_by_name[ - "event_notification_configs" -].message_type = _EVENTNOTIFICATIONCONFIG -_DEVICEREGISTRY.fields_by_name[ - "state_notification_config" -].message_type = _STATENOTIFICATIONCONFIG -_DEVICEREGISTRY.fields_by_name["mqtt_config"].message_type = _MQTTCONFIG -_DEVICEREGISTRY.fields_by_name["http_config"].message_type = _HTTPCONFIG -_DEVICEREGISTRY.fields_by_name["log_level"].enum_type = _LOGLEVEL -_DEVICEREGISTRY.fields_by_name["credentials"].message_type = _REGISTRYCREDENTIAL -_MQTTCONFIG.fields_by_name["mqtt_enabled_state"].enum_type = _MQTTSTATE -_HTTPCONFIG.fields_by_name["http_enabled_state"].enum_type = _HTTPSTATE -_REGISTRYCREDENTIAL.fields_by_name[ - "public_key_certificate" -].message_type = _PUBLICKEYCERTIFICATE -_REGISTRYCREDENTIAL.oneofs_by_name["credential"].fields.append( - _REGISTRYCREDENTIAL.fields_by_name["public_key_certificate"] -) -_REGISTRYCREDENTIAL.fields_by_name[ - "public_key_certificate" -].containing_oneof = _REGISTRYCREDENTIAL.oneofs_by_name["credential"] -_X509CERTIFICATEDETAILS.fields_by_name[ - "start_time" -].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP -_X509CERTIFICATEDETAILS.fields_by_name[ - "expiry_time" -].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP -_PUBLICKEYCERTIFICATE.fields_by_name["format"].enum_type = _PUBLICKEYCERTIFICATEFORMAT -_PUBLICKEYCERTIFICATE.fields_by_name[ - "x509_details" -].message_type = _X509CERTIFICATEDETAILS -_DEVICECREDENTIAL.fields_by_name["public_key"].message_type = _PUBLICKEYCREDENTIAL -_DEVICECREDENTIAL.fields_by_name[ - "expiration_time" -].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP -_DEVICECREDENTIAL.oneofs_by_name["credential"].fields.append( - _DEVICECREDENTIAL.fields_by_name["public_key"] -) -_DEVICECREDENTIAL.fields_by_name[ - "public_key" -].containing_oneof = _DEVICECREDENTIAL.oneofs_by_name["credential"] -_PUBLICKEYCREDENTIAL.fields_by_name["format"].enum_type = _PUBLICKEYFORMAT -_DEVICECONFIG.fields_by_name[ - "cloud_update_time" -].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP -_DEVICECONFIG.fields_by_name[ - "device_ack_time" -].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP -_DEVICESTATE.fields_by_name[ - "update_time" -].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP -DESCRIPTOR.message_types_by_name["Device"] = _DEVICE -DESCRIPTOR.message_types_by_name["GatewayConfig"] = _GATEWAYCONFIG -DESCRIPTOR.message_types_by_name["DeviceRegistry"] = _DEVICEREGISTRY -DESCRIPTOR.message_types_by_name["MqttConfig"] = _MQTTCONFIG -DESCRIPTOR.message_types_by_name["HttpConfig"] = _HTTPCONFIG -DESCRIPTOR.message_types_by_name["EventNotificationConfig"] = _EVENTNOTIFICATIONCONFIG -DESCRIPTOR.message_types_by_name["StateNotificationConfig"] = _STATENOTIFICATIONCONFIG -DESCRIPTOR.message_types_by_name["RegistryCredential"] = _REGISTRYCREDENTIAL -DESCRIPTOR.message_types_by_name["X509CertificateDetails"] = _X509CERTIFICATEDETAILS -DESCRIPTOR.message_types_by_name["PublicKeyCertificate"] = _PUBLICKEYCERTIFICATE -DESCRIPTOR.message_types_by_name["DeviceCredential"] = _DEVICECREDENTIAL -DESCRIPTOR.message_types_by_name["PublicKeyCredential"] = _PUBLICKEYCREDENTIAL -DESCRIPTOR.message_types_by_name["DeviceConfig"] = _DEVICECONFIG -DESCRIPTOR.message_types_by_name["DeviceState"] = _DEVICESTATE -DESCRIPTOR.enum_types_by_name["MqttState"] = _MQTTSTATE -DESCRIPTOR.enum_types_by_name["HttpState"] = _HTTPSTATE -DESCRIPTOR.enum_types_by_name["LogLevel"] = _LOGLEVEL -DESCRIPTOR.enum_types_by_name["GatewayType"] = _GATEWAYTYPE -DESCRIPTOR.enum_types_by_name["GatewayAuthMethod"] = _GATEWAYAUTHMETHOD -DESCRIPTOR.enum_types_by_name[ - "PublicKeyCertificateFormat" -] = _PUBLICKEYCERTIFICATEFORMAT -DESCRIPTOR.enum_types_by_name["PublicKeyFormat"] = _PUBLICKEYFORMAT -_sym_db.RegisterFileDescriptor(DESCRIPTOR) - -Device = _reflection.GeneratedProtocolMessageType( - "Device", - (_message.Message,), - { - "MetadataEntry": _reflection.GeneratedProtocolMessageType( - "MetadataEntry", - (_message.Message,), - { - "DESCRIPTOR": _DEVICE_METADATAENTRY, - "__module__": "google.cloud.iot_v1.proto.resources_pb2" - # @@protoc_insertion_point(class_scope:google.cloud.iot.v1.Device.MetadataEntry) - }, - ), - "DESCRIPTOR": _DEVICE, - "__module__": "google.cloud.iot_v1.proto.resources_pb2", - "__doc__": """The device resource. - - Attributes: - id: - The user-defined device identifier. The device ID must be - unique within a device registry. - name: - The resource path name. For example, - ``projects/p1/locations/us- - central1/registries/registry0/devices/dev0`` or - ``projects/p1/locations/us- - central1/registries/registry0/devices/{num_id}``. When - ``name`` is populated as a response from the service, it - always ends in the device numeric ID. - num_id: - [Output only] A server-defined unique numeric ID for the - device. This is a more compact way to identify devices, and it - is globally unique. - credentials: - The credentials used to authenticate this device. To allow - credential rotation without interruption, multiple device - credentials can be bound to this device. No more than 3 - credentials can be bound to a single device at a time. When - new credentials are added to a device, they are verified - against the registry credentials. For details, see the - description of the ``DeviceRegistry.credentials`` field. - last_heartbeat_time: - [Output only] The last time an MQTT ``PINGREQ`` was received. - This field applies only to devices connecting through MQTT. - MQTT clients usually only send ``PINGREQ`` messages if the - connection is idle, and no other messages have been sent. - Timestamps are periodically collected and written to storage; - they may be stale by a few minutes. - last_event_time: - [Output only] The last time a telemetry event was received. - Timestamps are periodically collected and written to storage; - they may be stale by a few minutes. - last_state_time: - [Output only] The last time a state event was received. - Timestamps are periodically collected and written to storage; - they may be stale by a few minutes. - last_config_ack_time: - [Output only] The last time a cloud-to-device config version - acknowledgment was received from the device. This field is - only for configurations sent through MQTT. - last_config_send_time: - [Output only] The last time a cloud-to-device config version - was sent to the device. - blocked: - If a device is blocked, connections or requests from this - device will fail. Can be used to temporarily prevent the - device from connecting if, for example, the sensor is - generating bad data and needs maintenance. - last_error_time: - [Output only] The time the most recent error occurred, such as - a failure to publish to Cloud Pub/Sub. This field is the - timestamp of ‘last_error_status’. - last_error_status: - [Output only] The error message of the most recent error, such - as a failure to publish to Cloud Pub/Sub. ‘last_error_time’ is - the timestamp of this field. If no errors have occurred, this - field has an empty message and the status code 0 == OK. - Otherwise, this field is expected to have a status code other - than OK. - config: - The most recent device configuration, which is eventually sent - from Cloud IoT Core to the device. If not present on creation, - the configuration will be initialized with an empty payload - and version value of ``1``. To update this field after - creation, use the ``DeviceManager.ModifyCloudToDeviceConfig`` - method. - state: - [Output only] The state most recently received from the - device. If no state has been reported, this field is not - present. - log_level: - \ **Beta Feature** The logging verbosity for device activity. - If unspecified, DeviceRegistry.log_level will be used. - metadata: - The metadata key-value pairs assigned to the device. This - metadata is not interpreted or indexed by Cloud IoT Core. It - can be used to add contextual information for the device. - Keys must conform to the regular expression - [a-zA-Z][a-zA-Z0-9-_.+~%]+ and be less than 128 bytes in - length. Values are free-form strings. Each value must be less - than or equal to 32 KB in size. The total size of all keys - and values must be less than 256 KB, and the maximum number of - key-value pairs is 500. - gateway_config: - Gateway-related configuration and state. - """, - # @@protoc_insertion_point(class_scope:google.cloud.iot.v1.Device) - }, -) -_sym_db.RegisterMessage(Device) -_sym_db.RegisterMessage(Device.MetadataEntry) - -GatewayConfig = _reflection.GeneratedProtocolMessageType( - "GatewayConfig", - (_message.Message,), - { - "DESCRIPTOR": _GATEWAYCONFIG, - "__module__": "google.cloud.iot_v1.proto.resources_pb2", - "__doc__": """Gateway-related configuration and state. - - Attributes: - gateway_type: - Indicates whether the device is a gateway. - gateway_auth_method: - Indicates how to authorize and/or authenticate devices to - access the gateway. - last_accessed_gateway_id: - [Output only] The ID of the gateway the device accessed most - recently. - last_accessed_gateway_time: - [Output only] The most recent time at which the device - accessed the gateway specified in ``last_accessed_gateway``. - """, - # @@protoc_insertion_point(class_scope:google.cloud.iot.v1.GatewayConfig) - }, -) -_sym_db.RegisterMessage(GatewayConfig) - -DeviceRegistry = _reflection.GeneratedProtocolMessageType( - "DeviceRegistry", - (_message.Message,), - { - "DESCRIPTOR": _DEVICEREGISTRY, - "__module__": "google.cloud.iot_v1.proto.resources_pb2", - "__doc__": """A container for a group of devices. - - Attributes: - id: - The identifier of this device registry. For example, - ``myRegistry``. - name: - The resource path name. For example, ``projects/example- - project/locations/us-central1/registries/my-registry``. - event_notification_configs: - The configuration for notification of telemetry events - received from the device. All telemetry events that were - successfully published by the device and acknowledged by Cloud - IoT Core are guaranteed to be delivered to Cloud Pub/Sub. If - multiple configurations match a message, only the first - matching configuration is used. If you try to publish a device - telemetry event using MQTT without specifying a Cloud Pub/Sub - topic for the device’s registry, the connection closes - automatically. If you try to do so using an HTTP connection, - an error is returned. Up to 10 configurations may be provided. - state_notification_config: - The configuration for notification of new states received from - the device. State updates are guaranteed to be stored in the - state history, but notifications to Cloud Pub/Sub are not - guaranteed. For example, if permissions are misconfigured or - the specified topic doesn’t exist, no notification will be - published but the state will still be stored in Cloud IoT - Core. - mqtt_config: - The MQTT configuration for this device registry. - http_config: - The DeviceService (HTTP) configuration for this device - registry. - log_level: - \ **Beta Feature** The default logging verbosity for activity - from devices in this registry. The verbosity level can be - overridden by Device.log_level. - credentials: - The credentials used to verify the device credentials. No more - than 10 credentials can be bound to a single registry at a - time. The verification process occurs at the time of device - creation or update. If this field is empty, no verification is - performed. Otherwise, the credentials of a newly created - device or added credentials of an updated device should be - signed with one of these registry credentials. Note, however, - that existing devices will never be affected by modifications - to this list of credentials: after a device has been - successfully created in a registry, it should be able to - connect even if its registry credentials are revoked, deleted, - or modified. - """, - # @@protoc_insertion_point(class_scope:google.cloud.iot.v1.DeviceRegistry) - }, -) -_sym_db.RegisterMessage(DeviceRegistry) - -MqttConfig = _reflection.GeneratedProtocolMessageType( - "MqttConfig", - (_message.Message,), - { - "DESCRIPTOR": _MQTTCONFIG, - "__module__": "google.cloud.iot_v1.proto.resources_pb2", - "__doc__": """The configuration of MQTT for a device registry. - - Attributes: - mqtt_enabled_state: - If enabled, allows connections using the MQTT protocol. - Otherwise, MQTT connections to this registry will fail. - """, - # @@protoc_insertion_point(class_scope:google.cloud.iot.v1.MqttConfig) - }, -) -_sym_db.RegisterMessage(MqttConfig) - -HttpConfig = _reflection.GeneratedProtocolMessageType( - "HttpConfig", - (_message.Message,), - { - "DESCRIPTOR": _HTTPCONFIG, - "__module__": "google.cloud.iot_v1.proto.resources_pb2", - "__doc__": """The configuration of the HTTP bridge for a device registry. - - Attributes: - http_enabled_state: - If enabled, allows devices to use DeviceService via the HTTP - protocol. Otherwise, any requests to DeviceService will fail - for this registry. - """, - # @@protoc_insertion_point(class_scope:google.cloud.iot.v1.HttpConfig) - }, -) -_sym_db.RegisterMessage(HttpConfig) - -EventNotificationConfig = _reflection.GeneratedProtocolMessageType( - "EventNotificationConfig", - (_message.Message,), - { - "DESCRIPTOR": _EVENTNOTIFICATIONCONFIG, - "__module__": "google.cloud.iot_v1.proto.resources_pb2", - "__doc__": """The configuration for forwarding telemetry events. - - Attributes: - subfolder_matches: - If the subfolder name matches this string exactly, this - configuration will be used. The string must not include the - leading ‘/’ character. If empty, all strings are matched. This - field is used only for telemetry events; subfolders are not - supported for state changes. - pubsub_topic_name: - A Cloud Pub/Sub topic name. For example, - ``projects/myProject/topics/deviceEvents``. - """, - # @@protoc_insertion_point(class_scope:google.cloud.iot.v1.EventNotificationConfig) - }, -) -_sym_db.RegisterMessage(EventNotificationConfig) - -StateNotificationConfig = _reflection.GeneratedProtocolMessageType( - "StateNotificationConfig", - (_message.Message,), - { - "DESCRIPTOR": _STATENOTIFICATIONCONFIG, - "__module__": "google.cloud.iot_v1.proto.resources_pb2", - "__doc__": """The configuration for notification of new states received from the - device. - - Attributes: - pubsub_topic_name: - A Cloud Pub/Sub topic name. For example, - ``projects/myProject/topics/deviceEvents``. - """, - # @@protoc_insertion_point(class_scope:google.cloud.iot.v1.StateNotificationConfig) - }, -) -_sym_db.RegisterMessage(StateNotificationConfig) - -RegistryCredential = _reflection.GeneratedProtocolMessageType( - "RegistryCredential", - (_message.Message,), - { - "DESCRIPTOR": _REGISTRYCREDENTIAL, - "__module__": "google.cloud.iot_v1.proto.resources_pb2", - "__doc__": """A server-stored registry credential used to validate device - credentials. - - Attributes: - credential: - The credential data. Reserved for expansion in the future. - public_key_certificate: - A public key certificate used to verify the device - credentials. - """, - # @@protoc_insertion_point(class_scope:google.cloud.iot.v1.RegistryCredential) - }, -) -_sym_db.RegisterMessage(RegistryCredential) - -X509CertificateDetails = _reflection.GeneratedProtocolMessageType( - "X509CertificateDetails", - (_message.Message,), - { - "DESCRIPTOR": _X509CERTIFICATEDETAILS, - "__module__": "google.cloud.iot_v1.proto.resources_pb2", - "__doc__": """Details of an X.509 certificate. For informational purposes only. - - Attributes: - issuer: - The entity that signed the certificate. - subject: - The entity the certificate and public key belong to. - start_time: - The time the certificate becomes valid. - expiry_time: - The time the certificate becomes invalid. - signature_algorithm: - The algorithm used to sign the certificate. - public_key_type: - The type of public key in the certificate. - """, - # @@protoc_insertion_point(class_scope:google.cloud.iot.v1.X509CertificateDetails) - }, -) -_sym_db.RegisterMessage(X509CertificateDetails) - -PublicKeyCertificate = _reflection.GeneratedProtocolMessageType( - "PublicKeyCertificate", - (_message.Message,), - { - "DESCRIPTOR": _PUBLICKEYCERTIFICATE, - "__module__": "google.cloud.iot_v1.proto.resources_pb2", - "__doc__": """A public key certificate format and data. - - Attributes: - format: - The certificate format. - certificate: - The certificate data. - x509_details: - [Output only] The certificate details. Used only for X.509 - certificates. - """, - # @@protoc_insertion_point(class_scope:google.cloud.iot.v1.PublicKeyCertificate) - }, -) -_sym_db.RegisterMessage(PublicKeyCertificate) - -DeviceCredential = _reflection.GeneratedProtocolMessageType( - "DeviceCredential", - (_message.Message,), - { - "DESCRIPTOR": _DEVICECREDENTIAL, - "__module__": "google.cloud.iot_v1.proto.resources_pb2", - "__doc__": """A server-stored device credential used for authentication. - - Attributes: - credential: - The credential data. Reserved for expansion in the future. - public_key: - A public key used to verify the signature of JSON Web Tokens - (JWTs). When adding a new device credential, either via device - creation or via modifications, this public key credential may - be required to be signed by one of the registry level - certificates. More specifically, if the registry contains at - least one certificate, any new device credential must be - signed by one of the registry certificates. As a result, when - the registry contains certificates, only X.509 certificates - are accepted as device credentials. However, if the registry - does not contain a certificate, self-signed certificates and - public keys will be accepted. New device credentials must be - different from every registry-level certificate. - expiration_time: - [Optional] The time at which this credential becomes invalid. - This credential will be ignored for new client authentication - requests after this timestamp; however, it will not be - automatically deleted. - """, - # @@protoc_insertion_point(class_scope:google.cloud.iot.v1.DeviceCredential) - }, -) -_sym_db.RegisterMessage(DeviceCredential) - -PublicKeyCredential = _reflection.GeneratedProtocolMessageType( - "PublicKeyCredential", - (_message.Message,), - { - "DESCRIPTOR": _PUBLICKEYCREDENTIAL, - "__module__": "google.cloud.iot_v1.proto.resources_pb2", - "__doc__": """A public key format and data. - - Attributes: - format: - The format of the key. - key: - The key data. - """, - # @@protoc_insertion_point(class_scope:google.cloud.iot.v1.PublicKeyCredential) - }, -) -_sym_db.RegisterMessage(PublicKeyCredential) - -DeviceConfig = _reflection.GeneratedProtocolMessageType( - "DeviceConfig", - (_message.Message,), - { - "DESCRIPTOR": _DEVICECONFIG, - "__module__": "google.cloud.iot_v1.proto.resources_pb2", - "__doc__": """The device configuration. Eventually delivered to devices. - - Attributes: - version: - [Output only] The version of this update. The version number - is assigned by the server, and is always greater than 0 after - device creation. The version must be 0 on the ``CreateDevice`` - request if a ``config`` is specified; the response of - ``CreateDevice`` will always have a value of 1. - cloud_update_time: - [Output only] The time at which this configuration version was - updated in Cloud IoT Core. This timestamp is set by the - server. - device_ack_time: - [Output only] The time at which Cloud IoT Core received the - acknowledgment from the device, indicating that the device has - received this configuration version. If this field is not - present, the device has not yet acknowledged that it received - this version. Note that when the config was sent to the - device, many config versions may have been available in Cloud - IoT Core while the device was disconnected, and on connection, - only the latest version is sent to the device. Some versions - may never be sent to the device, and therefore are never - acknowledged. This timestamp is set by Cloud IoT Core. - binary_data: - The device configuration data. - """, - # @@protoc_insertion_point(class_scope:google.cloud.iot.v1.DeviceConfig) - }, -) -_sym_db.RegisterMessage(DeviceConfig) - -DeviceState = _reflection.GeneratedProtocolMessageType( - "DeviceState", - (_message.Message,), - { - "DESCRIPTOR": _DEVICESTATE, - "__module__": "google.cloud.iot_v1.proto.resources_pb2", - "__doc__": """The device state, as reported by the device. - - Attributes: - update_time: - [Output only] The time at which this state version was updated - in Cloud IoT Core. - binary_data: - The device state data. - """, - # @@protoc_insertion_point(class_scope:google.cloud.iot.v1.DeviceState) - }, -) -_sym_db.RegisterMessage(DeviceState) - - -DESCRIPTOR._options = None -_DEVICE_METADATAENTRY._options = None -_DEVICE._options = None -_DEVICEREGISTRY._options = None -# @@protoc_insertion_point(module_scope) diff --git a/google/cloud/iot_v1/proto/resources_pb2_grpc.py b/google/cloud/iot_v1/proto/resources_pb2_grpc.py deleted file mode 100644 index 07cb78fe..00000000 --- a/google/cloud/iot_v1/proto/resources_pb2_grpc.py +++ /dev/null @@ -1,2 +0,0 @@ -# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! -import grpc diff --git a/google/cloud/iot_v1/py.typed b/google/cloud/iot_v1/py.typed new file mode 100644 index 00000000..d89d40c8 --- /dev/null +++ b/google/cloud/iot_v1/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-iot package uses inline types. diff --git a/google/__init__.py b/google/cloud/iot_v1/services/__init__.py similarity index 66% rename from google/__init__.py rename to google/cloud/iot_v1/services/__init__.py index dd3a9f48..42ffdf2b 100644 --- a/google/__init__.py +++ b/google/cloud/iot_v1/services/__init__.py @@ -1,22 +1,16 @@ -# Copyright 2018 Google LLC +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # -# https://www.apache.org/licenses/LICENSE-2.0 +# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. - -try: - import pkg_resources - - pkg_resources.declare_namespace(__name__) -except ImportError: - import pkgutil - - __path__ = pkgutil.extend_path(__path__, __name__) +# diff --git a/google/cloud/__init__.py b/google/cloud/iot_v1/services/device_manager/__init__.py similarity index 65% rename from google/cloud/__init__.py rename to google/cloud/iot_v1/services/device_manager/__init__.py index dd3a9f48..52c82388 100644 --- a/google/cloud/__init__.py +++ b/google/cloud/iot_v1/services/device_manager/__init__.py @@ -1,22 +1,24 @@ -# Copyright 2018 Google LLC +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # -# https://www.apache.org/licenses/LICENSE-2.0 +# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. +# -try: - import pkg_resources - - pkg_resources.declare_namespace(__name__) -except ImportError: - import pkgutil +from .client import DeviceManagerClient +from .async_client import DeviceManagerAsyncClient - __path__ = pkgutil.extend_path(__path__, __name__) +__all__ = ( + "DeviceManagerClient", + "DeviceManagerAsyncClient", +) diff --git a/google/cloud/iot_v1/services/device_manager/async_client.py b/google/cloud/iot_v1/services/device_manager/async_client.py new file mode 100644 index 00000000..2b1bbd31 --- /dev/null +++ b/google/cloud/iot_v1/services/device_manager/async_client.py @@ -0,0 +1,1851 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from collections import OrderedDict +import functools +import re +from typing import Dict, Sequence, Tuple, Type, Union +import pkg_resources + +import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.iot_v1.services.device_manager import pagers +from google.cloud.iot_v1.types import device_manager +from google.cloud.iot_v1.types import resources +from google.iam.v1 import iam_policy_pb2 as iam_policy # type: ignore +from google.iam.v1 import policy_pb2 as policy # type: ignore +from google.protobuf import field_mask_pb2 as field_mask # type: ignore +from google.protobuf import timestamp_pb2 as timestamp # type: ignore +from google.rpc import status_pb2 as status # type: ignore + +from .transports.base import DeviceManagerTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import DeviceManagerGrpcAsyncIOTransport +from .client import DeviceManagerClient + + +class DeviceManagerAsyncClient: + """Internet of Things (IoT) service. Securely connect and manage + IoT devices. + """ + + _client: DeviceManagerClient + + DEFAULT_ENDPOINT = DeviceManagerClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = DeviceManagerClient.DEFAULT_MTLS_ENDPOINT + + registry_path = staticmethod(DeviceManagerClient.registry_path) + + device_path = staticmethod(DeviceManagerClient.device_path) + + from_service_account_file = DeviceManagerClient.from_service_account_file + from_service_account_json = from_service_account_file + + get_transport_class = functools.partial( + type(DeviceManagerClient).get_transport_class, type(DeviceManagerClient) + ) + + def __init__( + self, + *, + credentials: credentials.Credentials = None, + transport: Union[str, DeviceManagerTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the device manager client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.DeviceManagerTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint, this is the default value for + the environment variable) and "auto" (auto switch to the default + mTLS endpoint if client SSL credentials is present). However, + the ``api_endpoint`` property takes precedence if provided. + (2) The ``client_cert_source`` property is used to provide client + SSL credentials for mutual TLS transport. If not provided, the + default SSL credentials will be used if present. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + + self._client = DeviceManagerClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + ) + + async def create_device_registry( + self, + request: device_manager.CreateDeviceRegistryRequest = None, + *, + parent: str = None, + device_registry: resources.DeviceRegistry = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.DeviceRegistry: + r"""Creates a device registry that contains devices. + + Args: + request (:class:`~.device_manager.CreateDeviceRegistryRequest`): + The request object. Request for `CreateDeviceRegistry`. + parent (:class:`str`): + Required. The project and cloud region where this device + registry must be created. For example, + ``projects/example-project/locations/us-central1``. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + device_registry (:class:`~.resources.DeviceRegistry`): + Required. The device registry. The field ``name`` must + be empty. The server will generate that field from the + device registry ``id`` provided and the ``parent`` + field. + This corresponds to the ``device_registry`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.DeviceRegistry: + A container for a group of devices. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([parent, device_registry]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = device_manager.CreateDeviceRegistryRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + if device_registry is not None: + request.device_registry = device_registry + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_device_registry, + default_timeout=120.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def get_device_registry( + self, + request: device_manager.GetDeviceRegistryRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.DeviceRegistry: + r"""Gets a device registry configuration. + + Args: + request (:class:`~.device_manager.GetDeviceRegistryRequest`): + The request object. Request for `GetDeviceRegistry`. + name (:class:`str`): + Required. The name of the device registry. For example, + ``projects/example-project/locations/us-central1/registries/my-registry``. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.DeviceRegistry: + A container for a group of devices. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([name]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = device_manager.GetDeviceRegistryRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_device_registry, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + default_timeout=120.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def update_device_registry( + self, + request: device_manager.UpdateDeviceRegistryRequest = None, + *, + device_registry: resources.DeviceRegistry = None, + update_mask: field_mask.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.DeviceRegistry: + r"""Updates a device registry configuration. + + Args: + request (:class:`~.device_manager.UpdateDeviceRegistryRequest`): + The request object. Request for `UpdateDeviceRegistry`. + device_registry (:class:`~.resources.DeviceRegistry`): + Required. The new values for the device registry. The + ``id`` field must be empty, and the ``name`` field must + indicate the path of the resource. For example, + ``projects/example-project/locations/us-central1/registries/my-registry``. + This corresponds to the ``device_registry`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`~.field_mask.FieldMask`): + Required. Only updates the ``device_registry`` fields + indicated by this mask. The field mask must not be + empty, and it must not contain fields that are immutable + or only set by the server. Mutable top-level fields: + ``event_notification_config``, ``http_config``, + ``mqtt_config``, and ``state_notification_config``. + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.DeviceRegistry: + A container for a group of devices. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([device_registry, update_mask]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = device_manager.UpdateDeviceRegistryRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if device_registry is not None: + request.device_registry = device_registry + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_device_registry, + default_timeout=120.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("device_registry.name", request.device_registry.name),) + ), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def delete_device_registry( + self, + request: device_manager.DeleteDeviceRegistryRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a device registry configuration. + + Args: + request (:class:`~.device_manager.DeleteDeviceRegistryRequest`): + The request object. Request for `DeleteDeviceRegistry`. + name (:class:`str`): + Required. The name of the device registry. For example, + ``projects/example-project/locations/us-central1/registries/my-registry``. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([name]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = device_manager.DeleteDeviceRegistryRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.delete_device_registry, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + default_timeout=120.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + await rpc( + request, retry=retry, timeout=timeout, metadata=metadata, + ) + + async def list_device_registries( + self, + request: device_manager.ListDeviceRegistriesRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListDeviceRegistriesAsyncPager: + r"""Lists device registries. + + Args: + request (:class:`~.device_manager.ListDeviceRegistriesRequest`): + The request object. Request for `ListDeviceRegistries`. + parent (:class:`str`): + Required. The project and cloud region path. For + example, + ``projects/example-project/locations/us-central1``. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.pagers.ListDeviceRegistriesAsyncPager: + Response for ``ListDeviceRegistries``. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([parent]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = device_manager.ListDeviceRegistriesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_device_registries, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + default_timeout=120.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListDeviceRegistriesAsyncPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_device( + self, + request: device_manager.CreateDeviceRequest = None, + *, + parent: str = None, + device: resources.Device = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.Device: + r"""Creates a device in a device registry. + + Args: + request (:class:`~.device_manager.CreateDeviceRequest`): + The request object. Request for `CreateDevice`. + parent (:class:`str`): + Required. The name of the device registry where this + device should be created. For example, + ``projects/example-project/locations/us-central1/registries/my-registry``. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + device (:class:`~.resources.Device`): + Required. The device registration details. The field + ``name`` must be empty. The server generates ``name`` + from the device registry ``id`` and the ``parent`` + field. + This corresponds to the ``device`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.Device: + The device resource. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([parent, device]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = device_manager.CreateDeviceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + if device is not None: + request.device = device + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_device, + default_timeout=120.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def get_device( + self, + request: device_manager.GetDeviceRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.Device: + r"""Gets details about a device. + + Args: + request (:class:`~.device_manager.GetDeviceRequest`): + The request object. Request for `GetDevice`. + name (:class:`str`): + Required. The name of the device. For example, + ``projects/p0/locations/us-central1/registries/registry0/devices/device0`` + or + ``projects/p0/locations/us-central1/registries/registry0/devices/{num_id}``. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.Device: + The device resource. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([name]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = device_manager.GetDeviceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_device, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + default_timeout=120.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def update_device( + self, + request: device_manager.UpdateDeviceRequest = None, + *, + device: resources.Device = None, + update_mask: field_mask.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.Device: + r"""Updates a device. + + Args: + request (:class:`~.device_manager.UpdateDeviceRequest`): + The request object. Request for `UpdateDevice`. + device (:class:`~.resources.Device`): + Required. The new values for the device. The ``id`` and + ``num_id`` fields must be empty, and the field ``name`` + must specify the name path. For example, + ``projects/p0/locations/us-central1/registries/registry0/devices/device0``\ or + ``projects/p0/locations/us-central1/registries/registry0/devices/{num_id}``. + This corresponds to the ``device`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`~.field_mask.FieldMask`): + Required. Only updates the ``device`` fields indicated + by this mask. The field mask must not be empty, and it + must not contain fields that are immutable or only set + by the server. Mutable top-level fields: + ``credentials``, ``blocked``, and ``metadata`` + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.Device: + The device resource. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([device, update_mask]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = device_manager.UpdateDeviceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if device is not None: + request.device = device + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_device, + default_timeout=120.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("device.name", request.device.name),) + ), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def delete_device( + self, + request: device_manager.DeleteDeviceRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a device. + + Args: + request (:class:`~.device_manager.DeleteDeviceRequest`): + The request object. Request for `DeleteDevice`. + name (:class:`str`): + Required. The name of the device. For example, + ``projects/p0/locations/us-central1/registries/registry0/devices/device0`` + or + ``projects/p0/locations/us-central1/registries/registry0/devices/{num_id}``. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([name]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = device_manager.DeleteDeviceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.delete_device, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + default_timeout=120.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + await rpc( + request, retry=retry, timeout=timeout, metadata=metadata, + ) + + async def list_devices( + self, + request: device_manager.ListDevicesRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListDevicesAsyncPager: + r"""List devices in a device registry. + + Args: + request (:class:`~.device_manager.ListDevicesRequest`): + The request object. Request for `ListDevices`. + parent (:class:`str`): + Required. The device registry path. Required. For + example, + ``projects/my-project/locations/us-central1/registries/my-registry``. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.pagers.ListDevicesAsyncPager: + Response for ``ListDevices``. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([parent]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = device_manager.ListDevicesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_devices, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + default_timeout=120.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListDevicesAsyncPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + + async def modify_cloud_to_device_config( + self, + request: device_manager.ModifyCloudToDeviceConfigRequest = None, + *, + name: str = None, + binary_data: bytes = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.DeviceConfig: + r"""Modifies the configuration for the device, which is + eventually sent from the Cloud IoT Core servers. Returns + the modified configuration version and its metadata. + + Args: + request (:class:`~.device_manager.ModifyCloudToDeviceConfigRequest`): + The request object. Request for + `ModifyCloudToDeviceConfig`. + name (:class:`str`): + Required. The name of the device. For example, + ``projects/p0/locations/us-central1/registries/registry0/devices/device0`` + or + ``projects/p0/locations/us-central1/registries/registry0/devices/{num_id}``. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + binary_data (:class:`bytes`): + Required. The configuration data for + the device. + This corresponds to the ``binary_data`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.DeviceConfig: + The device configuration. Eventually + delivered to devices. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([name, binary_data]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = device_manager.ModifyCloudToDeviceConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + if binary_data is not None: + request.binary_data = binary_data + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.modify_cloud_to_device_config, + default_retry=retries.Retry( + initial=1.0, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ResourceExhausted, + exceptions.ServiceUnavailable, + exceptions.DeadlineExceeded, + ), + ), + default_timeout=120.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def list_device_config_versions( + self, + request: device_manager.ListDeviceConfigVersionsRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> device_manager.ListDeviceConfigVersionsResponse: + r"""Lists the last few versions of the device + configuration in descending order (i.e.: newest first). + + Args: + request (:class:`~.device_manager.ListDeviceConfigVersionsRequest`): + The request object. Request for + `ListDeviceConfigVersions`. + name (:class:`str`): + Required. The name of the device. For example, + ``projects/p0/locations/us-central1/registries/registry0/devices/device0`` + or + ``projects/p0/locations/us-central1/registries/registry0/devices/{num_id}``. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.device_manager.ListDeviceConfigVersionsResponse: + Response for ``ListDeviceConfigVersions``. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([name]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = device_manager.ListDeviceConfigVersionsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_device_config_versions, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + default_timeout=120.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def list_device_states( + self, + request: device_manager.ListDeviceStatesRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> device_manager.ListDeviceStatesResponse: + r"""Lists the last few versions of the device state in + descending order (i.e.: newest first). + + Args: + request (:class:`~.device_manager.ListDeviceStatesRequest`): + The request object. Request for `ListDeviceStates`. + name (:class:`str`): + Required. The name of the device. For example, + ``projects/p0/locations/us-central1/registries/registry0/devices/device0`` + or + ``projects/p0/locations/us-central1/registries/registry0/devices/{num_id}``. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.device_manager.ListDeviceStatesResponse: + Response for ``ListDeviceStates``. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([name]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = device_manager.ListDeviceStatesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_device_states, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + default_timeout=120.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def set_iam_policy( + self, + request: iam_policy.SetIamPolicyRequest = None, + *, + resource: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy.Policy: + r"""Sets the access control policy on the specified + resource. Replaces any existing policy. + + Args: + request (:class:`~.iam_policy.SetIamPolicyRequest`): + The request object. Request message for `SetIamPolicy` + method. + resource (:class:`str`): + REQUIRED: The resource for which the + policy is being specified. See the + operation documentation for the + appropriate value for this field. + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.policy.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([resource]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy.SetIamPolicyRequest(**request) + + elif not request: + request = iam_policy.SetIamPolicyRequest() + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if resource is not None: + request.resource = resource + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.set_iam_policy, + default_timeout=120.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def get_iam_policy( + self, + request: iam_policy.GetIamPolicyRequest = None, + *, + resource: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy.Policy: + r"""Gets the access control policy for a resource. + Returns an empty policy if the resource exists and does + not have a policy set. + + Args: + request (:class:`~.iam_policy.GetIamPolicyRequest`): + The request object. Request message for `GetIamPolicy` + method. + resource (:class:`str`): + REQUIRED: The resource for which the + policy is being requested. See the + operation documentation for the + appropriate value for this field. + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.policy.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([resource]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy.GetIamPolicyRequest(**request) + + elif not request: + request = iam_policy.GetIamPolicyRequest() + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if resource is not None: + request.resource = resource + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_iam_policy, + default_timeout=120.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def test_iam_permissions( + self, + request: iam_policy.TestIamPermissionsRequest = None, + *, + resource: str = None, + permissions: Sequence[str] = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam_policy.TestIamPermissionsResponse: + r"""Returns permissions that a caller has on the specified resource. + If the resource does not exist, this will return an empty set of + permissions, not a NOT_FOUND error. + + Args: + request (:class:`~.iam_policy.TestIamPermissionsRequest`): + The request object. Request message for + `TestIamPermissions` method. + resource (:class:`str`): + REQUIRED: The resource for which the + policy detail is being requested. See + the operation documentation for the + appropriate value for this field. + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + permissions (:class:`Sequence[str]`): + The set of permissions to check for the ``resource``. + Permissions with wildcards (such as '*' or 'storage.*') + are not allowed. For more information see `IAM + Overview `__. + This corresponds to the ``permissions`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.iam_policy.TestIamPermissionsResponse: + Response message for ``TestIamPermissions`` method. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([resource, permissions]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy.TestIamPermissionsRequest(**request) + + elif not request: + request = iam_policy.TestIamPermissionsRequest() + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if resource is not None: + request.resource = resource + + if permissions: + request.permissions.extend(permissions) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.test_iam_permissions, + default_timeout=120.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def send_command_to_device( + self, + request: device_manager.SendCommandToDeviceRequest = None, + *, + name: str = None, + binary_data: bytes = None, + subfolder: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> device_manager.SendCommandToDeviceResponse: + r"""Sends a command to the specified device. In order for a device + to be able to receive commands, it must: + + 1) be connected to Cloud IoT Core using the MQTT protocol, and + 2) be subscribed to the group of MQTT topics specified by + /devices/{device-id}/commands/#. This subscription will + receive commands at the top-level topic + /devices/{device-id}/commands as well as commands for + subfolders, like /devices/{device-id}/commands/subfolder. + Note that subscribing to specific subfolders is not + supported. If the command could not be delivered to the + device, this method will return an error; in particular, if + the device is not subscribed, this method will return + FAILED_PRECONDITION. Otherwise, this method will return OK. + If the subscription is QoS 1, at least once delivery will be + guaranteed; for QoS 0, no acknowledgment will be expected + from the device. + + Args: + request (:class:`~.device_manager.SendCommandToDeviceRequest`): + The request object. Request for `SendCommandToDevice`. + name (:class:`str`): + Required. The name of the device. For example, + ``projects/p0/locations/us-central1/registries/registry0/devices/device0`` + or + ``projects/p0/locations/us-central1/registries/registry0/devices/{num_id}``. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + binary_data (:class:`bytes`): + Required. The command data to send to + the device. + This corresponds to the ``binary_data`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + subfolder (:class:`str`): + Optional subfolder for the command. + If empty, the command will be delivered + to the /devices/{device-id}/commands + topic, otherwise it will be delivered to + the /devices/{device- + id}/commands/{subfolder} topic. Multi- + level subfolders are allowed. This field + must not have more than 256 characters, + and must not contain any MQTT wildcards + ("+" or "#") or null characters. + This corresponds to the ``subfolder`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.device_manager.SendCommandToDeviceResponse: + Response for ``SendCommandToDevice``. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([name, binary_data, subfolder]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = device_manager.SendCommandToDeviceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + if binary_data is not None: + request.binary_data = binary_data + if subfolder is not None: + request.subfolder = subfolder + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.send_command_to_device, + default_retry=retries.Retry( + initial=1.0, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ResourceExhausted, + exceptions.ServiceUnavailable, + exceptions.DeadlineExceeded, + ), + ), + default_timeout=120.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def bind_device_to_gateway( + self, + request: device_manager.BindDeviceToGatewayRequest = None, + *, + parent: str = None, + gateway_id: str = None, + device_id: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> device_manager.BindDeviceToGatewayResponse: + r"""Associates the device with the gateway. + + Args: + request (:class:`~.device_manager.BindDeviceToGatewayRequest`): + The request object. Request for `BindDeviceToGateway`. + parent (:class:`str`): + Required. The name of the registry. For example, + ``projects/example-project/locations/us-central1/registries/my-registry``. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + gateway_id (:class:`str`): + Required. The value of ``gateway_id`` can be either the + device numeric ID or the user-defined device identifier. + This corresponds to the ``gateway_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + device_id (:class:`str`): + Required. The device to associate with the specified + gateway. The value of ``device_id`` can be either the + device numeric ID or the user-defined device identifier. + This corresponds to the ``device_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.device_manager.BindDeviceToGatewayResponse: + Response for ``BindDeviceToGateway``. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([parent, gateway_id, device_id]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = device_manager.BindDeviceToGatewayRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + if gateway_id is not None: + request.gateway_id = gateway_id + if device_id is not None: + request.device_id = device_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.bind_device_to_gateway, + default_timeout=120.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def unbind_device_from_gateway( + self, + request: device_manager.UnbindDeviceFromGatewayRequest = None, + *, + parent: str = None, + gateway_id: str = None, + device_id: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> device_manager.UnbindDeviceFromGatewayResponse: + r"""Deletes the association between the device and the + gateway. + + Args: + request (:class:`~.device_manager.UnbindDeviceFromGatewayRequest`): + The request object. Request for + `UnbindDeviceFromGateway`. + parent (:class:`str`): + Required. The name of the registry. For example, + ``projects/example-project/locations/us-central1/registries/my-registry``. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + gateway_id (:class:`str`): + Required. The value of ``gateway_id`` can be either the + device numeric ID or the user-defined device identifier. + This corresponds to the ``gateway_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + device_id (:class:`str`): + Required. The device to disassociate from the specified + gateway. The value of ``device_id`` can be either the + device numeric ID or the user-defined device identifier. + This corresponds to the ``device_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.device_manager.UnbindDeviceFromGatewayResponse: + Response for ``UnbindDeviceFromGateway``. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([parent, gateway_id, device_id]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = device_manager.UnbindDeviceFromGatewayRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + if gateway_id is not None: + request.gateway_id = gateway_id + if device_id is not None: + request.device_id = device_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.unbind_device_from_gateway, + default_timeout=120.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution("google-cloud-iot",).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ("DeviceManagerAsyncClient",) diff --git a/google/cloud/iot_v1/services/device_manager/client.py b/google/cloud/iot_v1/services/device_manager/client.py new file mode 100644 index 00000000..3432432e --- /dev/null +++ b/google/cloud/iot_v1/services/device_manager/client.py @@ -0,0 +1,1951 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from collections import OrderedDict +import os +import re +from typing import Callable, Dict, Sequence, Tuple, Type, Union +import pkg_resources + +import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.iot_v1.services.device_manager import pagers +from google.cloud.iot_v1.types import device_manager +from google.cloud.iot_v1.types import resources +from google.iam.v1 import iam_policy_pb2 as iam_policy # type: ignore +from google.iam.v1 import policy_pb2 as policy # type: ignore +from google.protobuf import field_mask_pb2 as field_mask # type: ignore +from google.protobuf import timestamp_pb2 as timestamp # type: ignore +from google.rpc import status_pb2 as status # type: ignore + +from .transports.base import DeviceManagerTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import DeviceManagerGrpcTransport +from .transports.grpc_asyncio import DeviceManagerGrpcAsyncIOTransport + + +class DeviceManagerClientMeta(type): + """Metaclass for the DeviceManager client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + + _transport_registry = OrderedDict() # type: Dict[str, Type[DeviceManagerTransport]] + _transport_registry["grpc"] = DeviceManagerGrpcTransport + _transport_registry["grpc_asyncio"] = DeviceManagerGrpcAsyncIOTransport + + def get_transport_class(cls, label: str = None,) -> Type[DeviceManagerTransport]: + """Return an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class DeviceManagerClient(metaclass=DeviceManagerClientMeta): + """Internet of Things (IoT) service. Securely connect and manage + IoT devices. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Convert api endpoint to mTLS endpoint. + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "cloudiot.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + {@api.name}: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file(filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @staticmethod + def device_path(project: str, location: str, registry: str, device: str,) -> str: + """Return a fully-qualified device string.""" + return "projects/{project}/locations/{location}/registries/{registry}/devices/{device}".format( + project=project, location=location, registry=registry, device=device, + ) + + @staticmethod + def parse_device_path(path: str) -> Dict[str, str]: + """Parse a device path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/registries/(?P.+?)/devices/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def registry_path(project: str, location: str, registry: str,) -> str: + """Return a fully-qualified registry string.""" + return "projects/{project}/locations/{location}/registries/{registry}".format( + project=project, location=location, registry=registry, + ) + + @staticmethod + def parse_registry_path(path: str) -> Dict[str, str]: + """Parse a registry path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/registries/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + def __init__( + self, + *, + credentials: credentials.Credentials = None, + transport: Union[str, DeviceManagerTransport] = None, + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the device manager client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.DeviceManagerTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint, this is the default value for + the environment variable) and "auto" (auto switch to the default + mTLS endpoint if client SSL credentials is present). However, + the ``api_endpoint`` property takes precedence if provided. + (2) The ``client_cert_source`` property is used to provide client + SSL credentials for mutual TLS transport. If not provided, the + default SSL credentials will be used if present. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = ClientOptions.from_dict(client_options) + if client_options is None: + client_options = ClientOptions.ClientOptions() + + if client_options.api_endpoint is None: + use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS", "never") + if use_mtls_env == "never": + client_options.api_endpoint = self.DEFAULT_ENDPOINT + elif use_mtls_env == "always": + client_options.api_endpoint = self.DEFAULT_MTLS_ENDPOINT + elif use_mtls_env == "auto": + has_client_cert_source = ( + client_options.client_cert_source is not None + or mtls.has_default_client_cert_source() + ) + client_options.api_endpoint = ( + self.DEFAULT_MTLS_ENDPOINT + if has_client_cert_source + else self.DEFAULT_ENDPOINT + ) + else: + raise MutualTLSChannelError( + "Unsupported GOOGLE_API_USE_MTLS value. Accepted values: never, auto, always" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, DeviceManagerTransport): + # transport is a DeviceManagerTransport instance. + if credentials or client_options.credentials_file: + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) + if client_options.scopes: + raise ValueError( + "When providing a transport instance, " + "provide its scopes directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=client_options.api_endpoint, + scopes=client_options.scopes, + api_mtls_endpoint=client_options.api_endpoint, + client_cert_source=client_options.client_cert_source, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + ) + + def create_device_registry( + self, + request: device_manager.CreateDeviceRegistryRequest = None, + *, + parent: str = None, + device_registry: resources.DeviceRegistry = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.DeviceRegistry: + r"""Creates a device registry that contains devices. + + Args: + request (:class:`~.device_manager.CreateDeviceRegistryRequest`): + The request object. Request for `CreateDeviceRegistry`. + parent (:class:`str`): + Required. The project and cloud region where this device + registry must be created. For example, + ``projects/example-project/locations/us-central1``. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + device_registry (:class:`~.resources.DeviceRegistry`): + Required. The device registry. The field ``name`` must + be empty. The server will generate that field from the + device registry ``id`` provided and the ``parent`` + field. + This corresponds to the ``device_registry`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.DeviceRegistry: + A container for a group of devices. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, device_registry]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a device_manager.CreateDeviceRegistryRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, device_manager.CreateDeviceRegistryRequest): + request = device_manager.CreateDeviceRegistryRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + if device_registry is not None: + request.device_registry = device_registry + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_device_registry] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def get_device_registry( + self, + request: device_manager.GetDeviceRegistryRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.DeviceRegistry: + r"""Gets a device registry configuration. + + Args: + request (:class:`~.device_manager.GetDeviceRegistryRequest`): + The request object. Request for `GetDeviceRegistry`. + name (:class:`str`): + Required. The name of the device registry. For example, + ``projects/example-project/locations/us-central1/registries/my-registry``. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.DeviceRegistry: + A container for a group of devices. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a device_manager.GetDeviceRegistryRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, device_manager.GetDeviceRegistryRequest): + request = device_manager.GetDeviceRegistryRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_device_registry] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def update_device_registry( + self, + request: device_manager.UpdateDeviceRegistryRequest = None, + *, + device_registry: resources.DeviceRegistry = None, + update_mask: field_mask.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.DeviceRegistry: + r"""Updates a device registry configuration. + + Args: + request (:class:`~.device_manager.UpdateDeviceRegistryRequest`): + The request object. Request for `UpdateDeviceRegistry`. + device_registry (:class:`~.resources.DeviceRegistry`): + Required. The new values for the device registry. The + ``id`` field must be empty, and the ``name`` field must + indicate the path of the resource. For example, + ``projects/example-project/locations/us-central1/registries/my-registry``. + This corresponds to the ``device_registry`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`~.field_mask.FieldMask`): + Required. Only updates the ``device_registry`` fields + indicated by this mask. The field mask must not be + empty, and it must not contain fields that are immutable + or only set by the server. Mutable top-level fields: + ``event_notification_config``, ``http_config``, + ``mqtt_config``, and ``state_notification_config``. + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.DeviceRegistry: + A container for a group of devices. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([device_registry, update_mask]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a device_manager.UpdateDeviceRegistryRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, device_manager.UpdateDeviceRegistryRequest): + request = device_manager.UpdateDeviceRegistryRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if device_registry is not None: + request.device_registry = device_registry + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_device_registry] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("device_registry.name", request.device_registry.name),) + ), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def delete_device_registry( + self, + request: device_manager.DeleteDeviceRegistryRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a device registry configuration. + + Args: + request (:class:`~.device_manager.DeleteDeviceRegistryRequest`): + The request object. Request for `DeleteDeviceRegistry`. + name (:class:`str`): + Required. The name of the device registry. For example, + ``projects/example-project/locations/us-central1/registries/my-registry``. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a device_manager.DeleteDeviceRegistryRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, device_manager.DeleteDeviceRegistryRequest): + request = device_manager.DeleteDeviceRegistryRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_device_registry] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + rpc( + request, retry=retry, timeout=timeout, metadata=metadata, + ) + + def list_device_registries( + self, + request: device_manager.ListDeviceRegistriesRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListDeviceRegistriesPager: + r"""Lists device registries. + + Args: + request (:class:`~.device_manager.ListDeviceRegistriesRequest`): + The request object. Request for `ListDeviceRegistries`. + parent (:class:`str`): + Required. The project and cloud region path. For + example, + ``projects/example-project/locations/us-central1``. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.pagers.ListDeviceRegistriesPager: + Response for ``ListDeviceRegistries``. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a device_manager.ListDeviceRegistriesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, device_manager.ListDeviceRegistriesRequest): + request = device_manager.ListDeviceRegistriesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_device_registries] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListDeviceRegistriesPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + + def create_device( + self, + request: device_manager.CreateDeviceRequest = None, + *, + parent: str = None, + device: resources.Device = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.Device: + r"""Creates a device in a device registry. + + Args: + request (:class:`~.device_manager.CreateDeviceRequest`): + The request object. Request for `CreateDevice`. + parent (:class:`str`): + Required. The name of the device registry where this + device should be created. For example, + ``projects/example-project/locations/us-central1/registries/my-registry``. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + device (:class:`~.resources.Device`): + Required. The device registration details. The field + ``name`` must be empty. The server generates ``name`` + from the device registry ``id`` and the ``parent`` + field. + This corresponds to the ``device`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.Device: + The device resource. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, device]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a device_manager.CreateDeviceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, device_manager.CreateDeviceRequest): + request = device_manager.CreateDeviceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + if device is not None: + request.device = device + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_device] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def get_device( + self, + request: device_manager.GetDeviceRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.Device: + r"""Gets details about a device. + + Args: + request (:class:`~.device_manager.GetDeviceRequest`): + The request object. Request for `GetDevice`. + name (:class:`str`): + Required. The name of the device. For example, + ``projects/p0/locations/us-central1/registries/registry0/devices/device0`` + or + ``projects/p0/locations/us-central1/registries/registry0/devices/{num_id}``. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.Device: + The device resource. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a device_manager.GetDeviceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, device_manager.GetDeviceRequest): + request = device_manager.GetDeviceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_device] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def update_device( + self, + request: device_manager.UpdateDeviceRequest = None, + *, + device: resources.Device = None, + update_mask: field_mask.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.Device: + r"""Updates a device. + + Args: + request (:class:`~.device_manager.UpdateDeviceRequest`): + The request object. Request for `UpdateDevice`. + device (:class:`~.resources.Device`): + Required. The new values for the device. The ``id`` and + ``num_id`` fields must be empty, and the field ``name`` + must specify the name path. For example, + ``projects/p0/locations/us-central1/registries/registry0/devices/device0``\ or + ``projects/p0/locations/us-central1/registries/registry0/devices/{num_id}``. + This corresponds to the ``device`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`~.field_mask.FieldMask`): + Required. Only updates the ``device`` fields indicated + by this mask. The field mask must not be empty, and it + must not contain fields that are immutable or only set + by the server. Mutable top-level fields: + ``credentials``, ``blocked``, and ``metadata`` + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.Device: + The device resource. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([device, update_mask]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a device_manager.UpdateDeviceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, device_manager.UpdateDeviceRequest): + request = device_manager.UpdateDeviceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if device is not None: + request.device = device + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_device] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("device.name", request.device.name),) + ), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def delete_device( + self, + request: device_manager.DeleteDeviceRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a device. + + Args: + request (:class:`~.device_manager.DeleteDeviceRequest`): + The request object. Request for `DeleteDevice`. + name (:class:`str`): + Required. The name of the device. For example, + ``projects/p0/locations/us-central1/registries/registry0/devices/device0`` + or + ``projects/p0/locations/us-central1/registries/registry0/devices/{num_id}``. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a device_manager.DeleteDeviceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, device_manager.DeleteDeviceRequest): + request = device_manager.DeleteDeviceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_device] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + rpc( + request, retry=retry, timeout=timeout, metadata=metadata, + ) + + def list_devices( + self, + request: device_manager.ListDevicesRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListDevicesPager: + r"""List devices in a device registry. + + Args: + request (:class:`~.device_manager.ListDevicesRequest`): + The request object. Request for `ListDevices`. + parent (:class:`str`): + Required. The device registry path. Required. For + example, + ``projects/my-project/locations/us-central1/registries/my-registry``. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.pagers.ListDevicesPager: + Response for ``ListDevices``. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a device_manager.ListDevicesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, device_manager.ListDevicesRequest): + request = device_manager.ListDevicesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_devices] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListDevicesPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + + def modify_cloud_to_device_config( + self, + request: device_manager.ModifyCloudToDeviceConfigRequest = None, + *, + name: str = None, + binary_data: bytes = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.DeviceConfig: + r"""Modifies the configuration for the device, which is + eventually sent from the Cloud IoT Core servers. Returns + the modified configuration version and its metadata. + + Args: + request (:class:`~.device_manager.ModifyCloudToDeviceConfigRequest`): + The request object. Request for + `ModifyCloudToDeviceConfig`. + name (:class:`str`): + Required. The name of the device. For example, + ``projects/p0/locations/us-central1/registries/registry0/devices/device0`` + or + ``projects/p0/locations/us-central1/registries/registry0/devices/{num_id}``. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + binary_data (:class:`bytes`): + Required. The configuration data for + the device. + This corresponds to the ``binary_data`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.DeviceConfig: + The device configuration. Eventually + delivered to devices. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name, binary_data]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a device_manager.ModifyCloudToDeviceConfigRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, device_manager.ModifyCloudToDeviceConfigRequest): + request = device_manager.ModifyCloudToDeviceConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + if binary_data is not None: + request.binary_data = binary_data + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.modify_cloud_to_device_config + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def list_device_config_versions( + self, + request: device_manager.ListDeviceConfigVersionsRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> device_manager.ListDeviceConfigVersionsResponse: + r"""Lists the last few versions of the device + configuration in descending order (i.e.: newest first). + + Args: + request (:class:`~.device_manager.ListDeviceConfigVersionsRequest`): + The request object. Request for + `ListDeviceConfigVersions`. + name (:class:`str`): + Required. The name of the device. For example, + ``projects/p0/locations/us-central1/registries/registry0/devices/device0`` + or + ``projects/p0/locations/us-central1/registries/registry0/devices/{num_id}``. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.device_manager.ListDeviceConfigVersionsResponse: + Response for ``ListDeviceConfigVersions``. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a device_manager.ListDeviceConfigVersionsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, device_manager.ListDeviceConfigVersionsRequest): + request = device_manager.ListDeviceConfigVersionsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.list_device_config_versions + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def list_device_states( + self, + request: device_manager.ListDeviceStatesRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> device_manager.ListDeviceStatesResponse: + r"""Lists the last few versions of the device state in + descending order (i.e.: newest first). + + Args: + request (:class:`~.device_manager.ListDeviceStatesRequest`): + The request object. Request for `ListDeviceStates`. + name (:class:`str`): + Required. The name of the device. For example, + ``projects/p0/locations/us-central1/registries/registry0/devices/device0`` + or + ``projects/p0/locations/us-central1/registries/registry0/devices/{num_id}``. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.device_manager.ListDeviceStatesResponse: + Response for ``ListDeviceStates``. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a device_manager.ListDeviceStatesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, device_manager.ListDeviceStatesRequest): + request = device_manager.ListDeviceStatesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_device_states] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def set_iam_policy( + self, + request: iam_policy.SetIamPolicyRequest = None, + *, + resource: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy.Policy: + r"""Sets the access control policy on the specified + resource. Replaces any existing policy. + + Args: + request (:class:`~.iam_policy.SetIamPolicyRequest`): + The request object. Request message for `SetIamPolicy` + method. + resource (:class:`str`): + REQUIRED: The resource for which the + policy is being specified. See the + operation documentation for the + appropriate value for this field. + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.policy.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([resource]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy.SetIamPolicyRequest(**request) + + elif not request: + request = iam_policy.SetIamPolicyRequest() + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if resource is not None: + request.resource = resource + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.set_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def get_iam_policy( + self, + request: iam_policy.GetIamPolicyRequest = None, + *, + resource: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy.Policy: + r"""Gets the access control policy for a resource. + Returns an empty policy if the resource exists and does + not have a policy set. + + Args: + request (:class:`~.iam_policy.GetIamPolicyRequest`): + The request object. Request message for `GetIamPolicy` + method. + resource (:class:`str`): + REQUIRED: The resource for which the + policy is being requested. See the + operation documentation for the + appropriate value for this field. + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.policy.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([resource]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy.GetIamPolicyRequest(**request) + + elif not request: + request = iam_policy.GetIamPolicyRequest() + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if resource is not None: + request.resource = resource + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def test_iam_permissions( + self, + request: iam_policy.TestIamPermissionsRequest = None, + *, + resource: str = None, + permissions: Sequence[str] = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam_policy.TestIamPermissionsResponse: + r"""Returns permissions that a caller has on the specified resource. + If the resource does not exist, this will return an empty set of + permissions, not a NOT_FOUND error. + + Args: + request (:class:`~.iam_policy.TestIamPermissionsRequest`): + The request object. Request message for + `TestIamPermissions` method. + resource (:class:`str`): + REQUIRED: The resource for which the + policy detail is being requested. See + the operation documentation for the + appropriate value for this field. + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + permissions (:class:`Sequence[str]`): + The set of permissions to check for the ``resource``. + Permissions with wildcards (such as '*' or 'storage.*') + are not allowed. For more information see `IAM + Overview `__. + This corresponds to the ``permissions`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.iam_policy.TestIamPermissionsResponse: + Response message for ``TestIamPermissions`` method. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([resource, permissions]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy.TestIamPermissionsRequest(**request) + + elif not request: + request = iam_policy.TestIamPermissionsRequest() + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if resource is not None: + request.resource = resource + + if permissions: + request.permissions.extend(permissions) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.test_iam_permissions] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def send_command_to_device( + self, + request: device_manager.SendCommandToDeviceRequest = None, + *, + name: str = None, + binary_data: bytes = None, + subfolder: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> device_manager.SendCommandToDeviceResponse: + r"""Sends a command to the specified device. In order for a device + to be able to receive commands, it must: + + 1) be connected to Cloud IoT Core using the MQTT protocol, and + 2) be subscribed to the group of MQTT topics specified by + /devices/{device-id}/commands/#. This subscription will + receive commands at the top-level topic + /devices/{device-id}/commands as well as commands for + subfolders, like /devices/{device-id}/commands/subfolder. + Note that subscribing to specific subfolders is not + supported. If the command could not be delivered to the + device, this method will return an error; in particular, if + the device is not subscribed, this method will return + FAILED_PRECONDITION. Otherwise, this method will return OK. + If the subscription is QoS 1, at least once delivery will be + guaranteed; for QoS 0, no acknowledgment will be expected + from the device. + + Args: + request (:class:`~.device_manager.SendCommandToDeviceRequest`): + The request object. Request for `SendCommandToDevice`. + name (:class:`str`): + Required. The name of the device. For example, + ``projects/p0/locations/us-central1/registries/registry0/devices/device0`` + or + ``projects/p0/locations/us-central1/registries/registry0/devices/{num_id}``. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + binary_data (:class:`bytes`): + Required. The command data to send to + the device. + This corresponds to the ``binary_data`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + subfolder (:class:`str`): + Optional subfolder for the command. + If empty, the command will be delivered + to the /devices/{device-id}/commands + topic, otherwise it will be delivered to + the /devices/{device- + id}/commands/{subfolder} topic. Multi- + level subfolders are allowed. This field + must not have more than 256 characters, + and must not contain any MQTT wildcards + ("+" or "#") or null characters. + This corresponds to the ``subfolder`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.device_manager.SendCommandToDeviceResponse: + Response for ``SendCommandToDevice``. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name, binary_data, subfolder]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a device_manager.SendCommandToDeviceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, device_manager.SendCommandToDeviceRequest): + request = device_manager.SendCommandToDeviceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + if binary_data is not None: + request.binary_data = binary_data + if subfolder is not None: + request.subfolder = subfolder + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.send_command_to_device] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def bind_device_to_gateway( + self, + request: device_manager.BindDeviceToGatewayRequest = None, + *, + parent: str = None, + gateway_id: str = None, + device_id: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> device_manager.BindDeviceToGatewayResponse: + r"""Associates the device with the gateway. + + Args: + request (:class:`~.device_manager.BindDeviceToGatewayRequest`): + The request object. Request for `BindDeviceToGateway`. + parent (:class:`str`): + Required. The name of the registry. For example, + ``projects/example-project/locations/us-central1/registries/my-registry``. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + gateway_id (:class:`str`): + Required. The value of ``gateway_id`` can be either the + device numeric ID or the user-defined device identifier. + This corresponds to the ``gateway_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + device_id (:class:`str`): + Required. The device to associate with the specified + gateway. The value of ``device_id`` can be either the + device numeric ID or the user-defined device identifier. + This corresponds to the ``device_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.device_manager.BindDeviceToGatewayResponse: + Response for ``BindDeviceToGateway``. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, gateway_id, device_id]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a device_manager.BindDeviceToGatewayRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, device_manager.BindDeviceToGatewayRequest): + request = device_manager.BindDeviceToGatewayRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + if gateway_id is not None: + request.gateway_id = gateway_id + if device_id is not None: + request.device_id = device_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.bind_device_to_gateway] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def unbind_device_from_gateway( + self, + request: device_manager.UnbindDeviceFromGatewayRequest = None, + *, + parent: str = None, + gateway_id: str = None, + device_id: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> device_manager.UnbindDeviceFromGatewayResponse: + r"""Deletes the association between the device and the + gateway. + + Args: + request (:class:`~.device_manager.UnbindDeviceFromGatewayRequest`): + The request object. Request for + `UnbindDeviceFromGateway`. + parent (:class:`str`): + Required. The name of the registry. For example, + ``projects/example-project/locations/us-central1/registries/my-registry``. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + gateway_id (:class:`str`): + Required. The value of ``gateway_id`` can be either the + device numeric ID or the user-defined device identifier. + This corresponds to the ``gateway_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + device_id (:class:`str`): + Required. The device to disassociate from the specified + gateway. The value of ``device_id`` can be either the + device numeric ID or the user-defined device identifier. + This corresponds to the ``device_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.device_manager.UnbindDeviceFromGatewayResponse: + Response for ``UnbindDeviceFromGateway``. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, gateway_id, device_id]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a device_manager.UnbindDeviceFromGatewayRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, device_manager.UnbindDeviceFromGatewayRequest): + request = device_manager.UnbindDeviceFromGatewayRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + if gateway_id is not None: + request.gateway_id = gateway_id + if device_id is not None: + request.device_id = device_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.unbind_device_from_gateway + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution("google-cloud-iot",).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ("DeviceManagerClient",) diff --git a/google/cloud/iot_v1/services/device_manager/pagers.py b/google/cloud/iot_v1/services/device_manager/pagers.py new file mode 100644 index 00000000..c3db7418 --- /dev/null +++ b/google/cloud/iot_v1/services/device_manager/pagers.py @@ -0,0 +1,277 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple + +from google.cloud.iot_v1.types import device_manager +from google.cloud.iot_v1.types import resources + + +class ListDeviceRegistriesPager: + """A pager for iterating through ``list_device_registries`` requests. + + This class thinly wraps an initial + :class:`~.device_manager.ListDeviceRegistriesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``device_registries`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListDeviceRegistries`` requests and continue to iterate + through the ``device_registries`` field on the + corresponding responses. + + All the usual :class:`~.device_manager.ListDeviceRegistriesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., device_manager.ListDeviceRegistriesResponse], + request: device_manager.ListDeviceRegistriesRequest, + response: device_manager.ListDeviceRegistriesResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (:class:`~.device_manager.ListDeviceRegistriesRequest`): + The initial request object. + response (:class:`~.device_manager.ListDeviceRegistriesResponse`): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = device_manager.ListDeviceRegistriesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[device_manager.ListDeviceRegistriesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterable[resources.DeviceRegistry]: + for page in self.pages: + yield from page.device_registries + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListDeviceRegistriesAsyncPager: + """A pager for iterating through ``list_device_registries`` requests. + + This class thinly wraps an initial + :class:`~.device_manager.ListDeviceRegistriesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``device_registries`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListDeviceRegistries`` requests and continue to iterate + through the ``device_registries`` field on the + corresponding responses. + + All the usual :class:`~.device_manager.ListDeviceRegistriesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., Awaitable[device_manager.ListDeviceRegistriesResponse]], + request: device_manager.ListDeviceRegistriesRequest, + response: device_manager.ListDeviceRegistriesResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (:class:`~.device_manager.ListDeviceRegistriesRequest`): + The initial request object. + response (:class:`~.device_manager.ListDeviceRegistriesResponse`): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = device_manager.ListDeviceRegistriesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterable[device_manager.ListDeviceRegistriesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterable[resources.DeviceRegistry]: + async def async_generator(): + async for page in self.pages: + for response in page.device_registries: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListDevicesPager: + """A pager for iterating through ``list_devices`` requests. + + This class thinly wraps an initial + :class:`~.device_manager.ListDevicesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``devices`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListDevices`` requests and continue to iterate + through the ``devices`` field on the + corresponding responses. + + All the usual :class:`~.device_manager.ListDevicesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., device_manager.ListDevicesResponse], + request: device_manager.ListDevicesRequest, + response: device_manager.ListDevicesResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (:class:`~.device_manager.ListDevicesRequest`): + The initial request object. + response (:class:`~.device_manager.ListDevicesResponse`): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = device_manager.ListDevicesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[device_manager.ListDevicesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterable[resources.Device]: + for page in self.pages: + yield from page.devices + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListDevicesAsyncPager: + """A pager for iterating through ``list_devices`` requests. + + This class thinly wraps an initial + :class:`~.device_manager.ListDevicesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``devices`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListDevices`` requests and continue to iterate + through the ``devices`` field on the + corresponding responses. + + All the usual :class:`~.device_manager.ListDevicesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., Awaitable[device_manager.ListDevicesResponse]], + request: device_manager.ListDevicesRequest, + response: device_manager.ListDevicesResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (:class:`~.device_manager.ListDevicesRequest`): + The initial request object. + response (:class:`~.device_manager.ListDevicesResponse`): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = device_manager.ListDevicesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterable[device_manager.ListDevicesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterable[resources.Device]: + async def async_generator(): + async for page in self.pages: + for response in page.devices: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) diff --git a/google/cloud/iot_v1/services/device_manager/transports/__init__.py b/google/cloud/iot_v1/services/device_manager/transports/__init__.py new file mode 100644 index 00000000..c1e5e505 --- /dev/null +++ b/google/cloud/iot_v1/services/device_manager/transports/__init__.py @@ -0,0 +1,36 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from collections import OrderedDict +from typing import Dict, Type + +from .base import DeviceManagerTransport +from .grpc import DeviceManagerGrpcTransport +from .grpc_asyncio import DeviceManagerGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[DeviceManagerTransport]] +_transport_registry["grpc"] = DeviceManagerGrpcTransport +_transport_registry["grpc_asyncio"] = DeviceManagerGrpcAsyncIOTransport + + +__all__ = ( + "DeviceManagerTransport", + "DeviceManagerGrpcTransport", + "DeviceManagerGrpcAsyncIOTransport", +) diff --git a/google/cloud/iot_v1/services/device_manager/transports/base.py b/google/cloud/iot_v1/services/device_manager/transports/base.py new file mode 100644 index 00000000..5236e9a7 --- /dev/null +++ b/google/cloud/iot_v1/services/device_manager/transports/base.py @@ -0,0 +1,489 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import abc +import typing +import pkg_resources + +from google import auth # type: ignore +from google.api_core import exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials # type: ignore + +from google.cloud.iot_v1.types import device_manager +from google.cloud.iot_v1.types import resources +from google.iam.v1 import iam_policy_pb2 as iam_policy # type: ignore +from google.iam.v1 import policy_pb2 as policy # type: ignore +from google.protobuf import empty_pb2 as empty # type: ignore + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution("google-cloud-iot",).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +class DeviceManagerTransport(abc.ABC): + """Abstract transport class for DeviceManager.""" + + AUTH_SCOPES = ( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloudiot", + ) + + def __init__( + self, + *, + host: str = "cloudiot.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: typing.Optional[str] = None, + scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, + quota_project_id: typing.Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scope (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + """ + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise exceptions.DuplicateCredentialArgs( + "'credentials_file' and 'credentials' are mutually exclusive" + ) + + if credentials_file is not None: + credentials, _ = auth.load_credentials_from_file( + credentials_file, scopes=scopes, quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = auth.default( + scopes=scopes, quota_project_id=quota_project_id + ) + + # Save the credentials. + self._credentials = credentials + + # Lifted into its own function so it can be stubbed out during tests. + self._prep_wrapped_messages(client_info) + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.create_device_registry: gapic_v1.method.wrap_method( + self.create_device_registry, + default_timeout=120.0, + client_info=client_info, + ), + self.get_device_registry: gapic_v1.method.wrap_method( + self.get_device_registry, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + default_timeout=120.0, + client_info=client_info, + ), + self.update_device_registry: gapic_v1.method.wrap_method( + self.update_device_registry, + default_timeout=120.0, + client_info=client_info, + ), + self.delete_device_registry: gapic_v1.method.wrap_method( + self.delete_device_registry, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + default_timeout=120.0, + client_info=client_info, + ), + self.list_device_registries: gapic_v1.method.wrap_method( + self.list_device_registries, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + default_timeout=120.0, + client_info=client_info, + ), + self.create_device: gapic_v1.method.wrap_method( + self.create_device, default_timeout=120.0, client_info=client_info, + ), + self.get_device: gapic_v1.method.wrap_method( + self.get_device, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + default_timeout=120.0, + client_info=client_info, + ), + self.update_device: gapic_v1.method.wrap_method( + self.update_device, default_timeout=120.0, client_info=client_info, + ), + self.delete_device: gapic_v1.method.wrap_method( + self.delete_device, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + default_timeout=120.0, + client_info=client_info, + ), + self.list_devices: gapic_v1.method.wrap_method( + self.list_devices, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + default_timeout=120.0, + client_info=client_info, + ), + self.modify_cloud_to_device_config: gapic_v1.method.wrap_method( + self.modify_cloud_to_device_config, + default_retry=retries.Retry( + initial=1.0, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ResourceExhausted, + exceptions.ServiceUnavailable, + exceptions.DeadlineExceeded, + ), + ), + default_timeout=120.0, + client_info=client_info, + ), + self.list_device_config_versions: gapic_v1.method.wrap_method( + self.list_device_config_versions, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + default_timeout=120.0, + client_info=client_info, + ), + self.list_device_states: gapic_v1.method.wrap_method( + self.list_device_states, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + default_timeout=120.0, + client_info=client_info, + ), + self.set_iam_policy: gapic_v1.method.wrap_method( + self.set_iam_policy, default_timeout=120.0, client_info=client_info, + ), + self.get_iam_policy: gapic_v1.method.wrap_method( + self.get_iam_policy, default_timeout=120.0, client_info=client_info, + ), + self.test_iam_permissions: gapic_v1.method.wrap_method( + self.test_iam_permissions, + default_timeout=120.0, + client_info=client_info, + ), + self.send_command_to_device: gapic_v1.method.wrap_method( + self.send_command_to_device, + default_retry=retries.Retry( + initial=1.0, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ResourceExhausted, + exceptions.ServiceUnavailable, + exceptions.DeadlineExceeded, + ), + ), + default_timeout=120.0, + client_info=client_info, + ), + self.bind_device_to_gateway: gapic_v1.method.wrap_method( + self.bind_device_to_gateway, + default_timeout=120.0, + client_info=client_info, + ), + self.unbind_device_from_gateway: gapic_v1.method.wrap_method( + self.unbind_device_from_gateway, + default_timeout=120.0, + client_info=client_info, + ), + } + + @property + def create_device_registry( + self, + ) -> typing.Callable[ + [device_manager.CreateDeviceRegistryRequest], + typing.Union[ + resources.DeviceRegistry, typing.Awaitable[resources.DeviceRegistry] + ], + ]: + raise NotImplementedError() + + @property + def get_device_registry( + self, + ) -> typing.Callable[ + [device_manager.GetDeviceRegistryRequest], + typing.Union[ + resources.DeviceRegistry, typing.Awaitable[resources.DeviceRegistry] + ], + ]: + raise NotImplementedError() + + @property + def update_device_registry( + self, + ) -> typing.Callable[ + [device_manager.UpdateDeviceRegistryRequest], + typing.Union[ + resources.DeviceRegistry, typing.Awaitable[resources.DeviceRegistry] + ], + ]: + raise NotImplementedError() + + @property + def delete_device_registry( + self, + ) -> typing.Callable[ + [device_manager.DeleteDeviceRegistryRequest], + typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + ]: + raise NotImplementedError() + + @property + def list_device_registries( + self, + ) -> typing.Callable[ + [device_manager.ListDeviceRegistriesRequest], + typing.Union[ + device_manager.ListDeviceRegistriesResponse, + typing.Awaitable[device_manager.ListDeviceRegistriesResponse], + ], + ]: + raise NotImplementedError() + + @property + def create_device( + self, + ) -> typing.Callable[ + [device_manager.CreateDeviceRequest], + typing.Union[resources.Device, typing.Awaitable[resources.Device]], + ]: + raise NotImplementedError() + + @property + def get_device( + self, + ) -> typing.Callable[ + [device_manager.GetDeviceRequest], + typing.Union[resources.Device, typing.Awaitable[resources.Device]], + ]: + raise NotImplementedError() + + @property + def update_device( + self, + ) -> typing.Callable[ + [device_manager.UpdateDeviceRequest], + typing.Union[resources.Device, typing.Awaitable[resources.Device]], + ]: + raise NotImplementedError() + + @property + def delete_device( + self, + ) -> typing.Callable[ + [device_manager.DeleteDeviceRequest], + typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + ]: + raise NotImplementedError() + + @property + def list_devices( + self, + ) -> typing.Callable[ + [device_manager.ListDevicesRequest], + typing.Union[ + device_manager.ListDevicesResponse, + typing.Awaitable[device_manager.ListDevicesResponse], + ], + ]: + raise NotImplementedError() + + @property + def modify_cloud_to_device_config( + self, + ) -> typing.Callable[ + [device_manager.ModifyCloudToDeviceConfigRequest], + typing.Union[resources.DeviceConfig, typing.Awaitable[resources.DeviceConfig]], + ]: + raise NotImplementedError() + + @property + def list_device_config_versions( + self, + ) -> typing.Callable[ + [device_manager.ListDeviceConfigVersionsRequest], + typing.Union[ + device_manager.ListDeviceConfigVersionsResponse, + typing.Awaitable[device_manager.ListDeviceConfigVersionsResponse], + ], + ]: + raise NotImplementedError() + + @property + def list_device_states( + self, + ) -> typing.Callable[ + [device_manager.ListDeviceStatesRequest], + typing.Union[ + device_manager.ListDeviceStatesResponse, + typing.Awaitable[device_manager.ListDeviceStatesResponse], + ], + ]: + raise NotImplementedError() + + @property + def set_iam_policy( + self, + ) -> typing.Callable[ + [iam_policy.SetIamPolicyRequest], + typing.Union[policy.Policy, typing.Awaitable[policy.Policy]], + ]: + raise NotImplementedError() + + @property + def get_iam_policy( + self, + ) -> typing.Callable[ + [iam_policy.GetIamPolicyRequest], + typing.Union[policy.Policy, typing.Awaitable[policy.Policy]], + ]: + raise NotImplementedError() + + @property + def test_iam_permissions( + self, + ) -> typing.Callable[ + [iam_policy.TestIamPermissionsRequest], + typing.Union[ + iam_policy.TestIamPermissionsResponse, + typing.Awaitable[iam_policy.TestIamPermissionsResponse], + ], + ]: + raise NotImplementedError() + + @property + def send_command_to_device( + self, + ) -> typing.Callable[ + [device_manager.SendCommandToDeviceRequest], + typing.Union[ + device_manager.SendCommandToDeviceResponse, + typing.Awaitable[device_manager.SendCommandToDeviceResponse], + ], + ]: + raise NotImplementedError() + + @property + def bind_device_to_gateway( + self, + ) -> typing.Callable[ + [device_manager.BindDeviceToGatewayRequest], + typing.Union[ + device_manager.BindDeviceToGatewayResponse, + typing.Awaitable[device_manager.BindDeviceToGatewayResponse], + ], + ]: + raise NotImplementedError() + + @property + def unbind_device_from_gateway( + self, + ) -> typing.Callable[ + [device_manager.UnbindDeviceFromGatewayRequest], + typing.Union[ + device_manager.UnbindDeviceFromGatewayResponse, + typing.Awaitable[device_manager.UnbindDeviceFromGatewayResponse], + ], + ]: + raise NotImplementedError() + + +__all__ = ("DeviceManagerTransport",) diff --git a/google/cloud/iot_v1/services/device_manager/transports/grpc.py b/google/cloud/iot_v1/services/device_manager/transports/grpc.py new file mode 100644 index 00000000..30bd43a2 --- /dev/null +++ b/google/cloud/iot_v1/services/device_manager/transports/grpc.py @@ -0,0 +1,770 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from typing import Callable, Dict, Optional, Sequence, Tuple + +from google.api_core import grpc_helpers # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google import auth # type: ignore +from google.auth import credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + + +import grpc # type: ignore + +from google.cloud.iot_v1.types import device_manager +from google.cloud.iot_v1.types import resources +from google.iam.v1 import iam_policy_pb2 as iam_policy # type: ignore +from google.iam.v1 import policy_pb2 as policy # type: ignore +from google.protobuf import empty_pb2 as empty # type: ignore + +from .base import DeviceManagerTransport, DEFAULT_CLIENT_INFO + + +class DeviceManagerGrpcTransport(DeviceManagerTransport): + """gRPC backend transport for DeviceManager. + + Internet of Things (IoT) service. Securely connect and manage + IoT devices. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _stubs: Dict[str, Callable] + + def __init__( + self, + *, + host: str = "cloudiot.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): The mutual TLS endpoint. If + provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): A + callback to provide client SSL certificate bytes and private key + bytes, both in PEM format. It is ignored if ``api_mtls_endpoint`` + is None. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + if channel: + # Sanity check: Ensure that channel and credentials are not both + # provided. + credentials = False + + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + elif api_mtls_endpoint: + host = ( + api_mtls_endpoint + if ":" in api_mtls_endpoint + else api_mtls_endpoint + ":443" + ) + + if credentials is None: + credentials, _ = auth.default( + scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id + ) + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + ssl_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + ssl_credentials = SslCredentials().ssl_credentials + + # create a new channel. The provided one is ignored. + self._grpc_channel = type(self).create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + ssl_credentials=ssl_credentials, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) + + self._stubs = {} # type: Dict[str, Callable] + + # Run the base constructor. + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + client_info=client_info, + ) + + @classmethod + def create_channel( + cls, + host: str = "cloudiot.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + address (Optionsl[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + scopes = scopes or cls.AUTH_SCOPES + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + **kwargs, + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Sanity check: Only create a new channel if we do not already + # have one. + if not hasattr(self, "_grpc_channel"): + self._grpc_channel = self.create_channel( + self._host, credentials=self._credentials, + ) + + # Return the channel from cache. + return self._grpc_channel + + @property + def create_device_registry( + self, + ) -> Callable[ + [device_manager.CreateDeviceRegistryRequest], resources.DeviceRegistry + ]: + r"""Return a callable for the create device registry method over gRPC. + + Creates a device registry that contains devices. + + Returns: + Callable[[~.CreateDeviceRegistryRequest], + ~.DeviceRegistry]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_device_registry" not in self._stubs: + self._stubs["create_device_registry"] = self.grpc_channel.unary_unary( + "/google.cloud.iot.v1.DeviceManager/CreateDeviceRegistry", + request_serializer=device_manager.CreateDeviceRegistryRequest.serialize, + response_deserializer=resources.DeviceRegistry.deserialize, + ) + return self._stubs["create_device_registry"] + + @property + def get_device_registry( + self, + ) -> Callable[[device_manager.GetDeviceRegistryRequest], resources.DeviceRegistry]: + r"""Return a callable for the get device registry method over gRPC. + + Gets a device registry configuration. + + Returns: + Callable[[~.GetDeviceRegistryRequest], + ~.DeviceRegistry]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_device_registry" not in self._stubs: + self._stubs["get_device_registry"] = self.grpc_channel.unary_unary( + "/google.cloud.iot.v1.DeviceManager/GetDeviceRegistry", + request_serializer=device_manager.GetDeviceRegistryRequest.serialize, + response_deserializer=resources.DeviceRegistry.deserialize, + ) + return self._stubs["get_device_registry"] + + @property + def update_device_registry( + self, + ) -> Callable[ + [device_manager.UpdateDeviceRegistryRequest], resources.DeviceRegistry + ]: + r"""Return a callable for the update device registry method over gRPC. + + Updates a device registry configuration. + + Returns: + Callable[[~.UpdateDeviceRegistryRequest], + ~.DeviceRegistry]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_device_registry" not in self._stubs: + self._stubs["update_device_registry"] = self.grpc_channel.unary_unary( + "/google.cloud.iot.v1.DeviceManager/UpdateDeviceRegistry", + request_serializer=device_manager.UpdateDeviceRegistryRequest.serialize, + response_deserializer=resources.DeviceRegistry.deserialize, + ) + return self._stubs["update_device_registry"] + + @property + def delete_device_registry( + self, + ) -> Callable[[device_manager.DeleteDeviceRegistryRequest], empty.Empty]: + r"""Return a callable for the delete device registry method over gRPC. + + Deletes a device registry configuration. + + Returns: + Callable[[~.DeleteDeviceRegistryRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_device_registry" not in self._stubs: + self._stubs["delete_device_registry"] = self.grpc_channel.unary_unary( + "/google.cloud.iot.v1.DeviceManager/DeleteDeviceRegistry", + request_serializer=device_manager.DeleteDeviceRegistryRequest.serialize, + response_deserializer=empty.Empty.FromString, + ) + return self._stubs["delete_device_registry"] + + @property + def list_device_registries( + self, + ) -> Callable[ + [device_manager.ListDeviceRegistriesRequest], + device_manager.ListDeviceRegistriesResponse, + ]: + r"""Return a callable for the list device registries method over gRPC. + + Lists device registries. + + Returns: + Callable[[~.ListDeviceRegistriesRequest], + ~.ListDeviceRegistriesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_device_registries" not in self._stubs: + self._stubs["list_device_registries"] = self.grpc_channel.unary_unary( + "/google.cloud.iot.v1.DeviceManager/ListDeviceRegistries", + request_serializer=device_manager.ListDeviceRegistriesRequest.serialize, + response_deserializer=device_manager.ListDeviceRegistriesResponse.deserialize, + ) + return self._stubs["list_device_registries"] + + @property + def create_device( + self, + ) -> Callable[[device_manager.CreateDeviceRequest], resources.Device]: + r"""Return a callable for the create device method over gRPC. + + Creates a device in a device registry. + + Returns: + Callable[[~.CreateDeviceRequest], + ~.Device]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_device" not in self._stubs: + self._stubs["create_device"] = self.grpc_channel.unary_unary( + "/google.cloud.iot.v1.DeviceManager/CreateDevice", + request_serializer=device_manager.CreateDeviceRequest.serialize, + response_deserializer=resources.Device.deserialize, + ) + return self._stubs["create_device"] + + @property + def get_device( + self, + ) -> Callable[[device_manager.GetDeviceRequest], resources.Device]: + r"""Return a callable for the get device method over gRPC. + + Gets details about a device. + + Returns: + Callable[[~.GetDeviceRequest], + ~.Device]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_device" not in self._stubs: + self._stubs["get_device"] = self.grpc_channel.unary_unary( + "/google.cloud.iot.v1.DeviceManager/GetDevice", + request_serializer=device_manager.GetDeviceRequest.serialize, + response_deserializer=resources.Device.deserialize, + ) + return self._stubs["get_device"] + + @property + def update_device( + self, + ) -> Callable[[device_manager.UpdateDeviceRequest], resources.Device]: + r"""Return a callable for the update device method over gRPC. + + Updates a device. + + Returns: + Callable[[~.UpdateDeviceRequest], + ~.Device]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_device" not in self._stubs: + self._stubs["update_device"] = self.grpc_channel.unary_unary( + "/google.cloud.iot.v1.DeviceManager/UpdateDevice", + request_serializer=device_manager.UpdateDeviceRequest.serialize, + response_deserializer=resources.Device.deserialize, + ) + return self._stubs["update_device"] + + @property + def delete_device( + self, + ) -> Callable[[device_manager.DeleteDeviceRequest], empty.Empty]: + r"""Return a callable for the delete device method over gRPC. + + Deletes a device. + + Returns: + Callable[[~.DeleteDeviceRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_device" not in self._stubs: + self._stubs["delete_device"] = self.grpc_channel.unary_unary( + "/google.cloud.iot.v1.DeviceManager/DeleteDevice", + request_serializer=device_manager.DeleteDeviceRequest.serialize, + response_deserializer=empty.Empty.FromString, + ) + return self._stubs["delete_device"] + + @property + def list_devices( + self, + ) -> Callable[ + [device_manager.ListDevicesRequest], device_manager.ListDevicesResponse + ]: + r"""Return a callable for the list devices method over gRPC. + + List devices in a device registry. + + Returns: + Callable[[~.ListDevicesRequest], + ~.ListDevicesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_devices" not in self._stubs: + self._stubs["list_devices"] = self.grpc_channel.unary_unary( + "/google.cloud.iot.v1.DeviceManager/ListDevices", + request_serializer=device_manager.ListDevicesRequest.serialize, + response_deserializer=device_manager.ListDevicesResponse.deserialize, + ) + return self._stubs["list_devices"] + + @property + def modify_cloud_to_device_config( + self, + ) -> Callable[ + [device_manager.ModifyCloudToDeviceConfigRequest], resources.DeviceConfig + ]: + r"""Return a callable for the modify cloud to device config method over gRPC. + + Modifies the configuration for the device, which is + eventually sent from the Cloud IoT Core servers. Returns + the modified configuration version and its metadata. + + Returns: + Callable[[~.ModifyCloudToDeviceConfigRequest], + ~.DeviceConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "modify_cloud_to_device_config" not in self._stubs: + self._stubs[ + "modify_cloud_to_device_config" + ] = self.grpc_channel.unary_unary( + "/google.cloud.iot.v1.DeviceManager/ModifyCloudToDeviceConfig", + request_serializer=device_manager.ModifyCloudToDeviceConfigRequest.serialize, + response_deserializer=resources.DeviceConfig.deserialize, + ) + return self._stubs["modify_cloud_to_device_config"] + + @property + def list_device_config_versions( + self, + ) -> Callable[ + [device_manager.ListDeviceConfigVersionsRequest], + device_manager.ListDeviceConfigVersionsResponse, + ]: + r"""Return a callable for the list device config versions method over gRPC. + + Lists the last few versions of the device + configuration in descending order (i.e.: newest first). + + Returns: + Callable[[~.ListDeviceConfigVersionsRequest], + ~.ListDeviceConfigVersionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_device_config_versions" not in self._stubs: + self._stubs["list_device_config_versions"] = self.grpc_channel.unary_unary( + "/google.cloud.iot.v1.DeviceManager/ListDeviceConfigVersions", + request_serializer=device_manager.ListDeviceConfigVersionsRequest.serialize, + response_deserializer=device_manager.ListDeviceConfigVersionsResponse.deserialize, + ) + return self._stubs["list_device_config_versions"] + + @property + def list_device_states( + self, + ) -> Callable[ + [device_manager.ListDeviceStatesRequest], + device_manager.ListDeviceStatesResponse, + ]: + r"""Return a callable for the list device states method over gRPC. + + Lists the last few versions of the device state in + descending order (i.e.: newest first). + + Returns: + Callable[[~.ListDeviceStatesRequest], + ~.ListDeviceStatesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_device_states" not in self._stubs: + self._stubs["list_device_states"] = self.grpc_channel.unary_unary( + "/google.cloud.iot.v1.DeviceManager/ListDeviceStates", + request_serializer=device_manager.ListDeviceStatesRequest.serialize, + response_deserializer=device_manager.ListDeviceStatesResponse.deserialize, + ) + return self._stubs["list_device_states"] + + @property + def set_iam_policy( + self, + ) -> Callable[[iam_policy.SetIamPolicyRequest], policy.Policy]: + r"""Return a callable for the set iam policy method over gRPC. + + Sets the access control policy on the specified + resource. Replaces any existing policy. + + Returns: + Callable[[~.SetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "set_iam_policy" not in self._stubs: + self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( + "/google.cloud.iot.v1.DeviceManager/SetIamPolicy", + request_serializer=iam_policy.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy.Policy.FromString, + ) + return self._stubs["set_iam_policy"] + + @property + def get_iam_policy( + self, + ) -> Callable[[iam_policy.GetIamPolicyRequest], policy.Policy]: + r"""Return a callable for the get iam policy method over gRPC. + + Gets the access control policy for a resource. + Returns an empty policy if the resource exists and does + not have a policy set. + + Returns: + Callable[[~.GetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_iam_policy" not in self._stubs: + self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( + "/google.cloud.iot.v1.DeviceManager/GetIamPolicy", + request_serializer=iam_policy.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy.Policy.FromString, + ) + return self._stubs["get_iam_policy"] + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy.TestIamPermissionsRequest], iam_policy.TestIamPermissionsResponse + ]: + r"""Return a callable for the test iam permissions method over gRPC. + + Returns permissions that a caller has on the specified resource. + If the resource does not exist, this will return an empty set of + permissions, not a NOT_FOUND error. + + Returns: + Callable[[~.TestIamPermissionsRequest], + ~.TestIamPermissionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "test_iam_permissions" not in self._stubs: + self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( + "/google.cloud.iot.v1.DeviceManager/TestIamPermissions", + request_serializer=iam_policy.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy.TestIamPermissionsResponse.FromString, + ) + return self._stubs["test_iam_permissions"] + + @property + def send_command_to_device( + self, + ) -> Callable[ + [device_manager.SendCommandToDeviceRequest], + device_manager.SendCommandToDeviceResponse, + ]: + r"""Return a callable for the send command to device method over gRPC. + + Sends a command to the specified device. In order for a device + to be able to receive commands, it must: + + 1) be connected to Cloud IoT Core using the MQTT protocol, and + 2) be subscribed to the group of MQTT topics specified by + /devices/{device-id}/commands/#. This subscription will + receive commands at the top-level topic + /devices/{device-id}/commands as well as commands for + subfolders, like /devices/{device-id}/commands/subfolder. + Note that subscribing to specific subfolders is not + supported. If the command could not be delivered to the + device, this method will return an error; in particular, if + the device is not subscribed, this method will return + FAILED_PRECONDITION. Otherwise, this method will return OK. + If the subscription is QoS 1, at least once delivery will be + guaranteed; for QoS 0, no acknowledgment will be expected + from the device. + + Returns: + Callable[[~.SendCommandToDeviceRequest], + ~.SendCommandToDeviceResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "send_command_to_device" not in self._stubs: + self._stubs["send_command_to_device"] = self.grpc_channel.unary_unary( + "/google.cloud.iot.v1.DeviceManager/SendCommandToDevice", + request_serializer=device_manager.SendCommandToDeviceRequest.serialize, + response_deserializer=device_manager.SendCommandToDeviceResponse.deserialize, + ) + return self._stubs["send_command_to_device"] + + @property + def bind_device_to_gateway( + self, + ) -> Callable[ + [device_manager.BindDeviceToGatewayRequest], + device_manager.BindDeviceToGatewayResponse, + ]: + r"""Return a callable for the bind device to gateway method over gRPC. + + Associates the device with the gateway. + + Returns: + Callable[[~.BindDeviceToGatewayRequest], + ~.BindDeviceToGatewayResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "bind_device_to_gateway" not in self._stubs: + self._stubs["bind_device_to_gateway"] = self.grpc_channel.unary_unary( + "/google.cloud.iot.v1.DeviceManager/BindDeviceToGateway", + request_serializer=device_manager.BindDeviceToGatewayRequest.serialize, + response_deserializer=device_manager.BindDeviceToGatewayResponse.deserialize, + ) + return self._stubs["bind_device_to_gateway"] + + @property + def unbind_device_from_gateway( + self, + ) -> Callable[ + [device_manager.UnbindDeviceFromGatewayRequest], + device_manager.UnbindDeviceFromGatewayResponse, + ]: + r"""Return a callable for the unbind device from gateway method over gRPC. + + Deletes the association between the device and the + gateway. + + Returns: + Callable[[~.UnbindDeviceFromGatewayRequest], + ~.UnbindDeviceFromGatewayResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "unbind_device_from_gateway" not in self._stubs: + self._stubs["unbind_device_from_gateway"] = self.grpc_channel.unary_unary( + "/google.cloud.iot.v1.DeviceManager/UnbindDeviceFromGateway", + request_serializer=device_manager.UnbindDeviceFromGatewayRequest.serialize, + response_deserializer=device_manager.UnbindDeviceFromGatewayResponse.deserialize, + ) + return self._stubs["unbind_device_from_gateway"] + + +__all__ = ("DeviceManagerGrpcTransport",) diff --git a/google/cloud/iot_v1/services/device_manager/transports/grpc_asyncio.py b/google/cloud/iot_v1/services/device_manager/transports/grpc_asyncio.py new file mode 100644 index 00000000..fc84f7aa --- /dev/null +++ b/google/cloud/iot_v1/services/device_manager/transports/grpc_asyncio.py @@ -0,0 +1,770 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple + +from google.api_core import gapic_v1 # type: ignore +from google.api_core import grpc_helpers_async # type: ignore +from google.auth import credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.iot_v1.types import device_manager +from google.cloud.iot_v1.types import resources +from google.iam.v1 import iam_policy_pb2 as iam_policy # type: ignore +from google.iam.v1 import policy_pb2 as policy # type: ignore +from google.protobuf import empty_pb2 as empty # type: ignore + +from .base import DeviceManagerTransport, DEFAULT_CLIENT_INFO +from .grpc import DeviceManagerGrpcTransport + + +class DeviceManagerGrpcAsyncIOTransport(DeviceManagerTransport): + """gRPC AsyncIO backend transport for DeviceManager. + + Internet of Things (IoT) service. Securely connect and manage + IoT devices. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel( + cls, + host: str = "cloudiot.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + address (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + scopes = scopes or cls.AUTH_SCOPES + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + **kwargs, + ) + + def __init__( + self, + *, + host: str = "cloudiot.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): The mutual TLS endpoint. If + provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): A + callback to provide client SSL certificate bytes and private key + bytes, both in PEM format. It is ignored if ``api_mtls_endpoint`` + is None. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + if channel: + # Sanity check: Ensure that channel and credentials are not both + # provided. + credentials = False + + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + elif api_mtls_endpoint: + host = ( + api_mtls_endpoint + if ":" in api_mtls_endpoint + else api_mtls_endpoint + ":443" + ) + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + ssl_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + ssl_credentials = SslCredentials().ssl_credentials + + # create a new channel. The provided one is ignored. + self._grpc_channel = type(self).create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + ssl_credentials=ssl_credentials, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) + + # Run the base constructor. + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + client_info=client_info, + ) + + self._stubs = {} + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Sanity check: Only create a new channel if we do not already + # have one. + if not hasattr(self, "_grpc_channel"): + self._grpc_channel = self.create_channel( + self._host, credentials=self._credentials, + ) + + # Return the channel from cache. + return self._grpc_channel + + @property + def create_device_registry( + self, + ) -> Callable[ + [device_manager.CreateDeviceRegistryRequest], + Awaitable[resources.DeviceRegistry], + ]: + r"""Return a callable for the create device registry method over gRPC. + + Creates a device registry that contains devices. + + Returns: + Callable[[~.CreateDeviceRegistryRequest], + Awaitable[~.DeviceRegistry]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_device_registry" not in self._stubs: + self._stubs["create_device_registry"] = self.grpc_channel.unary_unary( + "/google.cloud.iot.v1.DeviceManager/CreateDeviceRegistry", + request_serializer=device_manager.CreateDeviceRegistryRequest.serialize, + response_deserializer=resources.DeviceRegistry.deserialize, + ) + return self._stubs["create_device_registry"] + + @property + def get_device_registry( + self, + ) -> Callable[ + [device_manager.GetDeviceRegistryRequest], Awaitable[resources.DeviceRegistry] + ]: + r"""Return a callable for the get device registry method over gRPC. + + Gets a device registry configuration. + + Returns: + Callable[[~.GetDeviceRegistryRequest], + Awaitable[~.DeviceRegistry]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_device_registry" not in self._stubs: + self._stubs["get_device_registry"] = self.grpc_channel.unary_unary( + "/google.cloud.iot.v1.DeviceManager/GetDeviceRegistry", + request_serializer=device_manager.GetDeviceRegistryRequest.serialize, + response_deserializer=resources.DeviceRegistry.deserialize, + ) + return self._stubs["get_device_registry"] + + @property + def update_device_registry( + self, + ) -> Callable[ + [device_manager.UpdateDeviceRegistryRequest], + Awaitable[resources.DeviceRegistry], + ]: + r"""Return a callable for the update device registry method over gRPC. + + Updates a device registry configuration. + + Returns: + Callable[[~.UpdateDeviceRegistryRequest], + Awaitable[~.DeviceRegistry]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_device_registry" not in self._stubs: + self._stubs["update_device_registry"] = self.grpc_channel.unary_unary( + "/google.cloud.iot.v1.DeviceManager/UpdateDeviceRegistry", + request_serializer=device_manager.UpdateDeviceRegistryRequest.serialize, + response_deserializer=resources.DeviceRegistry.deserialize, + ) + return self._stubs["update_device_registry"] + + @property + def delete_device_registry( + self, + ) -> Callable[[device_manager.DeleteDeviceRegistryRequest], Awaitable[empty.Empty]]: + r"""Return a callable for the delete device registry method over gRPC. + + Deletes a device registry configuration. + + Returns: + Callable[[~.DeleteDeviceRegistryRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_device_registry" not in self._stubs: + self._stubs["delete_device_registry"] = self.grpc_channel.unary_unary( + "/google.cloud.iot.v1.DeviceManager/DeleteDeviceRegistry", + request_serializer=device_manager.DeleteDeviceRegistryRequest.serialize, + response_deserializer=empty.Empty.FromString, + ) + return self._stubs["delete_device_registry"] + + @property + def list_device_registries( + self, + ) -> Callable[ + [device_manager.ListDeviceRegistriesRequest], + Awaitable[device_manager.ListDeviceRegistriesResponse], + ]: + r"""Return a callable for the list device registries method over gRPC. + + Lists device registries. + + Returns: + Callable[[~.ListDeviceRegistriesRequest], + Awaitable[~.ListDeviceRegistriesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_device_registries" not in self._stubs: + self._stubs["list_device_registries"] = self.grpc_channel.unary_unary( + "/google.cloud.iot.v1.DeviceManager/ListDeviceRegistries", + request_serializer=device_manager.ListDeviceRegistriesRequest.serialize, + response_deserializer=device_manager.ListDeviceRegistriesResponse.deserialize, + ) + return self._stubs["list_device_registries"] + + @property + def create_device( + self, + ) -> Callable[[device_manager.CreateDeviceRequest], Awaitable[resources.Device]]: + r"""Return a callable for the create device method over gRPC. + + Creates a device in a device registry. + + Returns: + Callable[[~.CreateDeviceRequest], + Awaitable[~.Device]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_device" not in self._stubs: + self._stubs["create_device"] = self.grpc_channel.unary_unary( + "/google.cloud.iot.v1.DeviceManager/CreateDevice", + request_serializer=device_manager.CreateDeviceRequest.serialize, + response_deserializer=resources.Device.deserialize, + ) + return self._stubs["create_device"] + + @property + def get_device( + self, + ) -> Callable[[device_manager.GetDeviceRequest], Awaitable[resources.Device]]: + r"""Return a callable for the get device method over gRPC. + + Gets details about a device. + + Returns: + Callable[[~.GetDeviceRequest], + Awaitable[~.Device]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_device" not in self._stubs: + self._stubs["get_device"] = self.grpc_channel.unary_unary( + "/google.cloud.iot.v1.DeviceManager/GetDevice", + request_serializer=device_manager.GetDeviceRequest.serialize, + response_deserializer=resources.Device.deserialize, + ) + return self._stubs["get_device"] + + @property + def update_device( + self, + ) -> Callable[[device_manager.UpdateDeviceRequest], Awaitable[resources.Device]]: + r"""Return a callable for the update device method over gRPC. + + Updates a device. + + Returns: + Callable[[~.UpdateDeviceRequest], + Awaitable[~.Device]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_device" not in self._stubs: + self._stubs["update_device"] = self.grpc_channel.unary_unary( + "/google.cloud.iot.v1.DeviceManager/UpdateDevice", + request_serializer=device_manager.UpdateDeviceRequest.serialize, + response_deserializer=resources.Device.deserialize, + ) + return self._stubs["update_device"] + + @property + def delete_device( + self, + ) -> Callable[[device_manager.DeleteDeviceRequest], Awaitable[empty.Empty]]: + r"""Return a callable for the delete device method over gRPC. + + Deletes a device. + + Returns: + Callable[[~.DeleteDeviceRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_device" not in self._stubs: + self._stubs["delete_device"] = self.grpc_channel.unary_unary( + "/google.cloud.iot.v1.DeviceManager/DeleteDevice", + request_serializer=device_manager.DeleteDeviceRequest.serialize, + response_deserializer=empty.Empty.FromString, + ) + return self._stubs["delete_device"] + + @property + def list_devices( + self, + ) -> Callable[ + [device_manager.ListDevicesRequest], + Awaitable[device_manager.ListDevicesResponse], + ]: + r"""Return a callable for the list devices method over gRPC. + + List devices in a device registry. + + Returns: + Callable[[~.ListDevicesRequest], + Awaitable[~.ListDevicesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_devices" not in self._stubs: + self._stubs["list_devices"] = self.grpc_channel.unary_unary( + "/google.cloud.iot.v1.DeviceManager/ListDevices", + request_serializer=device_manager.ListDevicesRequest.serialize, + response_deserializer=device_manager.ListDevicesResponse.deserialize, + ) + return self._stubs["list_devices"] + + @property + def modify_cloud_to_device_config( + self, + ) -> Callable[ + [device_manager.ModifyCloudToDeviceConfigRequest], + Awaitable[resources.DeviceConfig], + ]: + r"""Return a callable for the modify cloud to device config method over gRPC. + + Modifies the configuration for the device, which is + eventually sent from the Cloud IoT Core servers. Returns + the modified configuration version and its metadata. + + Returns: + Callable[[~.ModifyCloudToDeviceConfigRequest], + Awaitable[~.DeviceConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "modify_cloud_to_device_config" not in self._stubs: + self._stubs[ + "modify_cloud_to_device_config" + ] = self.grpc_channel.unary_unary( + "/google.cloud.iot.v1.DeviceManager/ModifyCloudToDeviceConfig", + request_serializer=device_manager.ModifyCloudToDeviceConfigRequest.serialize, + response_deserializer=resources.DeviceConfig.deserialize, + ) + return self._stubs["modify_cloud_to_device_config"] + + @property + def list_device_config_versions( + self, + ) -> Callable[ + [device_manager.ListDeviceConfigVersionsRequest], + Awaitable[device_manager.ListDeviceConfigVersionsResponse], + ]: + r"""Return a callable for the list device config versions method over gRPC. + + Lists the last few versions of the device + configuration in descending order (i.e.: newest first). + + Returns: + Callable[[~.ListDeviceConfigVersionsRequest], + Awaitable[~.ListDeviceConfigVersionsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_device_config_versions" not in self._stubs: + self._stubs["list_device_config_versions"] = self.grpc_channel.unary_unary( + "/google.cloud.iot.v1.DeviceManager/ListDeviceConfigVersions", + request_serializer=device_manager.ListDeviceConfigVersionsRequest.serialize, + response_deserializer=device_manager.ListDeviceConfigVersionsResponse.deserialize, + ) + return self._stubs["list_device_config_versions"] + + @property + def list_device_states( + self, + ) -> Callable[ + [device_manager.ListDeviceStatesRequest], + Awaitable[device_manager.ListDeviceStatesResponse], + ]: + r"""Return a callable for the list device states method over gRPC. + + Lists the last few versions of the device state in + descending order (i.e.: newest first). + + Returns: + Callable[[~.ListDeviceStatesRequest], + Awaitable[~.ListDeviceStatesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_device_states" not in self._stubs: + self._stubs["list_device_states"] = self.grpc_channel.unary_unary( + "/google.cloud.iot.v1.DeviceManager/ListDeviceStates", + request_serializer=device_manager.ListDeviceStatesRequest.serialize, + response_deserializer=device_manager.ListDeviceStatesResponse.deserialize, + ) + return self._stubs["list_device_states"] + + @property + def set_iam_policy( + self, + ) -> Callable[[iam_policy.SetIamPolicyRequest], Awaitable[policy.Policy]]: + r"""Return a callable for the set iam policy method over gRPC. + + Sets the access control policy on the specified + resource. Replaces any existing policy. + + Returns: + Callable[[~.SetIamPolicyRequest], + Awaitable[~.Policy]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "set_iam_policy" not in self._stubs: + self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( + "/google.cloud.iot.v1.DeviceManager/SetIamPolicy", + request_serializer=iam_policy.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy.Policy.FromString, + ) + return self._stubs["set_iam_policy"] + + @property + def get_iam_policy( + self, + ) -> Callable[[iam_policy.GetIamPolicyRequest], Awaitable[policy.Policy]]: + r"""Return a callable for the get iam policy method over gRPC. + + Gets the access control policy for a resource. + Returns an empty policy if the resource exists and does + not have a policy set. + + Returns: + Callable[[~.GetIamPolicyRequest], + Awaitable[~.Policy]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_iam_policy" not in self._stubs: + self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( + "/google.cloud.iot.v1.DeviceManager/GetIamPolicy", + request_serializer=iam_policy.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy.Policy.FromString, + ) + return self._stubs["get_iam_policy"] + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy.TestIamPermissionsRequest], + Awaitable[iam_policy.TestIamPermissionsResponse], + ]: + r"""Return a callable for the test iam permissions method over gRPC. + + Returns permissions that a caller has on the specified resource. + If the resource does not exist, this will return an empty set of + permissions, not a NOT_FOUND error. + + Returns: + Callable[[~.TestIamPermissionsRequest], + Awaitable[~.TestIamPermissionsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "test_iam_permissions" not in self._stubs: + self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( + "/google.cloud.iot.v1.DeviceManager/TestIamPermissions", + request_serializer=iam_policy.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy.TestIamPermissionsResponse.FromString, + ) + return self._stubs["test_iam_permissions"] + + @property + def send_command_to_device( + self, + ) -> Callable[ + [device_manager.SendCommandToDeviceRequest], + Awaitable[device_manager.SendCommandToDeviceResponse], + ]: + r"""Return a callable for the send command to device method over gRPC. + + Sends a command to the specified device. In order for a device + to be able to receive commands, it must: + + 1) be connected to Cloud IoT Core using the MQTT protocol, and + 2) be subscribed to the group of MQTT topics specified by + /devices/{device-id}/commands/#. This subscription will + receive commands at the top-level topic + /devices/{device-id}/commands as well as commands for + subfolders, like /devices/{device-id}/commands/subfolder. + Note that subscribing to specific subfolders is not + supported. If the command could not be delivered to the + device, this method will return an error; in particular, if + the device is not subscribed, this method will return + FAILED_PRECONDITION. Otherwise, this method will return OK. + If the subscription is QoS 1, at least once delivery will be + guaranteed; for QoS 0, no acknowledgment will be expected + from the device. + + Returns: + Callable[[~.SendCommandToDeviceRequest], + Awaitable[~.SendCommandToDeviceResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "send_command_to_device" not in self._stubs: + self._stubs["send_command_to_device"] = self.grpc_channel.unary_unary( + "/google.cloud.iot.v1.DeviceManager/SendCommandToDevice", + request_serializer=device_manager.SendCommandToDeviceRequest.serialize, + response_deserializer=device_manager.SendCommandToDeviceResponse.deserialize, + ) + return self._stubs["send_command_to_device"] + + @property + def bind_device_to_gateway( + self, + ) -> Callable[ + [device_manager.BindDeviceToGatewayRequest], + Awaitable[device_manager.BindDeviceToGatewayResponse], + ]: + r"""Return a callable for the bind device to gateway method over gRPC. + + Associates the device with the gateway. + + Returns: + Callable[[~.BindDeviceToGatewayRequest], + Awaitable[~.BindDeviceToGatewayResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "bind_device_to_gateway" not in self._stubs: + self._stubs["bind_device_to_gateway"] = self.grpc_channel.unary_unary( + "/google.cloud.iot.v1.DeviceManager/BindDeviceToGateway", + request_serializer=device_manager.BindDeviceToGatewayRequest.serialize, + response_deserializer=device_manager.BindDeviceToGatewayResponse.deserialize, + ) + return self._stubs["bind_device_to_gateway"] + + @property + def unbind_device_from_gateway( + self, + ) -> Callable[ + [device_manager.UnbindDeviceFromGatewayRequest], + Awaitable[device_manager.UnbindDeviceFromGatewayResponse], + ]: + r"""Return a callable for the unbind device from gateway method over gRPC. + + Deletes the association between the device and the + gateway. + + Returns: + Callable[[~.UnbindDeviceFromGatewayRequest], + Awaitable[~.UnbindDeviceFromGatewayResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "unbind_device_from_gateway" not in self._stubs: + self._stubs["unbind_device_from_gateway"] = self.grpc_channel.unary_unary( + "/google.cloud.iot.v1.DeviceManager/UnbindDeviceFromGateway", + request_serializer=device_manager.UnbindDeviceFromGatewayRequest.serialize, + response_deserializer=device_manager.UnbindDeviceFromGatewayResponse.deserialize, + ) + return self._stubs["unbind_device_from_gateway"] + + +__all__ = ("DeviceManagerGrpcAsyncIOTransport",) diff --git a/google/cloud/iot_v1/types.py b/google/cloud/iot_v1/types.py deleted file mode 100644 index fe70dabd..00000000 --- a/google/cloud/iot_v1/types.py +++ /dev/null @@ -1,66 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -from __future__ import absolute_import -import sys - -from google.api_core.protobuf_helpers import get_messages - -from google.cloud.iot_v1.proto import device_manager_pb2 -from google.cloud.iot_v1.proto import resources_pb2 -from google.iam.v1 import iam_policy_pb2 -from google.iam.v1 import options_pb2 -from google.iam.v1 import policy_pb2 -from google.protobuf import any_pb2 -from google.protobuf import empty_pb2 -from google.protobuf import field_mask_pb2 -from google.protobuf import timestamp_pb2 -from google.rpc import status_pb2 -from google.type import expr_pb2 - - -_shared_modules = [ - iam_policy_pb2, - options_pb2, - policy_pb2, - any_pb2, - empty_pb2, - field_mask_pb2, - timestamp_pb2, - status_pb2, - expr_pb2, -] - -_local_modules = [ - device_manager_pb2, - resources_pb2, -] - -names = [] - -for module in _shared_modules: # pragma: NO COVER - for name, message in get_messages(module).items(): - setattr(sys.modules[__name__], name, message) - names.append(name) -for module in _local_modules: - for name, message in get_messages(module).items(): - message.__module__ = "google.cloud.iot_v1.types" - setattr(sys.modules[__name__], name, message) - names.append(name) - - -__all__ = tuple(sorted(names)) diff --git a/google/cloud/iot_v1/types/__init__.py b/google/cloud/iot_v1/types/__init__.py new file mode 100644 index 00000000..37160f38 --- /dev/null +++ b/google/cloud/iot_v1/types/__init__.py @@ -0,0 +1,101 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from .resources import ( + Device, + GatewayConfig, + DeviceRegistry, + MqttConfig, + HttpConfig, + EventNotificationConfig, + StateNotificationConfig, + RegistryCredential, + X509CertificateDetails, + PublicKeyCertificate, + DeviceCredential, + PublicKeyCredential, + DeviceConfig, + DeviceState, +) +from .device_manager import ( + CreateDeviceRegistryRequest, + GetDeviceRegistryRequest, + DeleteDeviceRegistryRequest, + UpdateDeviceRegistryRequest, + ListDeviceRegistriesRequest, + ListDeviceRegistriesResponse, + CreateDeviceRequest, + GetDeviceRequest, + UpdateDeviceRequest, + DeleteDeviceRequest, + ListDevicesRequest, + GatewayListOptions, + ListDevicesResponse, + ModifyCloudToDeviceConfigRequest, + ListDeviceConfigVersionsRequest, + ListDeviceConfigVersionsResponse, + ListDeviceStatesRequest, + ListDeviceStatesResponse, + SendCommandToDeviceRequest, + SendCommandToDeviceResponse, + BindDeviceToGatewayRequest, + BindDeviceToGatewayResponse, + UnbindDeviceFromGatewayRequest, + UnbindDeviceFromGatewayResponse, +) + + +__all__ = ( + "Device", + "GatewayConfig", + "DeviceRegistry", + "MqttConfig", + "HttpConfig", + "EventNotificationConfig", + "StateNotificationConfig", + "RegistryCredential", + "X509CertificateDetails", + "PublicKeyCertificate", + "DeviceCredential", + "PublicKeyCredential", + "DeviceConfig", + "DeviceState", + "CreateDeviceRegistryRequest", + "GetDeviceRegistryRequest", + "DeleteDeviceRegistryRequest", + "UpdateDeviceRegistryRequest", + "ListDeviceRegistriesRequest", + "ListDeviceRegistriesResponse", + "CreateDeviceRequest", + "GetDeviceRequest", + "UpdateDeviceRequest", + "DeleteDeviceRequest", + "ListDevicesRequest", + "GatewayListOptions", + "ListDevicesResponse", + "ModifyCloudToDeviceConfigRequest", + "ListDeviceConfigVersionsRequest", + "ListDeviceConfigVersionsResponse", + "ListDeviceStatesRequest", + "ListDeviceStatesResponse", + "SendCommandToDeviceRequest", + "SendCommandToDeviceResponse", + "BindDeviceToGatewayRequest", + "BindDeviceToGatewayResponse", + "UnbindDeviceFromGatewayRequest", + "UnbindDeviceFromGatewayResponse", +) diff --git a/google/cloud/iot_v1/types/device_manager.py b/google/cloud/iot_v1/types/device_manager.py new file mode 100644 index 00000000..d118cb24 --- /dev/null +++ b/google/cloud/iot_v1/types/device_manager.py @@ -0,0 +1,549 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import proto # type: ignore + + +from google.cloud.iot_v1.types import resources +from google.protobuf import field_mask_pb2 as gp_field_mask # type: ignore + + +__protobuf__ = proto.module( + package="google.cloud.iot.v1", + manifest={ + "CreateDeviceRegistryRequest", + "GetDeviceRegistryRequest", + "DeleteDeviceRegistryRequest", + "UpdateDeviceRegistryRequest", + "ListDeviceRegistriesRequest", + "ListDeviceRegistriesResponse", + "CreateDeviceRequest", + "GetDeviceRequest", + "UpdateDeviceRequest", + "DeleteDeviceRequest", + "ListDevicesRequest", + "GatewayListOptions", + "ListDevicesResponse", + "ModifyCloudToDeviceConfigRequest", + "ListDeviceConfigVersionsRequest", + "ListDeviceConfigVersionsResponse", + "ListDeviceStatesRequest", + "ListDeviceStatesResponse", + "SendCommandToDeviceRequest", + "SendCommandToDeviceResponse", + "BindDeviceToGatewayRequest", + "BindDeviceToGatewayResponse", + "UnbindDeviceFromGatewayRequest", + "UnbindDeviceFromGatewayResponse", + }, +) + + +class CreateDeviceRegistryRequest(proto.Message): + r"""Request for ``CreateDeviceRegistry``. + + Attributes: + parent (str): + Required. The project and cloud region where this device + registry must be created. For example, + ``projects/example-project/locations/us-central1``. + device_registry (~.resources.DeviceRegistry): + Required. The device registry. The field ``name`` must be + empty. The server will generate that field from the device + registry ``id`` provided and the ``parent`` field. + """ + + parent = proto.Field(proto.STRING, number=1) + + device_registry = proto.Field( + proto.MESSAGE, number=2, message=resources.DeviceRegistry, + ) + + +class GetDeviceRegistryRequest(proto.Message): + r"""Request for ``GetDeviceRegistry``. + + Attributes: + name (str): + Required. The name of the device registry. For example, + ``projects/example-project/locations/us-central1/registries/my-registry``. + """ + + name = proto.Field(proto.STRING, number=1) + + +class DeleteDeviceRegistryRequest(proto.Message): + r"""Request for ``DeleteDeviceRegistry``. + + Attributes: + name (str): + Required. The name of the device registry. For example, + ``projects/example-project/locations/us-central1/registries/my-registry``. + """ + + name = proto.Field(proto.STRING, number=1) + + +class UpdateDeviceRegistryRequest(proto.Message): + r"""Request for ``UpdateDeviceRegistry``. + + Attributes: + device_registry (~.resources.DeviceRegistry): + Required. The new values for the device registry. The ``id`` + field must be empty, and the ``name`` field must indicate + the path of the resource. For example, + ``projects/example-project/locations/us-central1/registries/my-registry``. + update_mask (~.gp_field_mask.FieldMask): + Required. Only updates the ``device_registry`` fields + indicated by this mask. The field mask must not be empty, + and it must not contain fields that are immutable or only + set by the server. Mutable top-level fields: + ``event_notification_config``, ``http_config``, + ``mqtt_config``, and ``state_notification_config``. + """ + + device_registry = proto.Field( + proto.MESSAGE, number=1, message=resources.DeviceRegistry, + ) + + update_mask = proto.Field(proto.MESSAGE, number=2, message=gp_field_mask.FieldMask,) + + +class ListDeviceRegistriesRequest(proto.Message): + r"""Request for ``ListDeviceRegistries``. + + Attributes: + parent (str): + Required. The project and cloud region path. For example, + ``projects/example-project/locations/us-central1``. + page_size (int): + The maximum number of registries to return in the response. + If this value is zero, the service will select a default + size. A call may return fewer objects than requested. A + non-empty ``next_page_token`` in the response indicates that + more data is available. + page_token (str): + The value returned by the last + ``ListDeviceRegistriesResponse``; indicates that this is a + continuation of a prior ``ListDeviceRegistries`` call and + the system should return the next page of data. + """ + + parent = proto.Field(proto.STRING, number=1) + + page_size = proto.Field(proto.INT32, number=2) + + page_token = proto.Field(proto.STRING, number=3) + + +class ListDeviceRegistriesResponse(proto.Message): + r"""Response for ``ListDeviceRegistries``. + + Attributes: + device_registries (Sequence[~.resources.DeviceRegistry]): + The registries that matched the query. + next_page_token (str): + If not empty, indicates that there may be more registries + that match the request; this value should be passed in a new + ``ListDeviceRegistriesRequest``. + """ + + @property + def raw_page(self): + return self + + device_registries = proto.RepeatedField( + proto.MESSAGE, number=1, message=resources.DeviceRegistry, + ) + + next_page_token = proto.Field(proto.STRING, number=2) + + +class CreateDeviceRequest(proto.Message): + r"""Request for ``CreateDevice``. + + Attributes: + parent (str): + Required. The name of the device registry where this device + should be created. For example, + ``projects/example-project/locations/us-central1/registries/my-registry``. + device (~.resources.Device): + Required. The device registration details. The field + ``name`` must be empty. The server generates ``name`` from + the device registry ``id`` and the ``parent`` field. + """ + + parent = proto.Field(proto.STRING, number=1) + + device = proto.Field(proto.MESSAGE, number=2, message=resources.Device,) + + +class GetDeviceRequest(proto.Message): + r"""Request for ``GetDevice``. + + Attributes: + name (str): + Required. The name of the device. For example, + ``projects/p0/locations/us-central1/registries/registry0/devices/device0`` + or + ``projects/p0/locations/us-central1/registries/registry0/devices/{num_id}``. + field_mask (~.gp_field_mask.FieldMask): + The fields of the ``Device`` resource to be returned in the + response. If the field mask is unset or empty, all fields + are returned. + """ + + name = proto.Field(proto.STRING, number=1) + + field_mask = proto.Field(proto.MESSAGE, number=2, message=gp_field_mask.FieldMask,) + + +class UpdateDeviceRequest(proto.Message): + r"""Request for ``UpdateDevice``. + + Attributes: + device (~.resources.Device): + Required. The new values for the device. The ``id`` and + ``num_id`` fields must be empty, and the field ``name`` must + specify the name path. For example, + ``projects/p0/locations/us-central1/registries/registry0/devices/device0``\ or + ``projects/p0/locations/us-central1/registries/registry0/devices/{num_id}``. + update_mask (~.gp_field_mask.FieldMask): + Required. Only updates the ``device`` fields indicated by + this mask. The field mask must not be empty, and it must not + contain fields that are immutable or only set by the server. + Mutable top-level fields: ``credentials``, ``blocked``, and + ``metadata`` + """ + + device = proto.Field(proto.MESSAGE, number=2, message=resources.Device,) + + update_mask = proto.Field(proto.MESSAGE, number=3, message=gp_field_mask.FieldMask,) + + +class DeleteDeviceRequest(proto.Message): + r"""Request for ``DeleteDevice``. + + Attributes: + name (str): + Required. The name of the device. For example, + ``projects/p0/locations/us-central1/registries/registry0/devices/device0`` + or + ``projects/p0/locations/us-central1/registries/registry0/devices/{num_id}``. + """ + + name = proto.Field(proto.STRING, number=1) + + +class ListDevicesRequest(proto.Message): + r"""Request for ``ListDevices``. + + Attributes: + parent (str): + Required. The device registry path. Required. For example, + ``projects/my-project/locations/us-central1/registries/my-registry``. + device_num_ids (Sequence[int]): + A list of device numeric IDs. If empty, this + field is ignored. Maximum IDs: 10,000. + device_ids (Sequence[str]): + A list of device string IDs. For example, + ``['device0', 'device12']``. If empty, this field is + ignored. Maximum IDs: 10,000 + field_mask (~.gp_field_mask.FieldMask): + The fields of the ``Device`` resource to be returned in the + response. The fields ``id`` and ``num_id`` are always + returned, along with any other fields specified. + gateway_list_options (~.device_manager.GatewayListOptions): + Options related to gateways. + page_size (int): + The maximum number of devices to return in the response. If + this value is zero, the service will select a default size. + A call may return fewer objects than requested. A non-empty + ``next_page_token`` in the response indicates that more data + is available. + page_token (str): + The value returned by the last ``ListDevicesResponse``; + indicates that this is a continuation of a prior + ``ListDevices`` call and the system should return the next + page of data. + """ + + parent = proto.Field(proto.STRING, number=1) + + device_num_ids = proto.RepeatedField(proto.UINT64, number=2) + + device_ids = proto.RepeatedField(proto.STRING, number=3) + + field_mask = proto.Field(proto.MESSAGE, number=4, message=gp_field_mask.FieldMask,) + + gateway_list_options = proto.Field( + proto.MESSAGE, number=6, message="GatewayListOptions", + ) + + page_size = proto.Field(proto.INT32, number=100) + + page_token = proto.Field(proto.STRING, number=101) + + +class GatewayListOptions(proto.Message): + r"""Options for limiting the list based on gateway type and + associations. + + Attributes: + gateway_type (~.resources.GatewayType): + If ``GATEWAY`` is specified, only gateways are returned. If + ``NON_GATEWAY`` is specified, only non-gateway devices are + returned. If ``GATEWAY_TYPE_UNSPECIFIED`` is specified, all + devices are returned. + associations_gateway_id (str): + If set, only devices associated with the specified gateway + are returned. The gateway ID can be numeric (``num_id``) or + the user-defined string (``id``). For example, if ``123`` is + specified, only devices bound to the gateway with ``num_id`` + 123 are returned. + associations_device_id (str): + If set, returns only the gateways with which the specified + device is associated. The device ID can be numeric + (``num_id``) or the user-defined string (``id``). For + example, if ``456`` is specified, returns only the gateways + to which the device with ``num_id`` 456 is bound. + """ + + gateway_type = proto.Field( + proto.ENUM, number=1, oneof="filter", enum=resources.GatewayType, + ) + + associations_gateway_id = proto.Field(proto.STRING, number=2, oneof="filter") + + associations_device_id = proto.Field(proto.STRING, number=3, oneof="filter") + + +class ListDevicesResponse(proto.Message): + r"""Response for ``ListDevices``. + + Attributes: + devices (Sequence[~.resources.Device]): + The devices that match the request. + next_page_token (str): + If not empty, indicates that there may be more devices that + match the request; this value should be passed in a new + ``ListDevicesRequest``. + """ + + @property + def raw_page(self): + return self + + devices = proto.RepeatedField(proto.MESSAGE, number=1, message=resources.Device,) + + next_page_token = proto.Field(proto.STRING, number=2) + + +class ModifyCloudToDeviceConfigRequest(proto.Message): + r"""Request for ``ModifyCloudToDeviceConfig``. + + Attributes: + name (str): + Required. The name of the device. For example, + ``projects/p0/locations/us-central1/registries/registry0/devices/device0`` + or + ``projects/p0/locations/us-central1/registries/registry0/devices/{num_id}``. + version_to_update (int): + The version number to update. If this value + is zero, it will not check the version number of + the server and will always update the current + version; otherwise, this update will fail if the + version number found on the server does not + match this version number. This is used to + support multiple simultaneous updates without + losing data. + binary_data (bytes): + Required. The configuration data for the + device. + """ + + name = proto.Field(proto.STRING, number=1) + + version_to_update = proto.Field(proto.INT64, number=2) + + binary_data = proto.Field(proto.BYTES, number=3) + + +class ListDeviceConfigVersionsRequest(proto.Message): + r"""Request for ``ListDeviceConfigVersions``. + + Attributes: + name (str): + Required. The name of the device. For example, + ``projects/p0/locations/us-central1/registries/registry0/devices/device0`` + or + ``projects/p0/locations/us-central1/registries/registry0/devices/{num_id}``. + num_versions (int): + The number of versions to list. Versions are + listed in decreasing order of the version + number. The maximum number of versions retained + is 10. If this value is zero, it will return all + the versions available. + """ + + name = proto.Field(proto.STRING, number=1) + + num_versions = proto.Field(proto.INT32, number=2) + + +class ListDeviceConfigVersionsResponse(proto.Message): + r"""Response for ``ListDeviceConfigVersions``. + + Attributes: + device_configs (Sequence[~.resources.DeviceConfig]): + The device configuration for the last few + versions. Versions are listed in decreasing + order, starting from the most recent one. + """ + + device_configs = proto.RepeatedField( + proto.MESSAGE, number=1, message=resources.DeviceConfig, + ) + + +class ListDeviceStatesRequest(proto.Message): + r"""Request for ``ListDeviceStates``. + + Attributes: + name (str): + Required. The name of the device. For example, + ``projects/p0/locations/us-central1/registries/registry0/devices/device0`` + or + ``projects/p0/locations/us-central1/registries/registry0/devices/{num_id}``. + num_states (int): + The number of states to list. States are + listed in descending order of update time. The + maximum number of states retained is 10. If this + value is zero, it will return all the states + available. + """ + + name = proto.Field(proto.STRING, number=1) + + num_states = proto.Field(proto.INT32, number=2) + + +class ListDeviceStatesResponse(proto.Message): + r"""Response for ``ListDeviceStates``. + + Attributes: + device_states (Sequence[~.resources.DeviceState]): + The last few device states. States are listed + in descending order of server update time, + starting from the most recent one. + """ + + device_states = proto.RepeatedField( + proto.MESSAGE, number=1, message=resources.DeviceState, + ) + + +class SendCommandToDeviceRequest(proto.Message): + r"""Request for ``SendCommandToDevice``. + + Attributes: + name (str): + Required. The name of the device. For example, + ``projects/p0/locations/us-central1/registries/registry0/devices/device0`` + or + ``projects/p0/locations/us-central1/registries/registry0/devices/{num_id}``. + binary_data (bytes): + Required. The command data to send to the + device. + subfolder (str): + Optional subfolder for the command. If empty, + the command will be delivered to the + /devices/{device-id}/commands topic, otherwise + it will be delivered to the /devices/{device- + id}/commands/{subfolder} topic. Multi-level + subfolders are allowed. This field must not have + more than 256 characters, and must not contain + any MQTT wildcards ("+" or "#") or null + characters. + """ + + name = proto.Field(proto.STRING, number=1) + + binary_data = proto.Field(proto.BYTES, number=2) + + subfolder = proto.Field(proto.STRING, number=3) + + +class SendCommandToDeviceResponse(proto.Message): + r"""Response for ``SendCommandToDevice``.""" + + +class BindDeviceToGatewayRequest(proto.Message): + r"""Request for ``BindDeviceToGateway``. + + Attributes: + parent (str): + Required. The name of the registry. For example, + ``projects/example-project/locations/us-central1/registries/my-registry``. + gateway_id (str): + Required. The value of ``gateway_id`` can be either the + device numeric ID or the user-defined device identifier. + device_id (str): + Required. The device to associate with the specified + gateway. The value of ``device_id`` can be either the device + numeric ID or the user-defined device identifier. + """ + + parent = proto.Field(proto.STRING, number=1) + + gateway_id = proto.Field(proto.STRING, number=2) + + device_id = proto.Field(proto.STRING, number=3) + + +class BindDeviceToGatewayResponse(proto.Message): + r"""Response for ``BindDeviceToGateway``.""" + + +class UnbindDeviceFromGatewayRequest(proto.Message): + r"""Request for ``UnbindDeviceFromGateway``. + + Attributes: + parent (str): + Required. The name of the registry. For example, + ``projects/example-project/locations/us-central1/registries/my-registry``. + gateway_id (str): + Required. The value of ``gateway_id`` can be either the + device numeric ID or the user-defined device identifier. + device_id (str): + Required. The device to disassociate from the specified + gateway. The value of ``device_id`` can be either the device + numeric ID or the user-defined device identifier. + """ + + parent = proto.Field(proto.STRING, number=1) + + gateway_id = proto.Field(proto.STRING, number=2) + + device_id = proto.Field(proto.STRING, number=3) + + +class UnbindDeviceFromGatewayResponse(proto.Message): + r"""Response for ``UnbindDeviceFromGateway``.""" + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/iot_v1/types/resources.py b/google/cloud/iot_v1/types/resources.py new file mode 100644 index 00000000..8ca12ae3 --- /dev/null +++ b/google/cloud/iot_v1/types/resources.py @@ -0,0 +1,618 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import proto # type: ignore + + +from google.protobuf import timestamp_pb2 as timestamp # type: ignore +from google.rpc import status_pb2 as status # type: ignore + + +__protobuf__ = proto.module( + package="google.cloud.iot.v1", + manifest={ + "MqttState", + "HttpState", + "LogLevel", + "GatewayType", + "GatewayAuthMethod", + "PublicKeyCertificateFormat", + "PublicKeyFormat", + "Device", + "GatewayConfig", + "DeviceRegistry", + "MqttConfig", + "HttpConfig", + "EventNotificationConfig", + "StateNotificationConfig", + "RegistryCredential", + "X509CertificateDetails", + "PublicKeyCertificate", + "DeviceCredential", + "PublicKeyCredential", + "DeviceConfig", + "DeviceState", + }, +) + + +class MqttState(proto.Enum): + r"""Indicates whether an MQTT connection is enabled or disabled. + See the field description for details. + """ + MQTT_STATE_UNSPECIFIED = 0 + MQTT_ENABLED = 1 + MQTT_DISABLED = 2 + + +class HttpState(proto.Enum): + r"""Indicates whether DeviceService (HTTP) is enabled or disabled + for the registry. See the field description for details. + """ + HTTP_STATE_UNSPECIFIED = 0 + HTTP_ENABLED = 1 + HTTP_DISABLED = 2 + + +class LogLevel(proto.Enum): + r"""**Beta Feature** + + The logging verbosity for device activity. Specifies which events + should be written to logs. For example, if the LogLevel is ERROR, + only events that terminate in errors will be logged. LogLevel is + inclusive; enabling INFO logging will also enable ERROR logging. + """ + LOG_LEVEL_UNSPECIFIED = 0 + NONE = 10 + ERROR = 20 + INFO = 30 + DEBUG = 40 + + +class GatewayType(proto.Enum): + r"""Gateway type.""" + GATEWAY_TYPE_UNSPECIFIED = 0 + GATEWAY = 1 + NON_GATEWAY = 2 + + +class GatewayAuthMethod(proto.Enum): + r"""The gateway authorization/authentication method. This setting + determines how Cloud IoT Core authorizes/authenticate devices to + access the gateway. + """ + GATEWAY_AUTH_METHOD_UNSPECIFIED = 0 + ASSOCIATION_ONLY = 1 + DEVICE_AUTH_TOKEN_ONLY = 2 + ASSOCIATION_AND_DEVICE_AUTH_TOKEN = 3 + + +class PublicKeyCertificateFormat(proto.Enum): + r"""The supported formats for the public key.""" + UNSPECIFIED_PUBLIC_KEY_CERTIFICATE_FORMAT = 0 + X509_CERTIFICATE_PEM = 1 + + +class PublicKeyFormat(proto.Enum): + r"""The supported formats for the public key.""" + UNSPECIFIED_PUBLIC_KEY_FORMAT = 0 + RSA_PEM = 3 + RSA_X509_PEM = 1 + ES256_PEM = 2 + ES256_X509_PEM = 4 + + +class Device(proto.Message): + r"""The device resource. + + Attributes: + id (str): + The user-defined device identifier. The + device ID must be unique within a device + registry. + name (str): + The resource path name. For example, + ``projects/p1/locations/us-central1/registries/registry0/devices/dev0`` + or + ``projects/p1/locations/us-central1/registries/registry0/devices/{num_id}``. + When ``name`` is populated as a response from the service, + it always ends in the device numeric ID. + num_id (int): + [Output only] A server-defined unique numeric ID for the + device. This is a more compact way to identify devices, and + it is globally unique. + credentials (Sequence[~.resources.DeviceCredential]): + The credentials used to authenticate this device. To allow + credential rotation without interruption, multiple device + credentials can be bound to this device. No more than 3 + credentials can be bound to a single device at a time. When + new credentials are added to a device, they are verified + against the registry credentials. For details, see the + description of the ``DeviceRegistry.credentials`` field. + last_heartbeat_time (~.timestamp.Timestamp): + [Output only] The last time an MQTT ``PINGREQ`` was + received. This field applies only to devices connecting + through MQTT. MQTT clients usually only send ``PINGREQ`` + messages if the connection is idle, and no other messages + have been sent. Timestamps are periodically collected and + written to storage; they may be stale by a few minutes. + last_event_time (~.timestamp.Timestamp): + [Output only] The last time a telemetry event was received. + Timestamps are periodically collected and written to + storage; they may be stale by a few minutes. + last_state_time (~.timestamp.Timestamp): + [Output only] The last time a state event was received. + Timestamps are periodically collected and written to + storage; they may be stale by a few minutes. + last_config_ack_time (~.timestamp.Timestamp): + [Output only] The last time a cloud-to-device config version + acknowledgment was received from the device. This field is + only for configurations sent through MQTT. + last_config_send_time (~.timestamp.Timestamp): + [Output only] The last time a cloud-to-device config version + was sent to the device. + blocked (bool): + If a device is blocked, connections or + requests from this device will fail. Can be used + to temporarily prevent the device from + connecting if, for example, the sensor is + generating bad data and needs maintenance. + last_error_time (~.timestamp.Timestamp): + [Output only] The time the most recent error occurred, such + as a failure to publish to Cloud Pub/Sub. This field is the + timestamp of 'last_error_status'. + last_error_status (~.status.Status): + [Output only] The error message of the most recent error, + such as a failure to publish to Cloud Pub/Sub. + 'last_error_time' is the timestamp of this field. If no + errors have occurred, this field has an empty message and + the status code 0 == OK. Otherwise, this field is expected + to have a status code other than OK. + config (~.resources.DeviceConfig): + The most recent device configuration, which is eventually + sent from Cloud IoT Core to the device. If not present on + creation, the configuration will be initialized with an + empty payload and version value of ``1``. To update this + field after creation, use the + ``DeviceManager.ModifyCloudToDeviceConfig`` method. + state (~.resources.DeviceState): + [Output only] The state most recently received from the + device. If no state has been reported, this field is not + present. + log_level (~.resources.LogLevel): + **Beta Feature** + + The logging verbosity for device activity. If unspecified, + DeviceRegistry.log_level will be used. + metadata (Sequence[~.resources.Device.MetadataEntry]): + The metadata key-value pairs assigned to the device. This + metadata is not interpreted or indexed by Cloud IoT Core. It + can be used to add contextual information for the device. + + Keys must conform to the regular expression + [a-zA-Z][a-zA-Z0-9-_.+~%]+ and be less than 128 bytes in + length. + + Values are free-form strings. Each value must be less than + or equal to 32 KB in size. + + The total size of all keys and values must be less than 256 + KB, and the maximum number of key-value pairs is 500. + gateway_config (~.resources.GatewayConfig): + Gateway-related configuration and state. + """ + + id = proto.Field(proto.STRING, number=1) + + name = proto.Field(proto.STRING, number=2) + + num_id = proto.Field(proto.UINT64, number=3) + + credentials = proto.RepeatedField( + proto.MESSAGE, number=12, message="DeviceCredential", + ) + + last_heartbeat_time = proto.Field( + proto.MESSAGE, number=7, message=timestamp.Timestamp, + ) + + last_event_time = proto.Field(proto.MESSAGE, number=8, message=timestamp.Timestamp,) + + last_state_time = proto.Field( + proto.MESSAGE, number=20, message=timestamp.Timestamp, + ) + + last_config_ack_time = proto.Field( + proto.MESSAGE, number=14, message=timestamp.Timestamp, + ) + + last_config_send_time = proto.Field( + proto.MESSAGE, number=18, message=timestamp.Timestamp, + ) + + blocked = proto.Field(proto.BOOL, number=19) + + last_error_time = proto.Field( + proto.MESSAGE, number=10, message=timestamp.Timestamp, + ) + + last_error_status = proto.Field(proto.MESSAGE, number=11, message=status.Status,) + + config = proto.Field(proto.MESSAGE, number=13, message="DeviceConfig",) + + state = proto.Field(proto.MESSAGE, number=16, message="DeviceState",) + + log_level = proto.Field(proto.ENUM, number=21, enum="LogLevel",) + + metadata = proto.MapField(proto.STRING, proto.STRING, number=17) + + gateway_config = proto.Field(proto.MESSAGE, number=24, message="GatewayConfig",) + + +class GatewayConfig(proto.Message): + r"""Gateway-related configuration and state. + + Attributes: + gateway_type (~.resources.GatewayType): + Indicates whether the device is a gateway. + gateway_auth_method (~.resources.GatewayAuthMethod): + Indicates how to authorize and/or + authenticate devices to access the gateway. + last_accessed_gateway_id (str): + [Output only] The ID of the gateway the device accessed most + recently. + last_accessed_gateway_time (~.timestamp.Timestamp): + [Output only] The most recent time at which the device + accessed the gateway specified in ``last_accessed_gateway``. + """ + + gateway_type = proto.Field(proto.ENUM, number=1, enum="GatewayType",) + + gateway_auth_method = proto.Field(proto.ENUM, number=2, enum="GatewayAuthMethod",) + + last_accessed_gateway_id = proto.Field(proto.STRING, number=3) + + last_accessed_gateway_time = proto.Field( + proto.MESSAGE, number=4, message=timestamp.Timestamp, + ) + + +class DeviceRegistry(proto.Message): + r"""A container for a group of devices. + + Attributes: + id (str): + The identifier of this device registry. For example, + ``myRegistry``. + name (str): + The resource path name. For example, + ``projects/example-project/locations/us-central1/registries/my-registry``. + event_notification_configs (Sequence[~.resources.EventNotificationConfig]): + The configuration for notification of + telemetry events received from the device. All + telemetry events that were successfully + published by the device and acknowledged by + Cloud IoT Core are guaranteed to be delivered to + Cloud Pub/Sub. If multiple configurations match + a message, only the first matching configuration + is used. If you try to publish a device + telemetry event using MQTT without specifying a + Cloud Pub/Sub topic for the device's registry, + the connection closes automatically. If you try + to do so using an HTTP connection, an error is + returned. Up to 10 configurations may be + provided. + state_notification_config (~.resources.StateNotificationConfig): + The configuration for notification of new + states received from the device. State updates + are guaranteed to be stored in the state + history, but notifications to Cloud Pub/Sub are + not guaranteed. For example, if permissions are + misconfigured or the specified topic doesn't + exist, no notification will be published but the + state will still be stored in Cloud IoT Core. + mqtt_config (~.resources.MqttConfig): + The MQTT configuration for this device + registry. + http_config (~.resources.HttpConfig): + The DeviceService (HTTP) configuration for + this device registry. + log_level (~.resources.LogLevel): + **Beta Feature** + + The default logging verbosity for activity from devices in + this registry. The verbosity level can be overridden by + Device.log_level. + credentials (Sequence[~.resources.RegistryCredential]): + The credentials used to verify the device + credentials. No more than 10 credentials can be + bound to a single registry at a time. The + verification process occurs at the time of + device creation or update. If this field is + empty, no verification is performed. Otherwise, + the credentials of a newly created device or + added credentials of an updated device should be + signed with one of these registry credentials. + + Note, however, that existing devices will never + be affected by modifications to this list of + credentials: after a device has been + successfully created in a registry, it should be + able to connect even if its registry credentials + are revoked, deleted, or modified. + """ + + id = proto.Field(proto.STRING, number=1) + + name = proto.Field(proto.STRING, number=2) + + event_notification_configs = proto.RepeatedField( + proto.MESSAGE, number=10, message="EventNotificationConfig", + ) + + state_notification_config = proto.Field( + proto.MESSAGE, number=7, message="StateNotificationConfig", + ) + + mqtt_config = proto.Field(proto.MESSAGE, number=4, message="MqttConfig",) + + http_config = proto.Field(proto.MESSAGE, number=9, message="HttpConfig",) + + log_level = proto.Field(proto.ENUM, number=11, enum="LogLevel",) + + credentials = proto.RepeatedField( + proto.MESSAGE, number=8, message="RegistryCredential", + ) + + +class MqttConfig(proto.Message): + r"""The configuration of MQTT for a device registry. + + Attributes: + mqtt_enabled_state (~.resources.MqttState): + If enabled, allows connections using the MQTT + protocol. Otherwise, MQTT connections to this + registry will fail. + """ + + mqtt_enabled_state = proto.Field(proto.ENUM, number=1, enum="MqttState",) + + +class HttpConfig(proto.Message): + r"""The configuration of the HTTP bridge for a device registry. + + Attributes: + http_enabled_state (~.resources.HttpState): + If enabled, allows devices to use + DeviceService via the HTTP protocol. Otherwise, + any requests to DeviceService will fail for this + registry. + """ + + http_enabled_state = proto.Field(proto.ENUM, number=1, enum="HttpState",) + + +class EventNotificationConfig(proto.Message): + r"""The configuration for forwarding telemetry events. + + Attributes: + subfolder_matches (str): + If the subfolder name matches this string + exactly, this configuration will be used. The + string must not include the leading '/' + character. If empty, all strings are matched. + This field is used only for telemetry events; + subfolders are not supported for state changes. + pubsub_topic_name (str): + A Cloud Pub/Sub topic name. For example, + ``projects/myProject/topics/deviceEvents``. + """ + + subfolder_matches = proto.Field(proto.STRING, number=2) + + pubsub_topic_name = proto.Field(proto.STRING, number=1) + + +class StateNotificationConfig(proto.Message): + r"""The configuration for notification of new states received + from the device. + + Attributes: + pubsub_topic_name (str): + A Cloud Pub/Sub topic name. For example, + ``projects/myProject/topics/deviceEvents``. + """ + + pubsub_topic_name = proto.Field(proto.STRING, number=1) + + +class RegistryCredential(proto.Message): + r"""A server-stored registry credential used to validate device + credentials. + + Attributes: + public_key_certificate (~.resources.PublicKeyCertificate): + A public key certificate used to verify the + device credentials. + """ + + public_key_certificate = proto.Field( + proto.MESSAGE, number=1, oneof="credential", message="PublicKeyCertificate", + ) + + +class X509CertificateDetails(proto.Message): + r"""Details of an X.509 certificate. For informational purposes + only. + + Attributes: + issuer (str): + The entity that signed the certificate. + subject (str): + The entity the certificate and public key + belong to. + start_time (~.timestamp.Timestamp): + The time the certificate becomes valid. + expiry_time (~.timestamp.Timestamp): + The time the certificate becomes invalid. + signature_algorithm (str): + The algorithm used to sign the certificate. + public_key_type (str): + The type of public key in the certificate. + """ + + issuer = proto.Field(proto.STRING, number=1) + + subject = proto.Field(proto.STRING, number=2) + + start_time = proto.Field(proto.MESSAGE, number=3, message=timestamp.Timestamp,) + + expiry_time = proto.Field(proto.MESSAGE, number=4, message=timestamp.Timestamp,) + + signature_algorithm = proto.Field(proto.STRING, number=5) + + public_key_type = proto.Field(proto.STRING, number=6) + + +class PublicKeyCertificate(proto.Message): + r"""A public key certificate format and data. + + Attributes: + format (~.resources.PublicKeyCertificateFormat): + The certificate format. + certificate (str): + The certificate data. + x509_details (~.resources.X509CertificateDetails): + [Output only] The certificate details. Used only for X.509 + certificates. + """ + + format = proto.Field(proto.ENUM, number=1, enum="PublicKeyCertificateFormat",) + + certificate = proto.Field(proto.STRING, number=2) + + x509_details = proto.Field(proto.MESSAGE, number=3, message=X509CertificateDetails,) + + +class DeviceCredential(proto.Message): + r"""A server-stored device credential used for authentication. + + Attributes: + public_key (~.resources.PublicKeyCredential): + A public key used to verify the signature of + JSON Web Tokens (JWTs). When adding a new device + credential, either via device creation or via + modifications, this public key credential may be + required to be signed by one of the registry + level certificates. More specifically, if the + registry contains at least one certificate, any + new device credential must be signed by one of + the registry certificates. As a result, when the + registry contains certificates, only X.509 + certificates are accepted as device credentials. + However, if the registry does not contain a + certificate, self-signed certificates and public + keys will be accepted. New device credentials + must be different from every registry-level + certificate. + expiration_time (~.timestamp.Timestamp): + [Optional] The time at which this credential becomes + invalid. This credential will be ignored for new client + authentication requests after this timestamp; however, it + will not be automatically deleted. + """ + + public_key = proto.Field( + proto.MESSAGE, number=2, oneof="credential", message="PublicKeyCredential", + ) + + expiration_time = proto.Field(proto.MESSAGE, number=6, message=timestamp.Timestamp,) + + +class PublicKeyCredential(proto.Message): + r"""A public key format and data. + + Attributes: + format (~.resources.PublicKeyFormat): + The format of the key. + key (str): + The key data. + """ + + format = proto.Field(proto.ENUM, number=1, enum="PublicKeyFormat",) + + key = proto.Field(proto.STRING, number=2) + + +class DeviceConfig(proto.Message): + r"""The device configuration. Eventually delivered to devices. + + Attributes: + version (int): + [Output only] The version of this update. The version number + is assigned by the server, and is always greater than 0 + after device creation. The version must be 0 on the + ``CreateDevice`` request if a ``config`` is specified; the + response of ``CreateDevice`` will always have a value of 1. + cloud_update_time (~.timestamp.Timestamp): + [Output only] The time at which this configuration version + was updated in Cloud IoT Core. This timestamp is set by the + server. + device_ack_time (~.timestamp.Timestamp): + [Output only] The time at which Cloud IoT Core received the + acknowledgment from the device, indicating that the device + has received this configuration version. If this field is + not present, the device has not yet acknowledged that it + received this version. Note that when the config was sent to + the device, many config versions may have been available in + Cloud IoT Core while the device was disconnected, and on + connection, only the latest version is sent to the device. + Some versions may never be sent to the device, and therefore + are never acknowledged. This timestamp is set by Cloud IoT + Core. + binary_data (bytes): + The device configuration data. + """ + + version = proto.Field(proto.INT64, number=1) + + cloud_update_time = proto.Field( + proto.MESSAGE, number=2, message=timestamp.Timestamp, + ) + + device_ack_time = proto.Field(proto.MESSAGE, number=3, message=timestamp.Timestamp,) + + binary_data = proto.Field(proto.BYTES, number=4) + + +class DeviceState(proto.Message): + r"""The device state, as reported by the device. + + Attributes: + update_time (~.timestamp.Timestamp): + [Output only] The time at which this state version was + updated in Cloud IoT Core. + binary_data (bytes): + The device state data. + """ + + update_time = proto.Field(proto.MESSAGE, number=1, message=timestamp.Timestamp,) + + binary_data = proto.Field(proto.BYTES, number=2) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/mypy.ini b/mypy.ini new file mode 100644 index 00000000..4505b485 --- /dev/null +++ b/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.6 +namespace_packages = True diff --git a/noxfile.py b/noxfile.py index bc20bc17..132eded7 100644 --- a/noxfile.py +++ b/noxfile.py @@ -27,8 +27,8 @@ BLACK_PATHS = ["docs", "google", "tests", "noxfile.py", "setup.py"] DEFAULT_PYTHON_VERSION = "3.8" -SYSTEM_TEST_PYTHON_VERSIONS = ["2.7", "3.8"] -UNIT_TEST_PYTHON_VERSIONS = ["2.7", "3.5", "3.6", "3.7", "3.8"] +SYSTEM_TEST_PYTHON_VERSIONS = ["3.8"] +UNIT_TEST_PYTHON_VERSIONS = ["3.6", "3.7", "3.8"] @nox.session(python=DEFAULT_PYTHON_VERSION) @@ -70,6 +70,8 @@ def lint_setup_py(session): def default(session): # Install all test dependencies, then install this package in-place. + session.install("asyncmock", "pytest-asyncio") + session.install("mock", "pytest", "pytest-cov") session.install("-e", ".") @@ -139,7 +141,7 @@ def cover(session): test runs (not system test runs), and then erases coverage data. """ session.install("coverage", "pytest-cov") - session.run("coverage", "report", "--show-missing", "--fail-under=74") + session.run("coverage", "report", "--show-missing", "--fail-under=99") session.run("coverage", "erase") diff --git a/samples/api-client/manager/manager.py b/samples/api-client/manager/manager.py index 1701940b..5d2e4ef5 100644 --- a/samples/api-client/manager/manager.py +++ b/samples/api-client/manager/manager.py @@ -38,6 +38,7 @@ from google.cloud import iot_v1 from google.cloud import pubsub from google.oauth2 import service_account +from google.protobuf import field_mask_pb2 as gp_field_mask from googleapiclient import discovery from googleapiclient.errors import HttpError @@ -51,8 +52,9 @@ def create_iot_topic(project, topic_name): policy = pubsub_client.get_iam_policy(topic_path) policy.bindings.add( - role='roles/pubsub.publisher', - members=['serviceAccount:cloud-iot@system.gserviceaccount.com']) + role="roles/pubsub.publisher", + members=["serviceAccount:cloud-iot@system.gserviceaccount.com"], + ) pubsub_client.set_iam_policy(topic_path, policy) @@ -62,28 +64,34 @@ def create_iot_topic(project, topic_name): def get_client(service_account_json): """Returns an authorized API client by discovering the IoT API and creating a service object using the service account credentials JSON.""" - api_scopes = ['https://www.googleapis.com/auth/cloud-platform'] - api_version = 'v1' - discovery_api = 'https://cloudiot.googleapis.com/$discovery/rest' - service_name = 'cloudiotcore' + api_scopes = ["https://www.googleapis.com/auth/cloud-platform"] + api_version = "v1" + discovery_api = "https://cloudiot.googleapis.com/$discovery/rest" + service_name = "cloudiotcore" credentials = service_account.Credentials.from_service_account_file( - service_account_json) + service_account_json + ) scoped_credentials = credentials.with_scopes(api_scopes) - discovery_url = '{}?version={}'.format( - discovery_api, api_version) + discovery_url = "{}?version={}".format(discovery_api, api_version) return discovery.build( - service_name, - api_version, - discoveryServiceUrl=discovery_url, - credentials=scoped_credentials) + service_name, + api_version, + discoveryServiceUrl=discovery_url, + credentials=scoped_credentials, + ) def create_rs256_device( - service_account_json, project_id, cloud_region, registry_id, device_id, - certificate_file): + service_account_json, + project_id, + cloud_region, + registry_id, + device_id, + certificate_file, +): """Create a new device with the given id, using RS256 for authentication.""" # [START iot_create_rsa_device] @@ -102,22 +110,29 @@ def create_rs256_device( # Note: You can have multiple credentials associated with a device. device_template = { - 'id': device_id, - 'credentials': [{ - 'public_key': { - 'format': 'RSA_X509_PEM', - 'key': certificate + "id": device_id, + "credentials": [ + { + "public_key": { + "format": iot_v1.PublicKeyFormat.RSA_X509_PEM, + "key": certificate, + } } - }] + ], } - return client.create_device(parent, device_template) + return client.create_device(request={"parent": parent, "device": device_template}) # [END iot_create_rsa_device] def create_es256_device( - service_account_json, project_id, cloud_region, registry_id, - device_id, public_key_file): + service_account_json, + project_id, + cloud_region, + registry_id, + device_id, + public_key_file, +): """Create a new device with the given id, using ES256 for authentication.""" # [START iot_create_es_device] @@ -136,22 +151,24 @@ def create_es256_device( # Note: You can have multiple credentials associated with a device. device_template = { - 'id': device_id, - 'credentials': [{ - 'public_key': { - 'format': 'ES256_PEM', - 'key': public_key + "id": device_id, + "credentials": [ + { + "public_key": { + "format": iot_v1.PublicKeyFormat.ES256_PEM, + "key": public_key, + } } - }] + ], } - return client.create_device(parent, device_template) + return client.create_device(request={"parent": parent, "device": device_template}) # [END iot_create_es_device] def create_device( - service_account_json, project_id, cloud_region, registry_id, - device_id): + service_account_json, project_id, cloud_region, registry_id, device_id +): """Create a device to bind to a gateway if it does not exist.""" # [START iot_create_device] # project_id = 'YOUR_PROJECT_ID' @@ -166,7 +183,7 @@ def create_device( parent = client.registry_path(project_id, cloud_region, registry_id) - devices = list(client.list_devices(parent=parent)) + devices = list(client.list_devices(request={"parent": parent})) for device in devices: if device.id == device_id: @@ -174,24 +191,26 @@ def create_device( # Create the device device_template = { - 'id': device_id, - 'gateway_config': { - 'gateway_type': 'NON_GATEWAY', - 'gateway_auth_method': 'ASSOCIATION_ONLY' - } + "id": device_id, + "gateway_config": { + "gateway_type": iot_v1.GatewayType.NON_GATEWAY, + "gateway_auth_method": iot_v1.GatewayAuthMethod.ASSOCIATION_ONLY, + }, } if not exists: - res = client.create_device(parent, device_template) - print('Created Device {}'.format(res)) + res = client.create_device( + request={"parent": parent, "device": device_template} + ) + print("Created Device {}".format(res)) else: - print('Device exists, skipping') + print("Device exists, skipping") # [END iot_create_device] def create_unauth_device( - service_account_json, project_id, cloud_region, registry_id, - device_id): + service_account_json, project_id, cloud_region, registry_id, device_id +): """Create a new device without authentication.""" # [START iot_create_unauth_device] # project_id = 'YOUR_PROJECT_ID' @@ -203,104 +222,97 @@ def create_unauth_device( parent = client.registry_path(project_id, cloud_region, registry_id) device_template = { - 'id': device_id, + "id": device_id, } - return client.create_device(parent, device_template) + return client.create_device(request={"parent": parent, "device": device_template}) # [END iot_create_unauth_device] def delete_device( - service_account_json, project_id, cloud_region, registry_id, - device_id): + service_account_json, project_id, cloud_region, registry_id, device_id +): """Delete the device with the given id.""" # [START iot_delete_device] # project_id = 'YOUR_PROJECT_ID' # cloud_region = 'us-central1' # registry_id = 'your-registry-id' # device_id = 'your-device-id' - print('Delete device') + print("Delete device") client = iot_v1.DeviceManagerClient() - device_path = client.device_path( - project_id, cloud_region, registry_id, device_id) + device_path = client.device_path(project_id, cloud_region, registry_id, device_id) - return client.delete_device(device_path) + return client.delete_device(request={"name": device_path}) # [END iot_delete_device] -def delete_registry( - service_account_json, project_id, cloud_region, registry_id): +def delete_registry(service_account_json, project_id, cloud_region, registry_id): """Deletes the specified registry.""" # [START iot_delete_registry] # project_id = 'YOUR_PROJECT_ID' # cloud_region = 'us-central1' # registry_id = 'your-registry-id' - print('Delete registry') + print("Delete registry") client = iot_v1.DeviceManagerClient() registry_path = client.registry_path(project_id, cloud_region, registry_id) try: - client.delete_device_registry(registry_path) - print('Deleted registry') - return 'Registry deleted' + client.delete_device_registry(request={"name": registry_path}) + print("Deleted registry") + return "Registry deleted" except HttpError: - print('Error, registry not deleted') + print("Error, registry not deleted") raise # [END iot_delete_registry] -def get_device( - service_account_json, project_id, cloud_region, registry_id, - device_id): +def get_device(service_account_json, project_id, cloud_region, registry_id, device_id): """Retrieve the device with the given id.""" # [START iot_get_device] # project_id = 'YOUR_PROJECT_ID' # cloud_region = 'us-central1' # registry_id = 'your-registry-id' # device_id = 'your-device-id' - print('Getting device') + print("Getting device") client = iot_v1.DeviceManagerClient() - device_path = client.device_path( - project_id, cloud_region, registry_id, device_id) + device_path = client.device_path(project_id, cloud_region, registry_id, device_id) - device = client.get_device(device_path) + device = client.get_device(request={"name": device_path}) - print('Id : {}'.format(device.id)) - print('Name : {}'.format(device.name)) - print('Credentials:') + print("Id : {}".format(device.id)) + print("Name : {}".format(device.name)) + print("Credentials:") if device.credentials is not None: for credential in device.credentials: keyinfo = credential.public_key - print('\tcertificate: \n{}'.format(keyinfo.key)) + print("\tcertificate: \n{}".format(keyinfo.key)) if keyinfo.format == 4: - keyformat = 'ES256_X509_PEM' + keyformat = "ES256_X509_PEM" elif keyinfo.format == 3: - keyformat = 'RSA_PEM' + keyformat = "RSA_PEM" elif keyinfo.format == 2: - keyformat = 'ES256_PEM' + keyformat = "ES256_PEM" elif keyinfo.format == 1: - keyformat = 'RSA_X509_PEM' + keyformat = "RSA_X509_PEM" else: - keyformat = 'UNSPECIFIED_PUBLIC_KEY_FORMAT' - print('\tformat : {}'.format(keyformat)) - print('\texpiration: {}'.format(credential.expiration_time)) + keyformat = "UNSPECIFIED_PUBLIC_KEY_FORMAT" + print("\tformat : {}".format(keyformat)) + print("\texpiration: {}".format(credential.expiration_time)) - print('Config:') - print('\tdata: {}'.format(device.config.binary_data)) - print('\tversion: {}'.format(device.config.version)) - print('\tcloudUpdateTime: {}'.format(device.config.cloud_update_time)) + print("Config:") + print("\tdata: {}".format(device.config.binary_data)) + print("\tversion: {}".format(device.config.version)) + print("\tcloudUpdateTime: {}".format(device.config.cloud_update_time)) return device # [END iot_get_device] -def get_state( - service_account_json, project_id, cloud_region, registry_id, - device_id): +def get_state(service_account_json, project_id, cloud_region, registry_id, device_id): """Retrieve a device's state blobs.""" # [START iot_get_device_state] # project_id = 'YOUR_PROJECT_ID' @@ -308,36 +320,34 @@ def get_state( # registry_id = 'your-registry-id' # device_id = 'your-device-id' client = iot_v1.DeviceManagerClient() - device_path = client.device_path( - project_id, cloud_region, registry_id, device_id) + device_path = client.device_path(project_id, cloud_region, registry_id, device_id) - device = client.get_device(device_path) - print('Last state: {}'.format(device.state)) + device = client.get_device(request={"name": device_path}) + print("Last state: {}".format(device.state)) - print('State history') - states = client.list_device_states(device_path).device_states + print("State history") + states = client.list_device_states(request={"name": device_path}).device_states for state in states: - print('State: {}'.format(state)) + print("State: {}".format(state)) return states # [END iot_get_device_state] -def list_devices( - service_account_json, project_id, cloud_region, registry_id): +def list_devices(service_account_json, project_id, cloud_region, registry_id): """List all devices in the registry.""" # [START iot_list_devices] # project_id = 'YOUR_PROJECT_ID' # cloud_region = 'us-central1' # registry_id = 'your-registry-id' - print('Listing devices') + print("Listing devices") client = iot_v1.DeviceManagerClient() registry_path = client.registry_path(project_id, cloud_region, registry_id) - devices = list(client.list_devices(parent=registry_path)) + devices = list(client.list_devices(request={"parent": registry_path})) for device in devices: - print('Device: {} : {}'.format(device.num_id, device.id)) + print("Device: {} : {}".format(device.num_id, device.id)) return devices # [END iot_list_devices] @@ -348,23 +358,21 @@ def list_registries(service_account_json, project_id, cloud_region): # [START iot_list_registries] # project_id = 'YOUR_PROJECT_ID' # cloud_region = 'us-central1' - print('Listing Registries') + print("Listing Registries") client = iot_v1.DeviceManagerClient() - parent = client.location_path(project_id, cloud_region) + parent = f"projects/{project_id}/locations/{cloud_region}" - registries = list(client.list_device_registries(parent)) + registries = list(client.list_device_registries(request={"parent": parent})) for registry in registries: - print('id: {}\n\tname: {}'.format( - registry.id, - registry.name)) + print("id: {}\n\tname: {}".format(registry.id, registry.name)) return registries # [END iot_list_registries] def create_registry( - service_account_json, project_id, cloud_region, pubsub_topic, - registry_id): + service_account_json, project_id, cloud_region, pubsub_topic, registry_id +): """ Creates a registry and returns the result. Returns an empty result if the registry already exists.""" # [START iot_create_registry] @@ -373,33 +381,32 @@ def create_registry( # pubsub_topic = 'your-pubsub-topic' # registry_id = 'your-registry-id' client = iot_v1.DeviceManagerClient() - parent = client.location_path(project_id, cloud_region) + parent = f"projects/{project_id}/locations/{cloud_region}" - if not pubsub_topic.startswith('projects/'): - pubsub_topic = 'projects/{}/topics/{}'.format(project_id, pubsub_topic) + if not pubsub_topic.startswith("projects/"): + pubsub_topic = "projects/{}/topics/{}".format(project_id, pubsub_topic) body = { - 'event_notification_configs': [{ - 'pubsub_topic_name': pubsub_topic - }], - 'id': registry_id + "event_notification_configs": [{"pubsub_topic_name": pubsub_topic}], + "id": registry_id, } try: - response = client.create_device_registry(parent, body) - print('Created registry') + response = client.create_device_registry( + request={"parent": parent, "device_registry": body} + ) + print("Created registry") return response except HttpError: - print('Error, registry not created') + print("Error, registry not created") raise except AlreadyExists: - print('Error, registry already exists') + print("Error, registry already exists") raise # [END iot_create_registry] -def get_registry( - service_account_json, project_id, cloud_region, registry_id): +def get_registry(service_account_json, project_id, cloud_region, registry_id): """ Retrieves a device registry.""" # [START iot_get_registry] # project_id = 'YOUR_PROJECT_ID' @@ -408,40 +415,43 @@ def get_registry( client = iot_v1.DeviceManagerClient() registry_path = client.registry_path(project_id, cloud_region, registry_id) - return client.get_device_registry(registry_path) + return client.get_device_registry(request={"name": registry_path}) # [END iot_get_registry] def open_registry( - service_account_json, project_id, cloud_region, pubsub_topic, - registry_id): + service_account_json, project_id, cloud_region, pubsub_topic, registry_id +): """Gets or creates a device registry.""" # project_id = 'YOUR_PROJECT_ID' # cloud_region = 'us-central1' # pubsub_topic = 'your-pubsub-topic' # registry_id = 'your-registry-id' - print('Creating registry') + print("Creating registry") try: response = create_registry( - service_account_json, project_id, cloud_region, - pubsub_topic, registry_id) + service_account_json, project_id, cloud_region, pubsub_topic, registry_id + ) except AlreadyExists: # Device registry already exists. We just re-use the existing one. - print( - 'Registry {} already exists - looking it up instead.'.format( - registry_id)) + print("Registry {} already exists - looking it up instead.".format(registry_id)) response = get_registry( - service_account_json, project_id, cloud_region, - registry_id) + service_account_json, project_id, cloud_region, registry_id + ) - print('Registry {} opened: '.format(response.name)) + print("Registry {} opened: ".format(response.name)) print(response) def patch_es256_auth( - service_account_json, project_id, cloud_region, registry_id, - device_id, public_key_file): + service_account_json, + project_id, + cloud_region, + registry_id, + device_id, + public_key_file, +): """Patch the device to add an ES256 public key to the device.""" # [START iot_patch_es] # project_id = 'YOUR_PROJECT_ID' @@ -449,39 +459,41 @@ def patch_es256_auth( # registry_id = 'your-registry-id' # device_id = 'your-device-id' # public_key_file = 'path/to/certificate.pem' - print('Patch device with ES256 certificate') + print("Patch device with ES256 certificate") client = iot_v1.DeviceManagerClient() - device_path = client.device_path( - project_id, cloud_region, registry_id, device_id) + device_path = client.device_path(project_id, cloud_region, registry_id, device_id) - public_key_bytes = '' + public_key_bytes = "" with io.open(public_key_file) as f: public_key_bytes = f.read() - key = iot_v1.types.PublicKeyCredential( - format='ES256_PEM', - key=public_key_bytes) + key = iot_v1.PublicKeyCredential( + format=iot_v1.PublicKeyFormat.ES256_PEM, key=public_key_bytes + ) - cred = iot_v1.types.DeviceCredential(public_key=key) - device = client.get_device(device_path) + cred = iot_v1.DeviceCredential(public_key=key) + device = client.get_device(request={"name": device_path}) - device.id = b'' + device.id = b"" device.num_id = 0 device.credentials.append(cred) - mask = iot_v1.types.FieldMask() - mask.paths.append('credentials') + mask = gp_field_mask.FieldMask() + mask.paths.append("credentials") - return client.update_device( - device=device, - update_mask=mask) + return client.update_device(request={"device": device, "update_mask": mask}) # [END iot_patch_es] def patch_rsa256_auth( - service_account_json, project_id, cloud_region, registry_id, device_id, - public_key_file): + service_account_json, + project_id, + cloud_region, + registry_id, + device_id, + public_key_file, +): """Patch the device to add an RSA256 public key to the device.""" # [START iot_patch_rsa] # project_id = 'YOUR_PROJECT_ID' @@ -489,40 +501,43 @@ def patch_rsa256_auth( # registry_id = 'your-registry-id' # device_id = 'your-device-id' # public_key_file = 'path/to/certificate.pem' - print('Patch device with RSA256 certificate') + print("Patch device with RSA256 certificate") client = iot_v1.DeviceManagerClient() - device_path = client.device_path( - project_id, cloud_region, registry_id, device_id) + device_path = client.device_path(project_id, cloud_region, registry_id, device_id) - public_key_bytes = '' + public_key_bytes = "" with io.open(public_key_file) as f: public_key_bytes = f.read() - key = iot_v1.types.PublicKeyCredential( - format='RSA_X509_PEM', - key=public_key_bytes) + key = iot_v1.PublicKeyCredential( + format=iot_v1.PublicKeyFormat.RSA_X509_PEM, key=public_key_bytes + ) - cred = iot_v1.types.DeviceCredential(public_key=key) - device = client.get_device(device_path) + cred = iot_v1.DeviceCredential(public_key=key) + device = client.get_device(request={"name": device_path}) - device.id = b'' + device.id = b"" device.num_id = 0 device.credentials.append(cred) - mask = iot_v1.types.FieldMask() - mask.paths.append('credentials') + mask = gp_field_mask.FieldMask() + mask.paths.append("credentials") - return client.update_device( - device=device, - update_mask=mask) + return client.update_device(request={"device": device, "update_mask": mask}) # [END iot_patch_rsa] def set_config( - service_account_json, project_id, cloud_region, registry_id, device_id, - version, config): + service_account_json, + project_id, + cloud_region, + registry_id, + device_id, + version, + config, +): # [START iot_set_device_config] # project_id = 'YOUR_PROJECT_ID' # cloud_region = 'us-central1' @@ -530,20 +545,21 @@ def set_config( # device_id = 'your-device-id' # version = '0' # config= 'your-config-data' - print('Set device configuration') + print("Set device configuration") client = iot_v1.DeviceManagerClient() - device_path = client.device_path( - project_id, cloud_region, registry_id, device_id) + device_path = client.device_path(project_id, cloud_region, registry_id, device_id) - data = config.encode('utf-8') + data = config.encode("utf-8") - return client.modify_cloud_to_device_config(device_path, data, version) + return client.modify_cloud_to_device_config( + request={"name": device_path, "binary_data": data, "version_to_update": version} + ) # [END iot_set_device_config] def get_config_versions( - service_account_json, project_id, cloud_region, registry_id, - device_id): + service_account_json, project_id, cloud_region, registry_id, device_id +): """Lists versions of a device config in descending order (newest first).""" # [START iot_get_device_configs] # project_id = 'YOUR_PROJECT_ID' @@ -551,23 +567,22 @@ def get_config_versions( # registry_id = 'your-registry-id' # device_id = 'your-device-id' client = iot_v1.DeviceManagerClient() - device_path = client.device_path( - project_id, cloud_region, registry_id, device_id) + device_path = client.device_path(project_id, cloud_region, registry_id, device_id) - configs = client.list_device_config_versions(device_path) + configs = client.list_device_config_versions(request={"name": device_path}) for config in configs.device_configs: - print('version: {}\n\tcloudUpdateTime: {}\n\t data: {}'.format( - config.version, - config.cloud_update_time, - config.binary_data)) + print( + "version: {}\n\tcloudUpdateTime: {}\n\t data: {}".format( + config.version, config.cloud_update_time, config.binary_data + ) + ) return configs # [END iot_get_device_configs] -def get_iam_permissions( - service_account_json, project_id, cloud_region, registry_id): +def get_iam_permissions(service_account_json, project_id, cloud_region, registry_id): """Retrieves IAM permissions for the given registry.""" # [START iot_get_iam_policy] # project_id = 'YOUR_PROJECT_ID' @@ -577,15 +592,15 @@ def get_iam_permissions( registry_path = client.registry_path(project_id, cloud_region, registry_id) - policy = client.get_iam_policy(registry_path) + policy = client.get_iam_policy(request={"resource": registry_path}) return policy # [END iot_get_iam_policy] def set_iam_permissions( - service_account_json, project_id, cloud_region, registry_id, role, - member): + service_account_json, project_id, cloud_region, registry_id, role, member +): """Sets IAM permissions for the given registry to a single role/member.""" # [START iot_set_iam_policy] # project_id = 'YOUR_PROJECT_ID' @@ -596,38 +611,40 @@ def set_iam_permissions( client = iot_v1.DeviceManagerClient() registry_path = client.registry_path(project_id, cloud_region, registry_id) - body = { - 'bindings': - [{ - 'members': [member], - 'role': role - }] - } + body = {"bindings": [{"members": [member], "role": role}]} - return client.set_iam_policy(registry_path, body) + return client.set_iam_policy(request={"resource": registry_path, "policy": body}) # [END iot_set_iam_policy] def send_command( - service_account_json, project_id, cloud_region, registry_id, device_id, - command): + service_account_json, project_id, cloud_region, registry_id, device_id, command +): """Send a command to a device.""" # [START iot_send_command] - print('Sending command to device') + print("Sending command to device") client = iot_v1.DeviceManagerClient() - device_path = client.device_path( - project_id, cloud_region, registry_id, device_id) + device_path = client.device_path(project_id, cloud_region, registry_id, device_id) # command = 'Hello IoT Core!' - data = command.encode('utf-8') + data = command.encode("utf-8") - return client.send_command_to_device(device_path, data) + return client.send_command_to_device( + request={"name": device_path, "binary_data": data} + ) # [END iot_send_command] def create_gateway( - service_account_json, project_id, cloud_region, registry_id, device_id, - gateway_id, certificate_file, algorithm): + service_account_json, + project_id, + cloud_region, + registry_id, + device_id, + gateway_id, + certificate_file, + algorithm, +): """Create a gateway to bind devices to.""" # [START iot_create_gateway] # project_id = 'YOUR_PROJECT_ID' @@ -642,52 +659,50 @@ def create_gateway( client = iot_v1.DeviceManagerClient() parent = client.registry_path(project_id, cloud_region, registry_id) - devices = list(client.list_devices(parent=parent)) + devices = list(client.list_devices(request={"parent": parent})) for device in devices: if device.id == gateway_id: exists = True - print('Device: {} : {} : {} : {}'.format( - device.id, - device.num_id, - device.config, - device.gateway_config - )) + print( + "Device: {} : {} : {} : {}".format( + device.id, device.num_id, device.config, device.gateway_config + ) + ) with io.open(certificate_file) as f: certificate = f.read() - if algorithm == 'ES256': - certificate_format = 'ES256_PEM' + if algorithm == "ES256": + certificate_format = iot_v1.PublicKeyFormat.ES256_PEM else: - certificate_format = 'RSA_X509_PEM' + certificate_format = iot_v1.PublicKeyFormat.RSA_X509_PEM # TODO: Auth type device_template = { - 'id': gateway_id, - 'credentials': [{ - 'public_key': { - 'format': certificate_format, - 'key': certificate - } - }], - 'gateway_config': { - 'gateway_type': 'GATEWAY', - 'gateway_auth_method': 'ASSOCIATION_ONLY' - } + "id": gateway_id, + "credentials": [ + {"public_key": {"format": certificate_format, "key": certificate}} + ], + "gateway_config": { + "gateway_type": iot_v1.GatewayType.GATEWAY, + "gateway_auth_method": iot_v1.GatewayAuthMethod.ASSOCIATION_ONLY, + }, } if not exists: - res = client.create_device(parent, device_template) - print('Created Gateway {}'.format(res)) + res = client.create_device( + request={"parent": parent, "device": device_template} + ) + print("Created Gateway {}".format(res)) else: - print('Gateway exists, skipping') + print("Gateway exists, skipping") # [END iot_create_gateway] def bind_device_to_gateway( - service_account_json, project_id, cloud_region, registry_id, device_id, - gateway_id): + service_account_json, project_id, cloud_region, registry_id, device_id, gateway_id +): """Binds a device to a gateway.""" # [START iot_bind_device_to_gateway] # project_id = 'YOUR_PROJECT_ID' @@ -698,20 +713,22 @@ def bind_device_to_gateway( client = iot_v1.DeviceManagerClient() create_device( - service_account_json, project_id, cloud_region, registry_id, - device_id) + service_account_json, project_id, cloud_region, registry_id, device_id + ) parent = client.registry_path(project_id, cloud_region, registry_id) - res = client.bind_device_to_gateway(parent, gateway_id, device_id) + res = client.bind_device_to_gateway( + request={"parent": parent, "gateway_id": gateway_id, "device_id": device_id} + ) - print('Device Bound! {}'.format(res)) + print("Device Bound! {}".format(res)) # [END iot_bind_device_to_gateway] def unbind_device_from_gateway( - service_account_json, project_id, cloud_region, registry_id, device_id, - gateway_id): + service_account_json, project_id, cloud_region, registry_id, device_id, gateway_id +): """Unbinds a device to a gateway.""" # [START iot_unbind_device_from_gateway] # project_id = 'YOUR_PROJECT_ID' @@ -723,14 +740,15 @@ def unbind_device_from_gateway( parent = client.registry_path(project_id, cloud_region, registry_id) - res = client.unbind_device_from_gateway(parent, gateway_id, device_id) + res = client.unbind_device_from_gateway( + request={"parent": parent, "gateway_id": gateway_id, "device_id": device_id} + ) - print('Device unbound: {}'.format(res)) + print("Device unbound: {}".format(res)) # [END iot_unbind_device_from_gateway] -def list_gateways( - service_account_json, project_id, cloud_region, registry_id): +def list_gateways(service_account_json, project_id, cloud_region, registry_id): """Lists gateways in a registry""" # [START iot_list_gateways] # project_id = 'YOUR_PROJECT_ID' @@ -739,21 +757,21 @@ def list_gateways( client = iot_v1.DeviceManagerClient() path = client.registry_path(project_id, cloud_region, registry_id) - mask = iot_v1.types.FieldMask() - mask.paths.append('config') - mask.paths.append('gateway_config') - devices = list(client.list_devices(parent=path, field_mask=mask)) + mask = gp_field_mask.FieldMask() + mask.paths.append("config") + mask.paths.append("gateway_config") + devices = list(client.list_devices(request={"parent": path, "field_mask": mask})) for device in devices: if device.gateway_config is not None: if device.gateway_config.gateway_type == 1: - print('Gateway ID: {}\n\t{}'.format(device.id, device)) + print("Gateway ID: {}\n\t{}".format(device.id, device)) # [END iot_list_gateways] def list_devices_for_gateway( - service_account_json, project_id, cloud_region, registry_id, - gateway_id): + service_account_json, project_id, cloud_region, registry_id, gateway_id +): """List devices bound to a gateway""" # [START iot_list_devices_for_gateway] # project_id = 'YOUR_PROJECT_ID' @@ -764,278 +782,366 @@ def list_devices_for_gateway( path = client.registry_path(project_id, cloud_region, registry_id) - devices = list(client.list_devices( - parent=path, - gateway_list_options={'associations_gateway_id': gateway_id})) + devices = list( + client.list_devices( + request={ + "parent": path, + "gateway_list_options": {"associations_gateway_id": gateway_id}, + } + ) + ) found = False for device in devices: found = True - print('Device: {} : {}'.format(device.num_id, device.id)) + print("Device: {} : {}".format(device.num_id, device.id)) if not found: - print('No devices bound to gateway {}'.format(gateway_id)) + print("No devices bound to gateway {}".format(gateway_id)) # [END iot_list_devices_for_gateway] def parse_command_line_args(): """Parse command line arguments.""" - default_registry = 'cloudiot_device_manager_example_registry_{}'.format( - int(time.time())) + default_registry = "cloudiot_device_manager_example_registry_{}".format( + int(time.time()) + ) parser = argparse.ArgumentParser( - description=__doc__, - formatter_class=argparse.RawDescriptionHelpFormatter) + description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter + ) # Optional arguments parser.add_argument( - '--algorithm', - choices=('RS256', 'ES256'), - help='Which encryption algorithm to use to generate the JWT.') + "--algorithm", + choices=("RS256", "ES256"), + help="Which encryption algorithm to use to generate the JWT.", + ) + parser.add_argument("--certificate_path", help="Path to public certificate.") parser.add_argument( - '--certificate_path', - help='Path to public certificate.') + "--cloud_region", default="us-central1", help="GCP cloud region" + ) parser.add_argument( - '--cloud_region', default='us-central1', help='GCP cloud region') + "--pubsub_topic", + help=( + "Google Cloud Pub/Sub topic. " + "Format is projects/project_id/topics/topic-id" + ), + ) parser.add_argument( - '--pubsub_topic', - help=('Google Cloud Pub/Sub topic. ' - 'Format is projects/project_id/topics/topic-id')) + "--config", default=None, help="Configuration sent to a device." + ) + parser.add_argument("--device_id", default=None, help="Device id.") parser.add_argument( - '--config', - default=None, - help='Configuration sent to a device.') + "--ec_public_key_file", default=None, help="Path to public ES256 key file." + ) + parser.add_argument("--gateway_id", help="Gateway identifier.") + parser.add_argument("--member", default=None, help="Member used for IAM commands.") + parser.add_argument("--role", default=None, help="Role used for IAM commands.") parser.add_argument( - '--device_id', - default=None, - help='Device id.') + "--send_command", default="1", help="The command sent to the device" + ) parser.add_argument( - '--ec_public_key_file', - default=None, - help='Path to public ES256 key file.') + "--project_id", + default=os.environ.get("GOOGLE_CLOUD_PROJECT"), + help="GCP cloud project name.", + ) parser.add_argument( - '--gateway_id', - help='Gateway identifier.') + "--registry_id", + default=default_registry, + help="Registry id. If not set, a name will be generated.", + ) parser.add_argument( - '--member', - default=None, - help='Member used for IAM commands.') + "--rsa_certificate_file", default=None, help="Path to RS256 certificate file." + ) parser.add_argument( - '--role', - default=None, - help='Role used for IAM commands.') + "--service_account_json", + default=os.environ.get("GOOGLE_APPLICATION_CREDENTIALS"), + help="Path to service account json file.", + ) parser.add_argument( - '--send_command', - default='1', - help='The command sent to the device') - parser.add_argument( - '--project_id', - default=os.environ.get("GOOGLE_CLOUD_PROJECT"), - help='GCP cloud project name.') - parser.add_argument( - '--registry_id', - default=default_registry, - help='Registry id. If not set, a name will be generated.') - parser.add_argument( - '--rsa_certificate_file', - default=None, - help='Path to RS256 certificate file.') - parser.add_argument( - '--service_account_json', - default=os.environ.get("GOOGLE_APPLICATION_CREDENTIALS"), - help='Path to service account json file.') - parser.add_argument( - '--version', - default=0, - type=int, - help='Version number for setting device configuration.') + "--version", + default=0, + type=int, + help="Version number for setting device configuration.", + ) # Command subparser - command = parser.add_subparsers(dest='command') - + command = parser.add_subparsers(dest="command") + + command.add_parser("bind-device-to-gateway", help=bind_device_to_gateway.__doc__) + command.add_parser("create-es256", help=create_es256_device.__doc__) + command.add_parser("create-gateway", help=create_gateway.__doc__) + command.add_parser("create-registry", help=open_registry.__doc__) + command.add_parser("create-rsa256", help=create_rs256_device.__doc__) + command.add_parser("create-topic", help=create_iot_topic.__doc__) + command.add_parser("create-unauth", help=create_unauth_device.__doc__) + command.add_parser("delete-device", help=delete_device.__doc__) + command.add_parser("delete-registry", help=delete_registry.__doc__) + command.add_parser("get", help=get_device.__doc__) + command.add_parser("get-config-versions", help=get_config_versions.__doc__) + command.add_parser("get-iam-permissions", help=get_iam_permissions.__doc__) + command.add_parser("get-registry", help=get_registry.__doc__) + command.add_parser("get-state", help=get_state.__doc__) + command.add_parser("list", help=list_devices.__doc__) command.add_parser( - 'bind-device-to-gateway', help=bind_device_to_gateway.__doc__) - command.add_parser('create-es256', help=create_es256_device.__doc__) - command.add_parser('create-gateway', help=create_gateway.__doc__) - command.add_parser('create-registry', help=open_registry.__doc__) - command.add_parser('create-rsa256', help=create_rs256_device.__doc__) - command.add_parser('create-topic', help=create_iot_topic.__doc__) - command.add_parser('create-unauth', help=create_unauth_device.__doc__) - command.add_parser('delete-device', help=delete_device.__doc__) - command.add_parser('delete-registry', help=delete_registry.__doc__) - command.add_parser('get', help=get_device.__doc__) - command.add_parser('get-config-versions', help=get_config_versions.__doc__) - command.add_parser('get-iam-permissions', help=get_iam_permissions.__doc__) - command.add_parser('get-registry', help=get_registry.__doc__) - command.add_parser('get-state', help=get_state.__doc__) - command.add_parser('list', help=list_devices.__doc__) + "list-devices-for-gateway", help=list_devices_for_gateway.__doc__ + ) + command.add_parser("list-gateways", help=list_gateways.__doc__) + command.add_parser("list-registries", help=list_registries.__doc__) + command.add_parser("patch-es256", help=patch_es256_auth.__doc__) + command.add_parser("patch-rs256", help=patch_rsa256_auth.__doc__) + command.add_parser("send-command", help=send_command.__doc__) + command.add_parser("set-config", help=patch_rsa256_auth.__doc__) + command.add_parser("set-iam-permissions", help=set_iam_permissions.__doc__) command.add_parser( - 'list-devices-for-gateway', help=list_devices_for_gateway.__doc__) - command.add_parser('list-gateways', help=list_gateways.__doc__) - command.add_parser('list-registries', help=list_registries.__doc__) - command.add_parser('patch-es256', help=patch_es256_auth.__doc__) - command.add_parser('patch-rs256', help=patch_rsa256_auth.__doc__) - command.add_parser('send-command', help=send_command.__doc__) - command.add_parser('set-config', help=patch_rsa256_auth.__doc__) - command.add_parser('set-iam-permissions', help=set_iam_permissions.__doc__) - command.add_parser( - 'unbind-device-from-gateway', help=unbind_device_from_gateway.__doc__) + "unbind-device-from-gateway", help=unbind_device_from_gateway.__doc__ + ) return parser.parse_args() def run_create(args): """Handles commands that create devices, registries, or topics.""" - if args.command == 'create-rsa256': + if args.command == "create-rsa256": create_rs256_device( - args.service_account_json, args.project_id, - args.cloud_region, args.registry_id, args.device_id, - args.rsa_certificate_file) - - elif args.command == 'create-es256': + args.service_account_json, + args.project_id, + args.cloud_region, + args.registry_id, + args.device_id, + args.rsa_certificate_file, + ) + + elif args.command == "create-es256": create_es256_device( - args.service_account_json, args.project_id, - args.cloud_region, args.registry_id, args.device_id, - args.ec_public_key_file) - - elif args.command == 'create-gateway': + args.service_account_json, + args.project_id, + args.cloud_region, + args.registry_id, + args.device_id, + args.ec_public_key_file, + ) + + elif args.command == "create-gateway": create_gateway( - args.service_account_json, args.project_id, - args.cloud_region, args.registry_id, args.device_id, - args.gateway_id, args.certificate_path, args.algorithm) - - elif args.command == 'create-unauth': + args.service_account_json, + args.project_id, + args.cloud_region, + args.registry_id, + args.device_id, + args.gateway_id, + args.certificate_path, + args.algorithm, + ) + + elif args.command == "create-unauth": create_unauth_device( - args.service_account_json, args.project_id, - args.cloud_region, args.registry_id, args.device_id) - - elif args.command == 'create-registry': - if (args.pubsub_topic is None): - sys.exit('Error: specify --pubsub_topic') + args.service_account_json, + args.project_id, + args.cloud_region, + args.registry_id, + args.device_id, + ) + + elif args.command == "create-registry": + if args.pubsub_topic is None: + sys.exit("Error: specify --pubsub_topic") open_registry( - args.service_account_json, args.project_id, - args.cloud_region, args.pubsub_topic, args.registry_id) - - elif args.command == 'create-topic': - if (args.pubsub_topic is None): - sys.exit('Error: specify --pubsub_topic') + args.service_account_json, + args.project_id, + args.cloud_region, + args.pubsub_topic, + args.registry_id, + ) + + elif args.command == "create-topic": + if args.pubsub_topic is None: + sys.exit("Error: specify --pubsub_topic") create_iot_topic(args.project_id, args.pubsub_topic) def run_get(args): - if args.command == 'get': + if args.command == "get": get_device( - args.service_account_json, args.project_id, - args.cloud_region, args.registry_id, args.device_id) - - elif args.command == 'get-config-versions': + args.service_account_json, + args.project_id, + args.cloud_region, + args.registry_id, + args.device_id, + ) + + elif args.command == "get-config-versions": get_config_versions( - args.service_account_json, args.project_id, - args.cloud_region, args.registry_id, args.device_id) - - elif args.command == 'get-state': + args.service_account_json, + args.project_id, + args.cloud_region, + args.registry_id, + args.device_id, + ) + + elif args.command == "get-state": get_state( - args.service_account_json, args.project_id, - args.cloud_region, args.registry_id, args.device_id) - - elif args.command == 'get-iam-permissions': - print(get_iam_permissions( - args.service_account_json, args.project_id, - args.cloud_region, args.registry_id)) - - elif args.command == 'get-registry': - print(get_registry( - args.service_account_json, args.project_id, - args.cloud_region, args.registry_id)) + args.service_account_json, + args.project_id, + args.cloud_region, + args.registry_id, + args.device_id, + ) + + elif args.command == "get-iam-permissions": + print( + get_iam_permissions( + args.service_account_json, + args.project_id, + args.cloud_region, + args.registry_id, + ) + ) + + elif args.command == "get-registry": + print( + get_registry( + args.service_account_json, + args.project_id, + args.cloud_region, + args.registry_id, + ) + ) def run_list(args): - if args.command == 'list': + if args.command == "list": list_devices( - args.service_account_json, args.project_id, - args.cloud_region, args.registry_id) - elif args.command == 'list-devices-for-gateway': + args.service_account_json, + args.project_id, + args.cloud_region, + args.registry_id, + ) + elif args.command == "list-devices-for-gateway": list_devices_for_gateway( - args.service_account_json, args.project_id, - args.cloud_region, args.registry_id, args.gateway_id) - elif args.command == 'list-gateways': + args.service_account_json, + args.project_id, + args.cloud_region, + args.registry_id, + args.gateway_id, + ) + elif args.command == "list-gateways": list_gateways( - args.service_account_json, args.project_id, - args.cloud_region, args.registry_id) - elif args.command == 'list-registries': - list_registries( - args.service_account_json, args.project_id, - args.cloud_region) + args.service_account_json, + args.project_id, + args.cloud_region, + args.registry_id, + ) + elif args.command == "list-registries": + list_registries(args.service_account_json, args.project_id, args.cloud_region) def run_command(args): """Calls the program using the specified command.""" if args.project_id is None: - print('You must specify a project ID or set the environment variable.') + print("You must specify a project ID or set the environment variable.") return - elif args.command.startswith('create'): + elif args.command.startswith("create"): run_create(args) - elif args.command.startswith('get'): + elif args.command.startswith("get"): run_get(args) - elif args.command.startswith('list'): + elif args.command.startswith("list"): run_list(args) - elif args.command == 'bind-device-to-gateway': + elif args.command == "bind-device-to-gateway": bind_device_to_gateway( - args.service_account_json, args.project_id, - args.cloud_region, args.registry_id, args.device_id, - args.gateway_id) - elif args.command == 'delete-device': + args.service_account_json, + args.project_id, + args.cloud_region, + args.registry_id, + args.device_id, + args.gateway_id, + ) + elif args.command == "delete-device": delete_device( - args.service_account_json, args.project_id, - args.cloud_region, args.registry_id, args.device_id) - elif args.command == 'delete-registry': + args.service_account_json, + args.project_id, + args.cloud_region, + args.registry_id, + args.device_id, + ) + elif args.command == "delete-registry": delete_registry( - args.service_account_json, args.project_id, - args.cloud_region, args.registry_id) - elif args.command == 'patch-es256': - if (args.ec_public_key_file is None): - sys.exit('Error: specify --ec_public_key_file') + args.service_account_json, + args.project_id, + args.cloud_region, + args.registry_id, + ) + elif args.command == "patch-es256": + if args.ec_public_key_file is None: + sys.exit("Error: specify --ec_public_key_file") patch_es256_auth( - args.service_account_json, args.project_id, - args.cloud_region, args.registry_id, args.device_id, - args.ec_public_key_file) - elif args.command == 'patch-rs256': - if (args.rsa_certificate_file is None): - sys.exit('Error: specify --rsa_certificate_file') + args.service_account_json, + args.project_id, + args.cloud_region, + args.registry_id, + args.device_id, + args.ec_public_key_file, + ) + elif args.command == "patch-rs256": + if args.rsa_certificate_file is None: + sys.exit("Error: specify --rsa_certificate_file") patch_rsa256_auth( - args.service_account_json, args.project_id, - args.cloud_region, args.registry_id, args.device_id, - args.rsa_certificate_file) - elif args.command == 'send-command': + args.service_account_json, + args.project_id, + args.cloud_region, + args.registry_id, + args.device_id, + args.rsa_certificate_file, + ) + elif args.command == "send-command": send_command( - args.service_account_json, args.project_id, - args.cloud_region, args.registry_id, args.device_id, - args.send_command) - elif args.command == 'set-iam-permissions': - if (args.member is None): - sys.exit('Error: specify --member') - if (args.role is None): - sys.exit('Error: specify --role') + args.service_account_json, + args.project_id, + args.cloud_region, + args.registry_id, + args.device_id, + args.send_command, + ) + elif args.command == "set-iam-permissions": + if args.member is None: + sys.exit("Error: specify --member") + if args.role is None: + sys.exit("Error: specify --role") set_iam_permissions( - args.service_account_json, args.project_id, - args.cloud_region, args.registry_id, args.role, args.member) - elif args.command == 'set-config': - if (args.config is None): - sys.exit('Error: specify --config') - if (args.version is None): - sys.exit('Error: specify --version') + args.service_account_json, + args.project_id, + args.cloud_region, + args.registry_id, + args.role, + args.member, + ) + elif args.command == "set-config": + if args.config is None: + sys.exit("Error: specify --config") + if args.version is None: + sys.exit("Error: specify --version") set_config( - args.service_account_json, args.project_id, - args.cloud_region, args.registry_id, args.device_id, - args.version, args.config) - elif args.command == 'unbind-device-from-gateway': + args.service_account_json, + args.project_id, + args.cloud_region, + args.registry_id, + args.device_id, + args.version, + args.config, + ) + elif args.command == "unbind-device-from-gateway": unbind_device_from_gateway( - args.service_account_json, args.project_id, - args.cloud_region, args.registry_id, args.device_id, - args.gateway_id) + args.service_account_json, + args.project_id, + args.cloud_region, + args.registry_id, + args.device_id, + args.gateway_id, + ) -if __name__ == '__main__': +if __name__ == "__main__": args = parse_command_line_args() run_command(args) diff --git a/scripts/fixup_iot_v1_keywords.py b/scripts/fixup_iot_v1_keywords.py new file mode 100644 index 00000000..1c0e0056 --- /dev/null +++ b/scripts/fixup_iot_v1_keywords.py @@ -0,0 +1,196 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import argparse +import os +import libcst as cst +import pathlib +import sys +from typing import (Any, Callable, Dict, List, Sequence, Tuple) + + +def partition( + predicate: Callable[[Any], bool], + iterator: Sequence[Any] +) -> Tuple[List[Any], List[Any]]: + """A stable, out-of-place partition.""" + results = ([], []) + + for i in iterator: + results[int(predicate(i))].append(i) + + # Returns trueList, falseList + return results[1], results[0] + + +class iotCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'bind_device_to_gateway': ('parent', 'gateway_id', 'device_id', ), + 'create_device': ('parent', 'device', ), + 'create_device_registry': ('parent', 'device_registry', ), + 'delete_device': ('name', ), + 'delete_device_registry': ('name', ), + 'get_device': ('name', 'field_mask', ), + 'get_device_registry': ('name', ), + 'get_iam_policy': ('resource', 'options', ), + 'list_device_config_versions': ('name', 'num_versions', ), + 'list_device_registries': ('parent', 'page_size', 'page_token', ), + 'list_devices': ('parent', 'device_num_ids', 'device_ids', 'field_mask', 'gateway_list_options', 'page_size', 'page_token', ), + 'list_device_states': ('name', 'num_states', ), + 'modify_cloud_to_device_config': ('name', 'binary_data', 'version_to_update', ), + 'send_command_to_device': ('name', 'binary_data', 'subfolder', ), + 'set_iam_policy': ('resource', 'policy', ), + 'test_iam_permissions': ('resource', 'permissions', ), + 'unbind_device_from_gateway': ('parent', 'gateway_id', 'device_id', ), + 'update_device': ('device', 'update_mask', ), + 'update_device_registry': ('device_registry', 'update_mask', ), + + } + + def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: + try: + key = original.func.attr.value + kword_params = self.METHOD_TO_PARAMS[key] + except (AttributeError, KeyError): + # Either not a method from the API or too convoluted to be sure. + return updated + + # If the existing code is valid, keyword args come after positional args. + # Therefore, all positional args must map to the first parameters. + args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) + if any(k.keyword.value == "request" for k in kwargs): + # We've already fixed this file, don't fix it again. + return updated + + kwargs, ctrl_kwargs = partition( + lambda a: not a.keyword.value in self.CTRL_PARAMS, + kwargs + ) + + args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] + ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) + for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) + + request_arg = cst.Arg( + value=cst.Dict([ + cst.DictElement( + cst.SimpleString("'{}'".format(name)), + cst.Element(value=arg.value) + ) + # Note: the args + kwargs looks silly, but keep in mind that + # the control parameters had to be stripped out, and that + # those could have been passed positionally or by keyword. + for name, arg in zip(kword_params, args + kwargs)]), + keyword=cst.Name("request") + ) + + return updated.with_changes( + args=[request_arg] + ctrl_kwargs + ) + + +def fix_files( + in_dir: pathlib.Path, + out_dir: pathlib.Path, + *, + transformer=iotCallTransformer(), +): + """Duplicate the input dir to the output dir, fixing file method calls. + + Preconditions: + * in_dir is a real directory + * out_dir is a real, empty directory + """ + pyfile_gen = ( + pathlib.Path(os.path.join(root, f)) + for root, _, files in os.walk(in_dir) + for f in files if os.path.splitext(f)[1] == ".py" + ) + + for fpath in pyfile_gen: + with open(fpath, 'r') as f: + src = f.read() + + # Parse the code and insert method call fixes. + tree = cst.parse_module(src) + updated = tree.visit(transformer) + + # Create the path and directory structure for the new file. + updated_path = out_dir.joinpath(fpath.relative_to(in_dir)) + updated_path.parent.mkdir(parents=True, exist_ok=True) + + # Generate the updated source file at the corresponding path. + with open(updated_path, 'w') as f: + f.write(updated.code) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser( + description="""Fix up source that uses the iot client library. + +The existing sources are NOT overwritten but are copied to output_dir with changes made. + +Note: This tool operates at a best-effort level at converting positional + parameters in client method calls to keyword based parameters. + Cases where it WILL FAIL include + A) * or ** expansion in a method call. + B) Calls via function or method alias (includes free function calls) + C) Indirect or dispatched calls (e.g. the method is looked up dynamically) + + These all constitute false negatives. The tool will also detect false + positives when an API method shares a name with another method. +""") + parser.add_argument( + '-d', + '--input-directory', + required=True, + dest='input_dir', + help='the input directory to walk for python files to fix up', + ) + parser.add_argument( + '-o', + '--output-directory', + required=True, + dest='output_dir', + help='the directory to output files fixed via un-flattening', + ) + args = parser.parse_args() + input_dir = pathlib.Path(args.input_dir) + output_dir = pathlib.Path(args.output_dir) + if not input_dir.is_dir(): + print( + f"input directory '{input_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if not output_dir.is_dir(): + print( + f"output directory '{output_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if os.listdir(output_dir): + print( + f"output directory '{output_dir}' is not empty", + file=sys.stderr, + ) + sys.exit(-1) + + fix_files(input_dir, output_dir) diff --git a/setup.py b/setup.py index 4a03dc13..291cd30f 100644 --- a/setup.py +++ b/setup.py @@ -22,9 +22,10 @@ version = "1.0.0" release_status = "Development Status :: 5 - Production/Stable" dependencies = [ - "google-api-core[grpc] >= 1.14.0, < 2.0.0dev", + "google-api-core[grpc] >= 1.22.0, < 2.0.0dev", "grpc-google-iam-v1 >= 0.12.3, < 0.13dev", - 'enum34; python_version < "3.4"', + "proto-plus >= 1.4.0", + "libcst >= 0.2.5", ] package_root = os.path.abspath(os.path.dirname(__file__)) @@ -34,7 +35,9 @@ readme = readme_file.read() packages = [ - package for package in setuptools.find_packages() if package.startswith("google") + package + for package in setuptools.PEP420PackageFinder.find() + if package.startswith("google") ] namespaces = ["google"] @@ -55,12 +58,10 @@ "Intended Audience :: Developers", "License :: OSI Approved :: Apache Software License", "Programming Language :: Python", - "Programming Language :: Python :: 2", - "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", - "Programming Language :: Python :: 3.5", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", + "Programming Language :: Python :: 3.8", "Operating System :: OS Independent", "Topic :: Internet", ], @@ -68,7 +69,8 @@ packages=packages, namespace_packages=namespaces, install_requires=dependencies, - python_requires=">=2.7,!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*", + python_requires=">=3.6", + scripts=["scripts/fixup_iot_v1_keywords.py"], include_package_data=True, zip_safe=False, ) diff --git a/synth.metadata b/synth.metadata index fd84d349..a0e77355 100644 --- a/synth.metadata +++ b/synth.metadata @@ -4,7 +4,7 @@ "git": { "name": ".", "remote": "https://github.com/googleapis/python-iot.git", - "sha": "06ed25e2a7f407d098410969c6dfa24a4c84ac9d" + "sha": "43f1f1a2b00d2e808afc12f08f674f4232de043d" } }, { diff --git a/synth.py b/synth.py index 4fa4ab2a..213f17c7 100644 --- a/synth.py +++ b/synth.py @@ -19,6 +19,7 @@ gapic = gcp.GAPICBazel() common = gcp.CommonTemplates() +excludes = ["README.rst", "setup.py", "nox*.py", "docs/index.rst"] # ---------------------------------------------------------------------------- # Generate iot GAPIC layer @@ -29,17 +30,17 @@ bazel_target="//google/cloud/iot/v1:iot-v1-py", include_protos=True, ) - -s.move(library / "google/cloud/iot_v1") -s.move(library / "tests/unit/gapic") -s.move(library / "tests/system/gapic") -s.move(library / "docs", excludes="index.rst") +s.copy(library, excludes=excludes) # ---------------------------------------------------------------------------- # Add templated files # ---------------------------------------------------------------------------- -templated_files = common.py_library(cov_level=74, samples=True) -s.move(templated_files) +templated_files = common.py_library( + samples=True, + microgenerator=True, + cov_level=99, +) +s.move(templated_files, excludes=[".coveragerc"]) # microgenerator has a good .coveragerc file # ---------------------------------------------------------------------------- # Samples templates diff --git a/tests/system/gapic/v1/test_system_device_manager_v1.py b/tests/system/gapic/v1/test_system_device_manager_v1.py index 68c92e80..90fc0dd4 100644 --- a/tests/system/gapic/v1/test_system_device_manager_v1.py +++ b/tests/system/gapic/v1/test_system_device_manager_v1.py @@ -18,7 +18,6 @@ import time from google.cloud import iot_v1 -from google.cloud.iot_v1.proto import device_manager_pb2 class TestSystemDeviceManager(object): @@ -26,5 +25,5 @@ def test_list_device_registries(self): project_id = os.environ["PROJECT_ID"] client = iot_v1.DeviceManagerClient() - parent = client.location_path(project_id, "us-central1") - response = client.list_device_registries(parent) + parent = f"projects/{project_id}/locations/us-central1" + response = client.list_device_registries(request={"parent": parent}) diff --git a/tests/unit/gapic/iot_v1/__init__.py b/tests/unit/gapic/iot_v1/__init__.py new file mode 100644 index 00000000..8b137891 --- /dev/null +++ b/tests/unit/gapic/iot_v1/__init__.py @@ -0,0 +1 @@ + diff --git a/tests/unit/gapic/iot_v1/test_device_manager.py b/tests/unit/gapic/iot_v1/test_device_manager.py new file mode 100644 index 00000000..2827a327 --- /dev/null +++ b/tests/unit/gapic/iot_v1/test_device_manager.py @@ -0,0 +1,5052 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import os +import mock + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + +from google import auth +from google.api_core import client_options +from google.api_core import exceptions +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.auth import credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.iot_v1.services.device_manager import DeviceManagerAsyncClient +from google.cloud.iot_v1.services.device_manager import DeviceManagerClient +from google.cloud.iot_v1.services.device_manager import pagers +from google.cloud.iot_v1.services.device_manager import transports +from google.cloud.iot_v1.types import device_manager +from google.cloud.iot_v1.types import resources +from google.iam.v1 import iam_policy_pb2 as iam_policy # type: ignore +from google.iam.v1 import options_pb2 as options # type: ignore +from google.iam.v1 import policy_pb2 as policy # type: ignore +from google.oauth2 import service_account +from google.protobuf import any_pb2 as any # type: ignore +from google.protobuf import field_mask_pb2 as field_mask # type: ignore +from google.protobuf import timestamp_pb2 as timestamp # type: ignore +from google.rpc import status_pb2 as status # type: ignore +from google.type import expr_pb2 as expr # type: ignore + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return ( + "foo.googleapis.com" + if ("localhost" in client.DEFAULT_ENDPOINT) + else client.DEFAULT_ENDPOINT + ) + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert DeviceManagerClient._get_default_mtls_endpoint(None) is None + assert ( + DeviceManagerClient._get_default_mtls_endpoint(api_endpoint) + == api_mtls_endpoint + ) + assert ( + DeviceManagerClient._get_default_mtls_endpoint(api_mtls_endpoint) + == api_mtls_endpoint + ) + assert ( + DeviceManagerClient._get_default_mtls_endpoint(sandbox_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + DeviceManagerClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + DeviceManagerClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + ) + + +@pytest.mark.parametrize( + "client_class", [DeviceManagerClient, DeviceManagerAsyncClient] +) +def test_device_manager_client_from_service_account_file(client_class): + creds = credentials.AnonymousCredentials() + with mock.patch.object( + service_account.Credentials, "from_service_account_file" + ) as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json") + assert client._transport._credentials == creds + + client = client_class.from_service_account_json("dummy/file/path.json") + assert client._transport._credentials == creds + + assert client._transport._host == "cloudiot.googleapis.com:443" + + +def test_device_manager_client_get_transport_class(): + transport = DeviceManagerClient.get_transport_class() + assert transport == transports.DeviceManagerGrpcTransport + + transport = DeviceManagerClient.get_transport_class("grpc") + assert transport == transports.DeviceManagerGrpcTransport + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (DeviceManagerClient, transports.DeviceManagerGrpcTransport, "grpc"), + ( + DeviceManagerAsyncClient, + transports.DeviceManagerGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +@mock.patch.object( + DeviceManagerClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(DeviceManagerClient), +) +@mock.patch.object( + DeviceManagerAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(DeviceManagerAsyncClient), +) +def test_device_manager_client_client_options( + client_class, transport_class, transport_name +): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(DeviceManagerClient, "get_transport_class") as gtc: + transport = transport_class(credentials=credentials.AnonymousCredentials()) + client = client_class(transport=transport) + gtc.assert_not_called() + + # Check that if channel is provided via str we will create a new one. + with mock.patch.object(DeviceManagerClient, "get_transport_class") as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + api_mtls_endpoint="squid.clam.whelk", + client_cert_source=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS": "never"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + api_mtls_endpoint=client.DEFAULT_ENDPOINT, + client_cert_source=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS": "always"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + api_mtls_endpoint=client.DEFAULT_MTLS_ENDPOINT, + client_cert_source=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided, GOOGLE_API_USE_MTLS is + # "auto", and client_cert_source is provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS": "auto"}): + options = client_options.ClientOptions( + client_cert_source=client_cert_source_callback + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + api_mtls_endpoint=client.DEFAULT_MTLS_ENDPOINT, + client_cert_source=client_cert_source_callback, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided, GOOGLE_API_USE_MTLS is + # "auto", and default_client_cert_source is provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS": "auto"}): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=True, + ): + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + api_mtls_endpoint=client.DEFAULT_MTLS_ENDPOINT, + client_cert_source=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided, GOOGLE_API_USE_MTLS is + # "auto", but client_cert_source and default_client_cert_source are None. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS": "auto"}): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=False, + ): + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + api_mtls_endpoint=client.DEFAULT_ENDPOINT, + client_cert_source=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class() + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + api_mtls_endpoint=client.DEFAULT_ENDPOINT, + client_cert_source=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (DeviceManagerClient, transports.DeviceManagerGrpcTransport, "grpc"), + ( + DeviceManagerAsyncClient, + transports.DeviceManagerGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +def test_device_manager_client_client_options_scopes( + client_class, transport_class, transport_name +): + # Check the case scopes are provided. + options = client_options.ClientOptions(scopes=["1", "2"],) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + api_mtls_endpoint=client.DEFAULT_ENDPOINT, + client_cert_source=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (DeviceManagerClient, transports.DeviceManagerGrpcTransport, "grpc"), + ( + DeviceManagerAsyncClient, + transports.DeviceManagerGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +def test_device_manager_client_client_options_credentials_file( + client_class, transport_class, transport_name +): + # Check the case credentials file is provided. + options = client_options.ClientOptions(credentials_file="credentials.json") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + api_mtls_endpoint=client.DEFAULT_ENDPOINT, + client_cert_source=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +def test_device_manager_client_client_options_from_dict(): + with mock.patch( + "google.cloud.iot_v1.services.device_manager.transports.DeviceManagerGrpcTransport.__init__" + ) as grpc_transport: + grpc_transport.return_value = None + client = DeviceManagerClient( + client_options={"api_endpoint": "squid.clam.whelk"} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + api_mtls_endpoint="squid.clam.whelk", + client_cert_source=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +def test_create_device_registry( + transport: str = "grpc", request_type=device_manager.CreateDeviceRegistryRequest +): + client = DeviceManagerClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.create_device_registry), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = resources.DeviceRegistry( + id="id_value", name="name_value", log_level=resources.LogLevel.NONE, + ) + + response = client.create_device_registry(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == device_manager.CreateDeviceRegistryRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.DeviceRegistry) + + assert response.id == "id_value" + + assert response.name == "name_value" + + assert response.log_level == resources.LogLevel.NONE + + +def test_create_device_registry_from_dict(): + test_create_device_registry(request_type=dict) + + +@pytest.mark.asyncio +async def test_create_device_registry_async(transport: str = "grpc_asyncio"): + client = DeviceManagerAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = device_manager.CreateDeviceRegistryRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.create_device_registry), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.DeviceRegistry( + id="id_value", name="name_value", log_level=resources.LogLevel.NONE, + ) + ) + + response = await client.create_device_registry(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.DeviceRegistry) + + assert response.id == "id_value" + + assert response.name == "name_value" + + assert response.log_level == resources.LogLevel.NONE + + +def test_create_device_registry_field_headers(): + client = DeviceManagerClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = device_manager.CreateDeviceRegistryRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.create_device_registry), "__call__" + ) as call: + call.return_value = resources.DeviceRegistry() + + client.create_device_registry(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_create_device_registry_field_headers_async(): + client = DeviceManagerAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = device_manager.CreateDeviceRegistryRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.create_device_registry), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.DeviceRegistry() + ) + + await client.create_device_registry(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +def test_create_device_registry_flattened(): + client = DeviceManagerClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.create_device_registry), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = resources.DeviceRegistry() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_device_registry( + parent="parent_value", + device_registry=resources.DeviceRegistry(id="id_value"), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].parent == "parent_value" + + assert args[0].device_registry == resources.DeviceRegistry(id="id_value") + + +def test_create_device_registry_flattened_error(): + client = DeviceManagerClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_device_registry( + device_manager.CreateDeviceRegistryRequest(), + parent="parent_value", + device_registry=resources.DeviceRegistry(id="id_value"), + ) + + +@pytest.mark.asyncio +async def test_create_device_registry_flattened_async(): + client = DeviceManagerAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.create_device_registry), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = resources.DeviceRegistry() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.DeviceRegistry() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_device_registry( + parent="parent_value", + device_registry=resources.DeviceRegistry(id="id_value"), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].parent == "parent_value" + + assert args[0].device_registry == resources.DeviceRegistry(id="id_value") + + +@pytest.mark.asyncio +async def test_create_device_registry_flattened_error_async(): + client = DeviceManagerAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_device_registry( + device_manager.CreateDeviceRegistryRequest(), + parent="parent_value", + device_registry=resources.DeviceRegistry(id="id_value"), + ) + + +def test_get_device_registry( + transport: str = "grpc", request_type=device_manager.GetDeviceRegistryRequest +): + client = DeviceManagerClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.get_device_registry), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = resources.DeviceRegistry( + id="id_value", name="name_value", log_level=resources.LogLevel.NONE, + ) + + response = client.get_device_registry(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == device_manager.GetDeviceRegistryRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.DeviceRegistry) + + assert response.id == "id_value" + + assert response.name == "name_value" + + assert response.log_level == resources.LogLevel.NONE + + +def test_get_device_registry_from_dict(): + test_get_device_registry(request_type=dict) + + +@pytest.mark.asyncio +async def test_get_device_registry_async(transport: str = "grpc_asyncio"): + client = DeviceManagerAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = device_manager.GetDeviceRegistryRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.get_device_registry), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.DeviceRegistry( + id="id_value", name="name_value", log_level=resources.LogLevel.NONE, + ) + ) + + response = await client.get_device_registry(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.DeviceRegistry) + + assert response.id == "id_value" + + assert response.name == "name_value" + + assert response.log_level == resources.LogLevel.NONE + + +def test_get_device_registry_field_headers(): + client = DeviceManagerClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = device_manager.GetDeviceRegistryRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.get_device_registry), "__call__" + ) as call: + call.return_value = resources.DeviceRegistry() + + client.get_device_registry(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_device_registry_field_headers_async(): + client = DeviceManagerAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = device_manager.GetDeviceRegistryRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.get_device_registry), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.DeviceRegistry() + ) + + await client.get_device_registry(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +def test_get_device_registry_flattened(): + client = DeviceManagerClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.get_device_registry), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = resources.DeviceRegistry() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_device_registry(name="name_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + +def test_get_device_registry_flattened_error(): + client = DeviceManagerClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_device_registry( + device_manager.GetDeviceRegistryRequest(), name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_device_registry_flattened_async(): + client = DeviceManagerAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.get_device_registry), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = resources.DeviceRegistry() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.DeviceRegistry() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_device_registry(name="name_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + +@pytest.mark.asyncio +async def test_get_device_registry_flattened_error_async(): + client = DeviceManagerAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_device_registry( + device_manager.GetDeviceRegistryRequest(), name="name_value", + ) + + +def test_update_device_registry( + transport: str = "grpc", request_type=device_manager.UpdateDeviceRegistryRequest +): + client = DeviceManagerClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.update_device_registry), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = resources.DeviceRegistry( + id="id_value", name="name_value", log_level=resources.LogLevel.NONE, + ) + + response = client.update_device_registry(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == device_manager.UpdateDeviceRegistryRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.DeviceRegistry) + + assert response.id == "id_value" + + assert response.name == "name_value" + + assert response.log_level == resources.LogLevel.NONE + + +def test_update_device_registry_from_dict(): + test_update_device_registry(request_type=dict) + + +@pytest.mark.asyncio +async def test_update_device_registry_async(transport: str = "grpc_asyncio"): + client = DeviceManagerAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = device_manager.UpdateDeviceRegistryRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.update_device_registry), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.DeviceRegistry( + id="id_value", name="name_value", log_level=resources.LogLevel.NONE, + ) + ) + + response = await client.update_device_registry(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.DeviceRegistry) + + assert response.id == "id_value" + + assert response.name == "name_value" + + assert response.log_level == resources.LogLevel.NONE + + +def test_update_device_registry_field_headers(): + client = DeviceManagerClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = device_manager.UpdateDeviceRegistryRequest() + request.device_registry.name = "device_registry.name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.update_device_registry), "__call__" + ) as call: + call.return_value = resources.DeviceRegistry() + + client.update_device_registry(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "device_registry.name=device_registry.name/value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_update_device_registry_field_headers_async(): + client = DeviceManagerAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = device_manager.UpdateDeviceRegistryRequest() + request.device_registry.name = "device_registry.name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.update_device_registry), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.DeviceRegistry() + ) + + await client.update_device_registry(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "device_registry.name=device_registry.name/value", + ) in kw["metadata"] + + +def test_update_device_registry_flattened(): + client = DeviceManagerClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.update_device_registry), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = resources.DeviceRegistry() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_device_registry( + device_registry=resources.DeviceRegistry(id="id_value"), + update_mask=field_mask.FieldMask(paths=["paths_value"]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].device_registry == resources.DeviceRegistry(id="id_value") + + assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + + +def test_update_device_registry_flattened_error(): + client = DeviceManagerClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_device_registry( + device_manager.UpdateDeviceRegistryRequest(), + device_registry=resources.DeviceRegistry(id="id_value"), + update_mask=field_mask.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.asyncio +async def test_update_device_registry_flattened_async(): + client = DeviceManagerAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.update_device_registry), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = resources.DeviceRegistry() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.DeviceRegistry() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_device_registry( + device_registry=resources.DeviceRegistry(id="id_value"), + update_mask=field_mask.FieldMask(paths=["paths_value"]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].device_registry == resources.DeviceRegistry(id="id_value") + + assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + + +@pytest.mark.asyncio +async def test_update_device_registry_flattened_error_async(): + client = DeviceManagerAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_device_registry( + device_manager.UpdateDeviceRegistryRequest(), + device_registry=resources.DeviceRegistry(id="id_value"), + update_mask=field_mask.FieldMask(paths=["paths_value"]), + ) + + +def test_delete_device_registry( + transport: str = "grpc", request_type=device_manager.DeleteDeviceRegistryRequest +): + client = DeviceManagerClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.delete_device_registry), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + + response = client.delete_device_registry(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == device_manager.DeleteDeviceRegistryRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_device_registry_from_dict(): + test_delete_device_registry(request_type=dict) + + +@pytest.mark.asyncio +async def test_delete_device_registry_async(transport: str = "grpc_asyncio"): + client = DeviceManagerAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = device_manager.DeleteDeviceRegistryRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.delete_device_registry), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + + response = await client.delete_device_registry(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_device_registry_field_headers(): + client = DeviceManagerClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = device_manager.DeleteDeviceRegistryRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.delete_device_registry), "__call__" + ) as call: + call.return_value = None + + client.delete_device_registry(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_delete_device_registry_field_headers_async(): + client = DeviceManagerAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = device_manager.DeleteDeviceRegistryRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.delete_device_registry), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + + await client.delete_device_registry(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +def test_delete_device_registry_flattened(): + client = DeviceManagerClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.delete_device_registry), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_device_registry(name="name_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + +def test_delete_device_registry_flattened_error(): + client = DeviceManagerClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_device_registry( + device_manager.DeleteDeviceRegistryRequest(), name="name_value", + ) + + +@pytest.mark.asyncio +async def test_delete_device_registry_flattened_async(): + client = DeviceManagerAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.delete_device_registry), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_device_registry(name="name_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + +@pytest.mark.asyncio +async def test_delete_device_registry_flattened_error_async(): + client = DeviceManagerAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_device_registry( + device_manager.DeleteDeviceRegistryRequest(), name="name_value", + ) + + +def test_list_device_registries( + transport: str = "grpc", request_type=device_manager.ListDeviceRegistriesRequest +): + client = DeviceManagerClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.list_device_registries), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = device_manager.ListDeviceRegistriesResponse( + next_page_token="next_page_token_value", + ) + + response = client.list_device_registries(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == device_manager.ListDeviceRegistriesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListDeviceRegistriesPager) + + assert response.next_page_token == "next_page_token_value" + + +def test_list_device_registries_from_dict(): + test_list_device_registries(request_type=dict) + + +@pytest.mark.asyncio +async def test_list_device_registries_async(transport: str = "grpc_asyncio"): + client = DeviceManagerAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = device_manager.ListDeviceRegistriesRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.list_device_registries), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + device_manager.ListDeviceRegistriesResponse( + next_page_token="next_page_token_value", + ) + ) + + response = await client.list_device_registries(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListDeviceRegistriesAsyncPager) + + assert response.next_page_token == "next_page_token_value" + + +def test_list_device_registries_field_headers(): + client = DeviceManagerClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = device_manager.ListDeviceRegistriesRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.list_device_registries), "__call__" + ) as call: + call.return_value = device_manager.ListDeviceRegistriesResponse() + + client.list_device_registries(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_device_registries_field_headers_async(): + client = DeviceManagerAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = device_manager.ListDeviceRegistriesRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.list_device_registries), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + device_manager.ListDeviceRegistriesResponse() + ) + + await client.list_device_registries(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +def test_list_device_registries_flattened(): + client = DeviceManagerClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.list_device_registries), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = device_manager.ListDeviceRegistriesResponse() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_device_registries(parent="parent_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].parent == "parent_value" + + +def test_list_device_registries_flattened_error(): + client = DeviceManagerClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_device_registries( + device_manager.ListDeviceRegistriesRequest(), parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_device_registries_flattened_async(): + client = DeviceManagerAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.list_device_registries), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = device_manager.ListDeviceRegistriesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + device_manager.ListDeviceRegistriesResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_device_registries(parent="parent_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].parent == "parent_value" + + +@pytest.mark.asyncio +async def test_list_device_registries_flattened_error_async(): + client = DeviceManagerAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_device_registries( + device_manager.ListDeviceRegistriesRequest(), parent="parent_value", + ) + + +def test_list_device_registries_pager(): + client = DeviceManagerClient(credentials=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.list_device_registries), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + device_manager.ListDeviceRegistriesResponse( + device_registries=[ + resources.DeviceRegistry(), + resources.DeviceRegistry(), + resources.DeviceRegistry(), + ], + next_page_token="abc", + ), + device_manager.ListDeviceRegistriesResponse( + device_registries=[], next_page_token="def", + ), + device_manager.ListDeviceRegistriesResponse( + device_registries=[resources.DeviceRegistry(),], next_page_token="ghi", + ), + device_manager.ListDeviceRegistriesResponse( + device_registries=[ + resources.DeviceRegistry(), + resources.DeviceRegistry(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_device_registries(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, resources.DeviceRegistry) for i in results) + + +def test_list_device_registries_pages(): + client = DeviceManagerClient(credentials=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.list_device_registries), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + device_manager.ListDeviceRegistriesResponse( + device_registries=[ + resources.DeviceRegistry(), + resources.DeviceRegistry(), + resources.DeviceRegistry(), + ], + next_page_token="abc", + ), + device_manager.ListDeviceRegistriesResponse( + device_registries=[], next_page_token="def", + ), + device_manager.ListDeviceRegistriesResponse( + device_registries=[resources.DeviceRegistry(),], next_page_token="ghi", + ), + device_manager.ListDeviceRegistriesResponse( + device_registries=[ + resources.DeviceRegistry(), + resources.DeviceRegistry(), + ], + ), + RuntimeError, + ) + pages = list(client.list_device_registries(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.asyncio +async def test_list_device_registries_async_pager(): + client = DeviceManagerAsyncClient(credentials=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.list_device_registries), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + device_manager.ListDeviceRegistriesResponse( + device_registries=[ + resources.DeviceRegistry(), + resources.DeviceRegistry(), + resources.DeviceRegistry(), + ], + next_page_token="abc", + ), + device_manager.ListDeviceRegistriesResponse( + device_registries=[], next_page_token="def", + ), + device_manager.ListDeviceRegistriesResponse( + device_registries=[resources.DeviceRegistry(),], next_page_token="ghi", + ), + device_manager.ListDeviceRegistriesResponse( + device_registries=[ + resources.DeviceRegistry(), + resources.DeviceRegistry(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_device_registries(request={},) + assert async_pager.next_page_token == "abc" + responses = [] + async for response in async_pager: + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, resources.DeviceRegistry) for i in responses) + + +@pytest.mark.asyncio +async def test_list_device_registries_async_pages(): + client = DeviceManagerAsyncClient(credentials=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.list_device_registries), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + device_manager.ListDeviceRegistriesResponse( + device_registries=[ + resources.DeviceRegistry(), + resources.DeviceRegistry(), + resources.DeviceRegistry(), + ], + next_page_token="abc", + ), + device_manager.ListDeviceRegistriesResponse( + device_registries=[], next_page_token="def", + ), + device_manager.ListDeviceRegistriesResponse( + device_registries=[resources.DeviceRegistry(),], next_page_token="ghi", + ), + device_manager.ListDeviceRegistriesResponse( + device_registries=[ + resources.DeviceRegistry(), + resources.DeviceRegistry(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_device_registries(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_create_device( + transport: str = "grpc", request_type=device_manager.CreateDeviceRequest +): + client = DeviceManagerClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.create_device), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = resources.Device( + id="id_value", + name="name_value", + num_id=636, + blocked=True, + log_level=resources.LogLevel.NONE, + ) + + response = client.create_device(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == device_manager.CreateDeviceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.Device) + + assert response.id == "id_value" + + assert response.name == "name_value" + + assert response.num_id == 636 + + assert response.blocked is True + + assert response.log_level == resources.LogLevel.NONE + + +def test_create_device_from_dict(): + test_create_device(request_type=dict) + + +@pytest.mark.asyncio +async def test_create_device_async(transport: str = "grpc_asyncio"): + client = DeviceManagerAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = device_manager.CreateDeviceRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.create_device), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.Device( + id="id_value", + name="name_value", + num_id=636, + blocked=True, + log_level=resources.LogLevel.NONE, + ) + ) + + response = await client.create_device(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.Device) + + assert response.id == "id_value" + + assert response.name == "name_value" + + assert response.num_id == 636 + + assert response.blocked is True + + assert response.log_level == resources.LogLevel.NONE + + +def test_create_device_field_headers(): + client = DeviceManagerClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = device_manager.CreateDeviceRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.create_device), "__call__") as call: + call.return_value = resources.Device() + + client.create_device(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_create_device_field_headers_async(): + client = DeviceManagerAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = device_manager.CreateDeviceRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.create_device), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.Device()) + + await client.create_device(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +def test_create_device_flattened(): + client = DeviceManagerClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.create_device), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = resources.Device() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_device( + parent="parent_value", device=resources.Device(id="id_value"), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].parent == "parent_value" + + assert args[0].device == resources.Device(id="id_value") + + +def test_create_device_flattened_error(): + client = DeviceManagerClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_device( + device_manager.CreateDeviceRequest(), + parent="parent_value", + device=resources.Device(id="id_value"), + ) + + +@pytest.mark.asyncio +async def test_create_device_flattened_async(): + client = DeviceManagerAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.create_device), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = resources.Device() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.Device()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_device( + parent="parent_value", device=resources.Device(id="id_value"), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].parent == "parent_value" + + assert args[0].device == resources.Device(id="id_value") + + +@pytest.mark.asyncio +async def test_create_device_flattened_error_async(): + client = DeviceManagerAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_device( + device_manager.CreateDeviceRequest(), + parent="parent_value", + device=resources.Device(id="id_value"), + ) + + +def test_get_device( + transport: str = "grpc", request_type=device_manager.GetDeviceRequest +): + client = DeviceManagerClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.get_device), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = resources.Device( + id="id_value", + name="name_value", + num_id=636, + blocked=True, + log_level=resources.LogLevel.NONE, + ) + + response = client.get_device(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == device_manager.GetDeviceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.Device) + + assert response.id == "id_value" + + assert response.name == "name_value" + + assert response.num_id == 636 + + assert response.blocked is True + + assert response.log_level == resources.LogLevel.NONE + + +def test_get_device_from_dict(): + test_get_device(request_type=dict) + + +@pytest.mark.asyncio +async def test_get_device_async(transport: str = "grpc_asyncio"): + client = DeviceManagerAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = device_manager.GetDeviceRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.get_device), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.Device( + id="id_value", + name="name_value", + num_id=636, + blocked=True, + log_level=resources.LogLevel.NONE, + ) + ) + + response = await client.get_device(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.Device) + + assert response.id == "id_value" + + assert response.name == "name_value" + + assert response.num_id == 636 + + assert response.blocked is True + + assert response.log_level == resources.LogLevel.NONE + + +def test_get_device_field_headers(): + client = DeviceManagerClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = device_manager.GetDeviceRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.get_device), "__call__") as call: + call.return_value = resources.Device() + + client.get_device(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_device_field_headers_async(): + client = DeviceManagerAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = device_manager.GetDeviceRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.get_device), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.Device()) + + await client.get_device(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +def test_get_device_flattened(): + client = DeviceManagerClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.get_device), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = resources.Device() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_device(name="name_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + +def test_get_device_flattened_error(): + client = DeviceManagerClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_device( + device_manager.GetDeviceRequest(), name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_device_flattened_async(): + client = DeviceManagerAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.get_device), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = resources.Device() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.Device()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_device(name="name_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + +@pytest.mark.asyncio +async def test_get_device_flattened_error_async(): + client = DeviceManagerAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_device( + device_manager.GetDeviceRequest(), name="name_value", + ) + + +def test_update_device( + transport: str = "grpc", request_type=device_manager.UpdateDeviceRequest +): + client = DeviceManagerClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.update_device), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = resources.Device( + id="id_value", + name="name_value", + num_id=636, + blocked=True, + log_level=resources.LogLevel.NONE, + ) + + response = client.update_device(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == device_manager.UpdateDeviceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.Device) + + assert response.id == "id_value" + + assert response.name == "name_value" + + assert response.num_id == 636 + + assert response.blocked is True + + assert response.log_level == resources.LogLevel.NONE + + +def test_update_device_from_dict(): + test_update_device(request_type=dict) + + +@pytest.mark.asyncio +async def test_update_device_async(transport: str = "grpc_asyncio"): + client = DeviceManagerAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = device_manager.UpdateDeviceRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.update_device), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.Device( + id="id_value", + name="name_value", + num_id=636, + blocked=True, + log_level=resources.LogLevel.NONE, + ) + ) + + response = await client.update_device(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.Device) + + assert response.id == "id_value" + + assert response.name == "name_value" + + assert response.num_id == 636 + + assert response.blocked is True + + assert response.log_level == resources.LogLevel.NONE + + +def test_update_device_field_headers(): + client = DeviceManagerClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = device_manager.UpdateDeviceRequest() + request.device.name = "device.name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.update_device), "__call__") as call: + call.return_value = resources.Device() + + client.update_device(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "device.name=device.name/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_update_device_field_headers_async(): + client = DeviceManagerAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = device_manager.UpdateDeviceRequest() + request.device.name = "device.name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.update_device), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.Device()) + + await client.update_device(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "device.name=device.name/value",) in kw["metadata"] + + +def test_update_device_flattened(): + client = DeviceManagerClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.update_device), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = resources.Device() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_device( + device=resources.Device(id="id_value"), + update_mask=field_mask.FieldMask(paths=["paths_value"]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].device == resources.Device(id="id_value") + + assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + + +def test_update_device_flattened_error(): + client = DeviceManagerClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_device( + device_manager.UpdateDeviceRequest(), + device=resources.Device(id="id_value"), + update_mask=field_mask.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.asyncio +async def test_update_device_flattened_async(): + client = DeviceManagerAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.update_device), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = resources.Device() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.Device()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_device( + device=resources.Device(id="id_value"), + update_mask=field_mask.FieldMask(paths=["paths_value"]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].device == resources.Device(id="id_value") + + assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + + +@pytest.mark.asyncio +async def test_update_device_flattened_error_async(): + client = DeviceManagerAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_device( + device_manager.UpdateDeviceRequest(), + device=resources.Device(id="id_value"), + update_mask=field_mask.FieldMask(paths=["paths_value"]), + ) + + +def test_delete_device( + transport: str = "grpc", request_type=device_manager.DeleteDeviceRequest +): + client = DeviceManagerClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.delete_device), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + response = client.delete_device(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == device_manager.DeleteDeviceRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_device_from_dict(): + test_delete_device(request_type=dict) + + +@pytest.mark.asyncio +async def test_delete_device_async(transport: str = "grpc_asyncio"): + client = DeviceManagerAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = device_manager.DeleteDeviceRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.delete_device), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + + response = await client.delete_device(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_device_field_headers(): + client = DeviceManagerClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = device_manager.DeleteDeviceRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.delete_device), "__call__") as call: + call.return_value = None + + client.delete_device(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_delete_device_field_headers_async(): + client = DeviceManagerAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = device_manager.DeleteDeviceRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.delete_device), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + + await client.delete_device(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +def test_delete_device_flattened(): + client = DeviceManagerClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.delete_device), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_device(name="name_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + +def test_delete_device_flattened_error(): + client = DeviceManagerClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_device( + device_manager.DeleteDeviceRequest(), name="name_value", + ) + + +@pytest.mark.asyncio +async def test_delete_device_flattened_async(): + client = DeviceManagerAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.delete_device), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_device(name="name_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + +@pytest.mark.asyncio +async def test_delete_device_flattened_error_async(): + client = DeviceManagerAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_device( + device_manager.DeleteDeviceRequest(), name="name_value", + ) + + +def test_list_devices( + transport: str = "grpc", request_type=device_manager.ListDevicesRequest +): + client = DeviceManagerClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.list_devices), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = device_manager.ListDevicesResponse( + next_page_token="next_page_token_value", + ) + + response = client.list_devices(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == device_manager.ListDevicesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListDevicesPager) + + assert response.next_page_token == "next_page_token_value" + + +def test_list_devices_from_dict(): + test_list_devices(request_type=dict) + + +@pytest.mark.asyncio +async def test_list_devices_async(transport: str = "grpc_asyncio"): + client = DeviceManagerAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = device_manager.ListDevicesRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.list_devices), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + device_manager.ListDevicesResponse(next_page_token="next_page_token_value",) + ) + + response = await client.list_devices(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListDevicesAsyncPager) + + assert response.next_page_token == "next_page_token_value" + + +def test_list_devices_field_headers(): + client = DeviceManagerClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = device_manager.ListDevicesRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.list_devices), "__call__") as call: + call.return_value = device_manager.ListDevicesResponse() + + client.list_devices(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_devices_field_headers_async(): + client = DeviceManagerAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = device_manager.ListDevicesRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.list_devices), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + device_manager.ListDevicesResponse() + ) + + await client.list_devices(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +def test_list_devices_flattened(): + client = DeviceManagerClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.list_devices), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = device_manager.ListDevicesResponse() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_devices(parent="parent_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].parent == "parent_value" + + +def test_list_devices_flattened_error(): + client = DeviceManagerClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_devices( + device_manager.ListDevicesRequest(), parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_devices_flattened_async(): + client = DeviceManagerAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.list_devices), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = device_manager.ListDevicesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + device_manager.ListDevicesResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_devices(parent="parent_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].parent == "parent_value" + + +@pytest.mark.asyncio +async def test_list_devices_flattened_error_async(): + client = DeviceManagerAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_devices( + device_manager.ListDevicesRequest(), parent="parent_value", + ) + + +def test_list_devices_pager(): + client = DeviceManagerClient(credentials=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.list_devices), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + device_manager.ListDevicesResponse( + devices=[resources.Device(), resources.Device(), resources.Device(),], + next_page_token="abc", + ), + device_manager.ListDevicesResponse(devices=[], next_page_token="def",), + device_manager.ListDevicesResponse( + devices=[resources.Device(),], next_page_token="ghi", + ), + device_manager.ListDevicesResponse( + devices=[resources.Device(), resources.Device(),], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_devices(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, resources.Device) for i in results) + + +def test_list_devices_pages(): + client = DeviceManagerClient(credentials=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.list_devices), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + device_manager.ListDevicesResponse( + devices=[resources.Device(), resources.Device(), resources.Device(),], + next_page_token="abc", + ), + device_manager.ListDevicesResponse(devices=[], next_page_token="def",), + device_manager.ListDevicesResponse( + devices=[resources.Device(),], next_page_token="ghi", + ), + device_manager.ListDevicesResponse( + devices=[resources.Device(), resources.Device(),], + ), + RuntimeError, + ) + pages = list(client.list_devices(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.asyncio +async def test_list_devices_async_pager(): + client = DeviceManagerAsyncClient(credentials=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.list_devices), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + device_manager.ListDevicesResponse( + devices=[resources.Device(), resources.Device(), resources.Device(),], + next_page_token="abc", + ), + device_manager.ListDevicesResponse(devices=[], next_page_token="def",), + device_manager.ListDevicesResponse( + devices=[resources.Device(),], next_page_token="ghi", + ), + device_manager.ListDevicesResponse( + devices=[resources.Device(), resources.Device(),], + ), + RuntimeError, + ) + async_pager = await client.list_devices(request={},) + assert async_pager.next_page_token == "abc" + responses = [] + async for response in async_pager: + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, resources.Device) for i in responses) + + +@pytest.mark.asyncio +async def test_list_devices_async_pages(): + client = DeviceManagerAsyncClient(credentials=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.list_devices), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + device_manager.ListDevicesResponse( + devices=[resources.Device(), resources.Device(), resources.Device(),], + next_page_token="abc", + ), + device_manager.ListDevicesResponse(devices=[], next_page_token="def",), + device_manager.ListDevicesResponse( + devices=[resources.Device(),], next_page_token="ghi", + ), + device_manager.ListDevicesResponse( + devices=[resources.Device(), resources.Device(),], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_devices(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_modify_cloud_to_device_config( + transport: str = "grpc", + request_type=device_manager.ModifyCloudToDeviceConfigRequest, +): + client = DeviceManagerClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.modify_cloud_to_device_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = resources.DeviceConfig( + version=774, binary_data=b"binary_data_blob", + ) + + response = client.modify_cloud_to_device_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == device_manager.ModifyCloudToDeviceConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.DeviceConfig) + + assert response.version == 774 + + assert response.binary_data == b"binary_data_blob" + + +def test_modify_cloud_to_device_config_from_dict(): + test_modify_cloud_to_device_config(request_type=dict) + + +@pytest.mark.asyncio +async def test_modify_cloud_to_device_config_async(transport: str = "grpc_asyncio"): + client = DeviceManagerAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = device_manager.ModifyCloudToDeviceConfigRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.modify_cloud_to_device_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.DeviceConfig(version=774, binary_data=b"binary_data_blob",) + ) + + response = await client.modify_cloud_to_device_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.DeviceConfig) + + assert response.version == 774 + + assert response.binary_data == b"binary_data_blob" + + +def test_modify_cloud_to_device_config_field_headers(): + client = DeviceManagerClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = device_manager.ModifyCloudToDeviceConfigRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.modify_cloud_to_device_config), "__call__" + ) as call: + call.return_value = resources.DeviceConfig() + + client.modify_cloud_to_device_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_modify_cloud_to_device_config_field_headers_async(): + client = DeviceManagerAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = device_manager.ModifyCloudToDeviceConfigRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.modify_cloud_to_device_config), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.DeviceConfig() + ) + + await client.modify_cloud_to_device_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +def test_modify_cloud_to_device_config_flattened(): + client = DeviceManagerClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.modify_cloud_to_device_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = resources.DeviceConfig() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.modify_cloud_to_device_config( + name="name_value", binary_data=b"binary_data_blob", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + assert args[0].binary_data == b"binary_data_blob" + + +def test_modify_cloud_to_device_config_flattened_error(): + client = DeviceManagerClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.modify_cloud_to_device_config( + device_manager.ModifyCloudToDeviceConfigRequest(), + name="name_value", + binary_data=b"binary_data_blob", + ) + + +@pytest.mark.asyncio +async def test_modify_cloud_to_device_config_flattened_async(): + client = DeviceManagerAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.modify_cloud_to_device_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = resources.DeviceConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.DeviceConfig() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.modify_cloud_to_device_config( + name="name_value", binary_data=b"binary_data_blob", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + assert args[0].binary_data == b"binary_data_blob" + + +@pytest.mark.asyncio +async def test_modify_cloud_to_device_config_flattened_error_async(): + client = DeviceManagerAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.modify_cloud_to_device_config( + device_manager.ModifyCloudToDeviceConfigRequest(), + name="name_value", + binary_data=b"binary_data_blob", + ) + + +def test_list_device_config_versions( + transport: str = "grpc", request_type=device_manager.ListDeviceConfigVersionsRequest +): + client = DeviceManagerClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.list_device_config_versions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = device_manager.ListDeviceConfigVersionsResponse() + + response = client.list_device_config_versions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == device_manager.ListDeviceConfigVersionsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, device_manager.ListDeviceConfigVersionsResponse) + + +def test_list_device_config_versions_from_dict(): + test_list_device_config_versions(request_type=dict) + + +@pytest.mark.asyncio +async def test_list_device_config_versions_async(transport: str = "grpc_asyncio"): + client = DeviceManagerAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = device_manager.ListDeviceConfigVersionsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.list_device_config_versions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + device_manager.ListDeviceConfigVersionsResponse() + ) + + response = await client.list_device_config_versions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, device_manager.ListDeviceConfigVersionsResponse) + + +def test_list_device_config_versions_field_headers(): + client = DeviceManagerClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = device_manager.ListDeviceConfigVersionsRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.list_device_config_versions), "__call__" + ) as call: + call.return_value = device_manager.ListDeviceConfigVersionsResponse() + + client.list_device_config_versions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_device_config_versions_field_headers_async(): + client = DeviceManagerAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = device_manager.ListDeviceConfigVersionsRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.list_device_config_versions), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + device_manager.ListDeviceConfigVersionsResponse() + ) + + await client.list_device_config_versions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +def test_list_device_config_versions_flattened(): + client = DeviceManagerClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.list_device_config_versions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = device_manager.ListDeviceConfigVersionsResponse() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_device_config_versions(name="name_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + +def test_list_device_config_versions_flattened_error(): + client = DeviceManagerClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_device_config_versions( + device_manager.ListDeviceConfigVersionsRequest(), name="name_value", + ) + + +@pytest.mark.asyncio +async def test_list_device_config_versions_flattened_async(): + client = DeviceManagerAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.list_device_config_versions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = device_manager.ListDeviceConfigVersionsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + device_manager.ListDeviceConfigVersionsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_device_config_versions(name="name_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + +@pytest.mark.asyncio +async def test_list_device_config_versions_flattened_error_async(): + client = DeviceManagerAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_device_config_versions( + device_manager.ListDeviceConfigVersionsRequest(), name="name_value", + ) + + +def test_list_device_states( + transport: str = "grpc", request_type=device_manager.ListDeviceStatesRequest +): + client = DeviceManagerClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.list_device_states), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = device_manager.ListDeviceStatesResponse() + + response = client.list_device_states(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == device_manager.ListDeviceStatesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, device_manager.ListDeviceStatesResponse) + + +def test_list_device_states_from_dict(): + test_list_device_states(request_type=dict) + + +@pytest.mark.asyncio +async def test_list_device_states_async(transport: str = "grpc_asyncio"): + client = DeviceManagerAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = device_manager.ListDeviceStatesRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.list_device_states), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + device_manager.ListDeviceStatesResponse() + ) + + response = await client.list_device_states(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, device_manager.ListDeviceStatesResponse) + + +def test_list_device_states_field_headers(): + client = DeviceManagerClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = device_manager.ListDeviceStatesRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.list_device_states), "__call__" + ) as call: + call.return_value = device_manager.ListDeviceStatesResponse() + + client.list_device_states(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_device_states_field_headers_async(): + client = DeviceManagerAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = device_manager.ListDeviceStatesRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.list_device_states), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + device_manager.ListDeviceStatesResponse() + ) + + await client.list_device_states(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +def test_list_device_states_flattened(): + client = DeviceManagerClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.list_device_states), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = device_manager.ListDeviceStatesResponse() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_device_states(name="name_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + +def test_list_device_states_flattened_error(): + client = DeviceManagerClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_device_states( + device_manager.ListDeviceStatesRequest(), name="name_value", + ) + + +@pytest.mark.asyncio +async def test_list_device_states_flattened_async(): + client = DeviceManagerAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.list_device_states), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = device_manager.ListDeviceStatesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + device_manager.ListDeviceStatesResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_device_states(name="name_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + +@pytest.mark.asyncio +async def test_list_device_states_flattened_error_async(): + client = DeviceManagerAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_device_states( + device_manager.ListDeviceStatesRequest(), name="name_value", + ) + + +def test_set_iam_policy( + transport: str = "grpc", request_type=iam_policy.SetIamPolicyRequest +): + client = DeviceManagerClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy.Policy(version=774, etag=b"etag_blob",) + + response = client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == iam_policy.SetIamPolicyRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, policy.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +def test_set_iam_policy_from_dict(): + test_set_iam_policy(request_type=dict) + + +@pytest.mark.asyncio +async def test_set_iam_policy_async(transport: str = "grpc_asyncio"): + client = DeviceManagerAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy.SetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.set_iam_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy.Policy(version=774, etag=b"etag_blob",) + ) + + response = await client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +def test_set_iam_policy_field_headers(): + client = DeviceManagerClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy.SetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.set_iam_policy), "__call__") as call: + call.return_value = policy.Policy() + + client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_set_iam_policy_field_headers_async(): + client = DeviceManagerAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy.SetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.set_iam_policy), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy.Policy()) + + await client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +def test_set_iam_policy_from_dict(): + client = DeviceManagerClient(credentials=credentials.AnonymousCredentials(),) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy.Policy() + + response = client.set_iam_policy( + request={ + "resource": "resource_value", + "policy": policy.Policy(version=774), + } + ) + call.assert_called() + + +def test_set_iam_policy_flattened(): + client = DeviceManagerClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy.Policy() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.set_iam_policy(resource="resource_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].resource == "resource_value" + + +def test_set_iam_policy_flattened_error(): + client = DeviceManagerClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.set_iam_policy( + iam_policy.SetIamPolicyRequest(), resource="resource_value", + ) + + +@pytest.mark.asyncio +async def test_set_iam_policy_flattened_async(): + client = DeviceManagerAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.set_iam_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = policy.Policy() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy.Policy()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.set_iam_policy(resource="resource_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].resource == "resource_value" + + +@pytest.mark.asyncio +async def test_set_iam_policy_flattened_error_async(): + client = DeviceManagerAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.set_iam_policy( + iam_policy.SetIamPolicyRequest(), resource="resource_value", + ) + + +def test_get_iam_policy( + transport: str = "grpc", request_type=iam_policy.GetIamPolicyRequest +): + client = DeviceManagerClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy.Policy(version=774, etag=b"etag_blob",) + + response = client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == iam_policy.GetIamPolicyRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, policy.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +def test_get_iam_policy_from_dict(): + test_get_iam_policy(request_type=dict) + + +@pytest.mark.asyncio +async def test_get_iam_policy_async(transport: str = "grpc_asyncio"): + client = DeviceManagerAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy.GetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.get_iam_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy.Policy(version=774, etag=b"etag_blob",) + ) + + response = await client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +def test_get_iam_policy_field_headers(): + client = DeviceManagerClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy.GetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.get_iam_policy), "__call__") as call: + call.return_value = policy.Policy() + + client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_iam_policy_field_headers_async(): + client = DeviceManagerAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy.GetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.get_iam_policy), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy.Policy()) + + await client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +def test_get_iam_policy_from_dict(): + client = DeviceManagerClient(credentials=credentials.AnonymousCredentials(),) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy.Policy() + + response = client.get_iam_policy( + request={ + "resource": "resource_value", + "options": options.GetPolicyOptions(requested_policy_version=2598), + } + ) + call.assert_called() + + +def test_get_iam_policy_flattened(): + client = DeviceManagerClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy.Policy() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_iam_policy(resource="resource_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].resource == "resource_value" + + +def test_get_iam_policy_flattened_error(): + client = DeviceManagerClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_iam_policy( + iam_policy.GetIamPolicyRequest(), resource="resource_value", + ) + + +@pytest.mark.asyncio +async def test_get_iam_policy_flattened_async(): + client = DeviceManagerAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.get_iam_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = policy.Policy() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy.Policy()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_iam_policy(resource="resource_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].resource == "resource_value" + + +@pytest.mark.asyncio +async def test_get_iam_policy_flattened_error_async(): + client = DeviceManagerAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_iam_policy( + iam_policy.GetIamPolicyRequest(), resource="resource_value", + ) + + +def test_test_iam_permissions( + transport: str = "grpc", request_type=iam_policy.TestIamPermissionsRequest +): + client = DeviceManagerClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iam_policy.TestIamPermissionsResponse( + permissions=["permissions_value"], + ) + + response = client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == iam_policy.TestIamPermissionsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy.TestIamPermissionsResponse) + + assert response.permissions == ["permissions_value"] + + +def test_test_iam_permissions_from_dict(): + test_test_iam_permissions(request_type=dict) + + +@pytest.mark.asyncio +async def test_test_iam_permissions_async(transport: str = "grpc_asyncio"): + client = DeviceManagerAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy.TestIamPermissionsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy.TestIamPermissionsResponse(permissions=["permissions_value"],) + ) + + response = await client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy.TestIamPermissionsResponse) + + assert response.permissions == ["permissions_value"] + + +def test_test_iam_permissions_field_headers(): + client = DeviceManagerClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy.TestIamPermissionsRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.test_iam_permissions), "__call__" + ) as call: + call.return_value = iam_policy.TestIamPermissionsResponse() + + client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_test_iam_permissions_field_headers_async(): + client = DeviceManagerAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy.TestIamPermissionsRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.test_iam_permissions), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy.TestIamPermissionsResponse() + ) + + await client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +def test_test_iam_permissions_from_dict(): + client = DeviceManagerClient(credentials=credentials.AnonymousCredentials(),) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iam_policy.TestIamPermissionsResponse() + + response = client.test_iam_permissions( + request={ + "resource": "resource_value", + "permissions": ["permissions_value"], + } + ) + call.assert_called() + + +def test_test_iam_permissions_flattened(): + client = DeviceManagerClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iam_policy.TestIamPermissionsResponse() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.test_iam_permissions( + resource="resource_value", permissions=["permissions_value"], + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].resource == "resource_value" + + assert args[0].permissions == ["permissions_value"] + + +def test_test_iam_permissions_flattened_error(): + client = DeviceManagerClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.test_iam_permissions( + iam_policy.TestIamPermissionsRequest(), + resource="resource_value", + permissions=["permissions_value"], + ) + + +@pytest.mark.asyncio +async def test_test_iam_permissions_flattened_async(): + client = DeviceManagerAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iam_policy.TestIamPermissionsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy.TestIamPermissionsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.test_iam_permissions( + resource="resource_value", permissions=["permissions_value"], + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].resource == "resource_value" + + assert args[0].permissions == ["permissions_value"] + + +@pytest.mark.asyncio +async def test_test_iam_permissions_flattened_error_async(): + client = DeviceManagerAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.test_iam_permissions( + iam_policy.TestIamPermissionsRequest(), + resource="resource_value", + permissions=["permissions_value"], + ) + + +def test_send_command_to_device( + transport: str = "grpc", request_type=device_manager.SendCommandToDeviceRequest +): + client = DeviceManagerClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.send_command_to_device), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = device_manager.SendCommandToDeviceResponse() + + response = client.send_command_to_device(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == device_manager.SendCommandToDeviceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, device_manager.SendCommandToDeviceResponse) + + +def test_send_command_to_device_from_dict(): + test_send_command_to_device(request_type=dict) + + +@pytest.mark.asyncio +async def test_send_command_to_device_async(transport: str = "grpc_asyncio"): + client = DeviceManagerAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = device_manager.SendCommandToDeviceRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.send_command_to_device), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + device_manager.SendCommandToDeviceResponse() + ) + + response = await client.send_command_to_device(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, device_manager.SendCommandToDeviceResponse) + + +def test_send_command_to_device_field_headers(): + client = DeviceManagerClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = device_manager.SendCommandToDeviceRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.send_command_to_device), "__call__" + ) as call: + call.return_value = device_manager.SendCommandToDeviceResponse() + + client.send_command_to_device(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_send_command_to_device_field_headers_async(): + client = DeviceManagerAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = device_manager.SendCommandToDeviceRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.send_command_to_device), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + device_manager.SendCommandToDeviceResponse() + ) + + await client.send_command_to_device(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +def test_send_command_to_device_flattened(): + client = DeviceManagerClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.send_command_to_device), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = device_manager.SendCommandToDeviceResponse() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.send_command_to_device( + name="name_value", + binary_data=b"binary_data_blob", + subfolder="subfolder_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + assert args[0].binary_data == b"binary_data_blob" + + assert args[0].subfolder == "subfolder_value" + + +def test_send_command_to_device_flattened_error(): + client = DeviceManagerClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.send_command_to_device( + device_manager.SendCommandToDeviceRequest(), + name="name_value", + binary_data=b"binary_data_blob", + subfolder="subfolder_value", + ) + + +@pytest.mark.asyncio +async def test_send_command_to_device_flattened_async(): + client = DeviceManagerAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.send_command_to_device), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = device_manager.SendCommandToDeviceResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + device_manager.SendCommandToDeviceResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.send_command_to_device( + name="name_value", + binary_data=b"binary_data_blob", + subfolder="subfolder_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + assert args[0].binary_data == b"binary_data_blob" + + assert args[0].subfolder == "subfolder_value" + + +@pytest.mark.asyncio +async def test_send_command_to_device_flattened_error_async(): + client = DeviceManagerAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.send_command_to_device( + device_manager.SendCommandToDeviceRequest(), + name="name_value", + binary_data=b"binary_data_blob", + subfolder="subfolder_value", + ) + + +def test_bind_device_to_gateway( + transport: str = "grpc", request_type=device_manager.BindDeviceToGatewayRequest +): + client = DeviceManagerClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.bind_device_to_gateway), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = device_manager.BindDeviceToGatewayResponse() + + response = client.bind_device_to_gateway(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == device_manager.BindDeviceToGatewayRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, device_manager.BindDeviceToGatewayResponse) + + +def test_bind_device_to_gateway_from_dict(): + test_bind_device_to_gateway(request_type=dict) + + +@pytest.mark.asyncio +async def test_bind_device_to_gateway_async(transport: str = "grpc_asyncio"): + client = DeviceManagerAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = device_manager.BindDeviceToGatewayRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.bind_device_to_gateway), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + device_manager.BindDeviceToGatewayResponse() + ) + + response = await client.bind_device_to_gateway(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, device_manager.BindDeviceToGatewayResponse) + + +def test_bind_device_to_gateway_field_headers(): + client = DeviceManagerClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = device_manager.BindDeviceToGatewayRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.bind_device_to_gateway), "__call__" + ) as call: + call.return_value = device_manager.BindDeviceToGatewayResponse() + + client.bind_device_to_gateway(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_bind_device_to_gateway_field_headers_async(): + client = DeviceManagerAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = device_manager.BindDeviceToGatewayRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.bind_device_to_gateway), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + device_manager.BindDeviceToGatewayResponse() + ) + + await client.bind_device_to_gateway(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +def test_bind_device_to_gateway_flattened(): + client = DeviceManagerClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.bind_device_to_gateway), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = device_manager.BindDeviceToGatewayResponse() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.bind_device_to_gateway( + parent="parent_value", + gateway_id="gateway_id_value", + device_id="device_id_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].parent == "parent_value" + + assert args[0].gateway_id == "gateway_id_value" + + assert args[0].device_id == "device_id_value" + + +def test_bind_device_to_gateway_flattened_error(): + client = DeviceManagerClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.bind_device_to_gateway( + device_manager.BindDeviceToGatewayRequest(), + parent="parent_value", + gateway_id="gateway_id_value", + device_id="device_id_value", + ) + + +@pytest.mark.asyncio +async def test_bind_device_to_gateway_flattened_async(): + client = DeviceManagerAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.bind_device_to_gateway), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = device_manager.BindDeviceToGatewayResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + device_manager.BindDeviceToGatewayResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.bind_device_to_gateway( + parent="parent_value", + gateway_id="gateway_id_value", + device_id="device_id_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].parent == "parent_value" + + assert args[0].gateway_id == "gateway_id_value" + + assert args[0].device_id == "device_id_value" + + +@pytest.mark.asyncio +async def test_bind_device_to_gateway_flattened_error_async(): + client = DeviceManagerAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.bind_device_to_gateway( + device_manager.BindDeviceToGatewayRequest(), + parent="parent_value", + gateway_id="gateway_id_value", + device_id="device_id_value", + ) + + +def test_unbind_device_from_gateway( + transport: str = "grpc", request_type=device_manager.UnbindDeviceFromGatewayRequest +): + client = DeviceManagerClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.unbind_device_from_gateway), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = device_manager.UnbindDeviceFromGatewayResponse() + + response = client.unbind_device_from_gateway(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == device_manager.UnbindDeviceFromGatewayRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, device_manager.UnbindDeviceFromGatewayResponse) + + +def test_unbind_device_from_gateway_from_dict(): + test_unbind_device_from_gateway(request_type=dict) + + +@pytest.mark.asyncio +async def test_unbind_device_from_gateway_async(transport: str = "grpc_asyncio"): + client = DeviceManagerAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = device_manager.UnbindDeviceFromGatewayRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.unbind_device_from_gateway), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + device_manager.UnbindDeviceFromGatewayResponse() + ) + + response = await client.unbind_device_from_gateway(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, device_manager.UnbindDeviceFromGatewayResponse) + + +def test_unbind_device_from_gateway_field_headers(): + client = DeviceManagerClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = device_manager.UnbindDeviceFromGatewayRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.unbind_device_from_gateway), "__call__" + ) as call: + call.return_value = device_manager.UnbindDeviceFromGatewayResponse() + + client.unbind_device_from_gateway(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_unbind_device_from_gateway_field_headers_async(): + client = DeviceManagerAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = device_manager.UnbindDeviceFromGatewayRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.unbind_device_from_gateway), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + device_manager.UnbindDeviceFromGatewayResponse() + ) + + await client.unbind_device_from_gateway(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +def test_unbind_device_from_gateway_flattened(): + client = DeviceManagerClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.unbind_device_from_gateway), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = device_manager.UnbindDeviceFromGatewayResponse() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.unbind_device_from_gateway( + parent="parent_value", + gateway_id="gateway_id_value", + device_id="device_id_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].parent == "parent_value" + + assert args[0].gateway_id == "gateway_id_value" + + assert args[0].device_id == "device_id_value" + + +def test_unbind_device_from_gateway_flattened_error(): + client = DeviceManagerClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.unbind_device_from_gateway( + device_manager.UnbindDeviceFromGatewayRequest(), + parent="parent_value", + gateway_id="gateway_id_value", + device_id="device_id_value", + ) + + +@pytest.mark.asyncio +async def test_unbind_device_from_gateway_flattened_async(): + client = DeviceManagerAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.unbind_device_from_gateway), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = device_manager.UnbindDeviceFromGatewayResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + device_manager.UnbindDeviceFromGatewayResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.unbind_device_from_gateway( + parent="parent_value", + gateway_id="gateway_id_value", + device_id="device_id_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].parent == "parent_value" + + assert args[0].gateway_id == "gateway_id_value" + + assert args[0].device_id == "device_id_value" + + +@pytest.mark.asyncio +async def test_unbind_device_from_gateway_flattened_error_async(): + client = DeviceManagerAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.unbind_device_from_gateway( + device_manager.UnbindDeviceFromGatewayRequest(), + parent="parent_value", + gateway_id="gateway_id_value", + device_id="device_id_value", + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.DeviceManagerGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = DeviceManagerClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.DeviceManagerGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = DeviceManagerClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.DeviceManagerGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = DeviceManagerClient( + client_options={"scopes": ["1", "2"]}, transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.DeviceManagerGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + client = DeviceManagerClient(transport=transport) + assert client._transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.DeviceManagerGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.DeviceManagerGrpcAsyncIOTransport( + credentials=credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = DeviceManagerClient(credentials=credentials.AnonymousCredentials(),) + assert isinstance(client._transport, transports.DeviceManagerGrpcTransport,) + + +def test_device_manager_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(exceptions.DuplicateCredentialArgs): + transport = transports.DeviceManagerTransport( + credentials=credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_device_manager_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.iot_v1.services.device_manager.transports.DeviceManagerTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.DeviceManagerTransport( + credentials=credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "create_device_registry", + "get_device_registry", + "update_device_registry", + "delete_device_registry", + "list_device_registries", + "create_device", + "get_device", + "update_device", + "delete_device", + "list_devices", + "modify_cloud_to_device_config", + "list_device_config_versions", + "list_device_states", + "set_iam_policy", + "get_iam_policy", + "test_iam_permissions", + "send_command_to_device", + "bind_device_to_gateway", + "unbind_device_from_gateway", + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + +def test_device_manager_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object( + auth, "load_credentials_from_file" + ) as load_creds, mock.patch( + "google.cloud.iot_v1.services.device_manager.transports.DeviceManagerTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (credentials.AnonymousCredentials(), None) + transport = transports.DeviceManagerTransport( + credentials_file="credentials.json", quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloudiot", + ), + quota_project_id="octopus", + ) + + +def test_device_manager_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(auth, "default") as adc: + adc.return_value = (credentials.AnonymousCredentials(), None) + DeviceManagerClient() + adc.assert_called_once_with( + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloudiot", + ), + quota_project_id=None, + ) + + +def test_device_manager_transport_auth_adc(): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(auth, "default") as adc: + adc.return_value = (credentials.AnonymousCredentials(), None) + transports.DeviceManagerGrpcTransport( + host="squid.clam.whelk", quota_project_id="octopus" + ) + adc.assert_called_once_with( + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloudiot", + ), + quota_project_id="octopus", + ) + + +def test_device_manager_host_no_port(): + client = DeviceManagerClient( + credentials=credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="cloudiot.googleapis.com" + ), + ) + assert client._transport._host == "cloudiot.googleapis.com:443" + + +def test_device_manager_host_with_port(): + client = DeviceManagerClient( + credentials=credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="cloudiot.googleapis.com:8000" + ), + ) + assert client._transport._host == "cloudiot.googleapis.com:8000" + + +def test_device_manager_grpc_transport_channel(): + channel = grpc.insecure_channel("http://localhost/") + + # Check that if channel is provided, mtls endpoint and client_cert_source + # won't be used. + callback = mock.MagicMock() + transport = transports.DeviceManagerGrpcTransport( + host="squid.clam.whelk", + channel=channel, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=callback, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert not callback.called + + +def test_device_manager_grpc_asyncio_transport_channel(): + channel = aio.insecure_channel("http://localhost/") + + # Check that if channel is provided, mtls endpoint and client_cert_source + # won't be used. + callback = mock.MagicMock() + transport = transports.DeviceManagerGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=callback, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert not callback.called + + +@mock.patch("grpc.ssl_channel_credentials", autospec=True) +@mock.patch("google.api_core.grpc_helpers.create_channel", autospec=True) +def test_device_manager_grpc_transport_channel_mtls_with_client_cert_source( + grpc_create_channel, grpc_ssl_channel_cred +): + # Check that if channel is None, but api_mtls_endpoint and client_cert_source + # are provided, then a mTLS channel will be created. + mock_cred = mock.Mock() + + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + transport = transports.DeviceManagerGrpcTransport( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloudiot", + ), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + ) + assert transport.grpc_channel == mock_grpc_channel + + +@mock.patch("grpc.ssl_channel_credentials", autospec=True) +@mock.patch("google.api_core.grpc_helpers_async.create_channel", autospec=True) +def test_device_manager_grpc_asyncio_transport_channel_mtls_with_client_cert_source( + grpc_create_channel, grpc_ssl_channel_cred +): + # Check that if channel is None, but api_mtls_endpoint and client_cert_source + # are provided, then a mTLS channel will be created. + mock_cred = mock.Mock() + + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + transport = transports.DeviceManagerGrpcAsyncIOTransport( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloudiot", + ), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + ) + assert transport.grpc_channel == mock_grpc_channel + + +@pytest.mark.parametrize( + "api_mtls_endpoint", ["mtls.squid.clam.whelk", "mtls.squid.clam.whelk:443"] +) +@mock.patch("google.api_core.grpc_helpers.create_channel", autospec=True) +def test_device_manager_grpc_transport_channel_mtls_with_adc( + grpc_create_channel, api_mtls_endpoint +): + # Check that if channel and client_cert_source are None, but api_mtls_endpoint + # is provided, then a mTLS channel will be created with SSL ADC. + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + # Mock google.auth.transport.grpc.SslCredentials class. + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + mock_cred = mock.Mock() + transport = transports.DeviceManagerGrpcTransport( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint=api_mtls_endpoint, + client_cert_source=None, + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloudiot", + ), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + ) + assert transport.grpc_channel == mock_grpc_channel + + +@pytest.mark.parametrize( + "api_mtls_endpoint", ["mtls.squid.clam.whelk", "mtls.squid.clam.whelk:443"] +) +@mock.patch("google.api_core.grpc_helpers_async.create_channel", autospec=True) +def test_device_manager_grpc_asyncio_transport_channel_mtls_with_adc( + grpc_create_channel, api_mtls_endpoint +): + # Check that if channel and client_cert_source are None, but api_mtls_endpoint + # is provided, then a mTLS channel will be created with SSL ADC. + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + # Mock google.auth.transport.grpc.SslCredentials class. + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + mock_cred = mock.Mock() + transport = transports.DeviceManagerGrpcAsyncIOTransport( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint=api_mtls_endpoint, + client_cert_source=None, + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloudiot", + ), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_registry_path(): + project = "squid" + location = "clam" + registry = "whelk" + + expected = "projects/{project}/locations/{location}/registries/{registry}".format( + project=project, location=location, registry=registry, + ) + actual = DeviceManagerClient.registry_path(project, location, registry) + assert expected == actual + + +def test_parse_registry_path(): + expected = { + "project": "octopus", + "location": "oyster", + "registry": "nudibranch", + } + path = DeviceManagerClient.registry_path(**expected) + + # Check that the path construction is reversible. + actual = DeviceManagerClient.parse_registry_path(path) + assert expected == actual + + +def test_device_path(): + project = "squid" + location = "clam" + registry = "whelk" + device = "octopus" + + expected = "projects/{project}/locations/{location}/registries/{registry}/devices/{device}".format( + project=project, location=location, registry=registry, device=device, + ) + actual = DeviceManagerClient.device_path(project, location, registry, device) + assert expected == actual + + +def test_parse_device_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + "registry": "cuttlefish", + "device": "mussel", + } + path = DeviceManagerClient.device_path(**expected) + + # Check that the path construction is reversible. + actual = DeviceManagerClient.parse_device_path(path) + assert expected == actual + + +def test_client_withDEFAULT_CLIENT_INFO(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object( + transports.DeviceManagerTransport, "_prep_wrapped_messages" + ) as prep: + client = DeviceManagerClient( + credentials=credentials.AnonymousCredentials(), client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object( + transports.DeviceManagerTransport, "_prep_wrapped_messages" + ) as prep: + transport_class = DeviceManagerClient.get_transport_class() + transport = transport_class( + credentials=credentials.AnonymousCredentials(), client_info=client_info, + ) + prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/v1/test_device_manager_client_v1.py b/tests/unit/gapic/v1/test_device_manager_client_v1.py deleted file mode 100644 index e94e464c..00000000 --- a/tests/unit/gapic/v1/test_device_manager_client_v1.py +++ /dev/null @@ -1,869 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Unit tests.""" - -import mock -import pytest - -from google.cloud import iot_v1 -from google.cloud.iot_v1.proto import device_manager_pb2 -from google.cloud.iot_v1.proto import resources_pb2 -from google.iam.v1 import iam_policy_pb2 -from google.iam.v1 import policy_pb2 -from google.protobuf import empty_pb2 -from google.protobuf import field_mask_pb2 - - -class MultiCallableStub(object): - """Stub for the grpc.UnaryUnaryMultiCallable interface.""" - - def __init__(self, method, channel_stub): - self.method = method - self.channel_stub = channel_stub - - def __call__(self, request, timeout=None, metadata=None, credentials=None): - self.channel_stub.requests.append((self.method, request)) - - response = None - if self.channel_stub.responses: - response = self.channel_stub.responses.pop() - - if isinstance(response, Exception): - raise response - - if response: - return response - - -class ChannelStub(object): - """Stub for the grpc.Channel interface.""" - - def __init__(self, responses=[]): - self.responses = responses - self.requests = [] - - def unary_unary(self, method, request_serializer=None, response_deserializer=None): - return MultiCallableStub(method, self) - - -class CustomException(Exception): - pass - - -class TestDeviceManagerClient(object): - def test_delete_device_registry(self): - channel = ChannelStub() - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = iot_v1.DeviceManagerClient() - - # Setup Request - name = client.registry_path("[PROJECT]", "[LOCATION]", "[REGISTRY]") - - client.delete_device_registry(name) - - assert len(channel.requests) == 1 - expected_request = device_manager_pb2.DeleteDeviceRegistryRequest(name=name) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_delete_device_registry_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = iot_v1.DeviceManagerClient() - - # Setup request - name = client.registry_path("[PROJECT]", "[LOCATION]", "[REGISTRY]") - - with pytest.raises(CustomException): - client.delete_device_registry(name) - - def test_delete_device(self): - channel = ChannelStub() - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = iot_v1.DeviceManagerClient() - - # Setup Request - name = client.device_path("[PROJECT]", "[LOCATION]", "[REGISTRY]", "[DEVICE]") - - client.delete_device(name) - - assert len(channel.requests) == 1 - expected_request = device_manager_pb2.DeleteDeviceRequest(name=name) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_delete_device_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = iot_v1.DeviceManagerClient() - - # Setup request - name = client.device_path("[PROJECT]", "[LOCATION]", "[REGISTRY]", "[DEVICE]") - - with pytest.raises(CustomException): - client.delete_device(name) - - def test_modify_cloud_to_device_config(self): - # Setup Expected Response - version = 351608024 - binary_data_2 = b"-37" - expected_response = {"version": version, "binary_data": binary_data_2} - expected_response = resources_pb2.DeviceConfig(**expected_response) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = iot_v1.DeviceManagerClient() - - # Setup Request - name = client.device_path("[PROJECT]", "[LOCATION]", "[REGISTRY]", "[DEVICE]") - binary_data = b"40" - - response = client.modify_cloud_to_device_config(name, binary_data) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = device_manager_pb2.ModifyCloudToDeviceConfigRequest( - name=name, binary_data=binary_data - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_modify_cloud_to_device_config_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = iot_v1.DeviceManagerClient() - - # Setup request - name = client.device_path("[PROJECT]", "[LOCATION]", "[REGISTRY]", "[DEVICE]") - binary_data = b"40" - - with pytest.raises(CustomException): - client.modify_cloud_to_device_config(name, binary_data) - - def test_send_command_to_device(self): - # Setup Expected Response - expected_response = {} - expected_response = device_manager_pb2.SendCommandToDeviceResponse( - **expected_response - ) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = iot_v1.DeviceManagerClient() - - # Setup Request - name = client.device_path("[PROJECT]", "[LOCATION]", "[REGISTRY]", "[DEVICE]") - binary_data = b"40" - - response = client.send_command_to_device(name, binary_data) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = device_manager_pb2.SendCommandToDeviceRequest( - name=name, binary_data=binary_data - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_send_command_to_device_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = iot_v1.DeviceManagerClient() - - # Setup request - name = client.device_path("[PROJECT]", "[LOCATION]", "[REGISTRY]", "[DEVICE]") - binary_data = b"40" - - with pytest.raises(CustomException): - client.send_command_to_device(name, binary_data) - - def test_create_device_registry(self): - # Setup Expected Response - id_ = "id3355" - name = "name3373707" - expected_response = {"id": id_, "name": name} - expected_response = resources_pb2.DeviceRegistry(**expected_response) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = iot_v1.DeviceManagerClient() - - # Setup Request - parent = client.location_path("[PROJECT]", "[LOCATION]") - device_registry = {} - - response = client.create_device_registry(parent, device_registry) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = device_manager_pb2.CreateDeviceRegistryRequest( - parent=parent, device_registry=device_registry - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_create_device_registry_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = iot_v1.DeviceManagerClient() - - # Setup request - parent = client.location_path("[PROJECT]", "[LOCATION]") - device_registry = {} - - with pytest.raises(CustomException): - client.create_device_registry(parent, device_registry) - - def test_get_device_registry(self): - # Setup Expected Response - id_ = "id3355" - name_2 = "name2-1052831874" - expected_response = {"id": id_, "name": name_2} - expected_response = resources_pb2.DeviceRegistry(**expected_response) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = iot_v1.DeviceManagerClient() - - # Setup Request - name = client.registry_path("[PROJECT]", "[LOCATION]", "[REGISTRY]") - - response = client.get_device_registry(name) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = device_manager_pb2.GetDeviceRegistryRequest(name=name) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_get_device_registry_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = iot_v1.DeviceManagerClient() - - # Setup request - name = client.registry_path("[PROJECT]", "[LOCATION]", "[REGISTRY]") - - with pytest.raises(CustomException): - client.get_device_registry(name) - - def test_update_device_registry(self): - # Setup Expected Response - id_ = "id3355" - name = "name3373707" - expected_response = {"id": id_, "name": name} - expected_response = resources_pb2.DeviceRegistry(**expected_response) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = iot_v1.DeviceManagerClient() - - # Setup Request - device_registry = {} - update_mask = {} - - response = client.update_device_registry(device_registry, update_mask) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = device_manager_pb2.UpdateDeviceRegistryRequest( - device_registry=device_registry, update_mask=update_mask - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_update_device_registry_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = iot_v1.DeviceManagerClient() - - # Setup request - device_registry = {} - update_mask = {} - - with pytest.raises(CustomException): - client.update_device_registry(device_registry, update_mask) - - def test_list_device_registries(self): - # Setup Expected Response - next_page_token = "" - device_registries_element = {} - device_registries = [device_registries_element] - expected_response = { - "next_page_token": next_page_token, - "device_registries": device_registries, - } - expected_response = device_manager_pb2.ListDeviceRegistriesResponse( - **expected_response - ) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = iot_v1.DeviceManagerClient() - - # Setup Request - parent = client.location_path("[PROJECT]", "[LOCATION]") - - paged_list_response = client.list_device_registries(parent) - resources = list(paged_list_response) - assert len(resources) == 1 - - assert expected_response.device_registries[0] == resources[0] - - assert len(channel.requests) == 1 - expected_request = device_manager_pb2.ListDeviceRegistriesRequest(parent=parent) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_list_device_registries_exception(self): - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = iot_v1.DeviceManagerClient() - - # Setup request - parent = client.location_path("[PROJECT]", "[LOCATION]") - - paged_list_response = client.list_device_registries(parent) - with pytest.raises(CustomException): - list(paged_list_response) - - def test_create_device(self): - # Setup Expected Response - id_ = "id3355" - name = "name3373707" - num_id = 1034366860 - blocked = True - expected_response = { - "id": id_, - "name": name, - "num_id": num_id, - "blocked": blocked, - } - expected_response = resources_pb2.Device(**expected_response) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = iot_v1.DeviceManagerClient() - - # Setup Request - parent = client.registry_path("[PROJECT]", "[LOCATION]", "[REGISTRY]") - device = {} - - response = client.create_device(parent, device) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = device_manager_pb2.CreateDeviceRequest( - parent=parent, device=device - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_create_device_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = iot_v1.DeviceManagerClient() - - # Setup request - parent = client.registry_path("[PROJECT]", "[LOCATION]", "[REGISTRY]") - device = {} - - with pytest.raises(CustomException): - client.create_device(parent, device) - - def test_get_device(self): - # Setup Expected Response - id_ = "id3355" - name_2 = "name2-1052831874" - num_id = 1034366860 - blocked = True - expected_response = { - "id": id_, - "name": name_2, - "num_id": num_id, - "blocked": blocked, - } - expected_response = resources_pb2.Device(**expected_response) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = iot_v1.DeviceManagerClient() - - # Setup Request - name = client.device_path("[PROJECT]", "[LOCATION]", "[REGISTRY]", "[DEVICE]") - - response = client.get_device(name) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = device_manager_pb2.GetDeviceRequest(name=name) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_get_device_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = iot_v1.DeviceManagerClient() - - # Setup request - name = client.device_path("[PROJECT]", "[LOCATION]", "[REGISTRY]", "[DEVICE]") - - with pytest.raises(CustomException): - client.get_device(name) - - def test_update_device(self): - # Setup Expected Response - id_ = "id3355" - name = "name3373707" - num_id = 1034366860 - blocked = True - expected_response = { - "id": id_, - "name": name, - "num_id": num_id, - "blocked": blocked, - } - expected_response = resources_pb2.Device(**expected_response) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = iot_v1.DeviceManagerClient() - - # Setup Request - device = {} - update_mask = {} - - response = client.update_device(device, update_mask) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = device_manager_pb2.UpdateDeviceRequest( - device=device, update_mask=update_mask - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_update_device_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = iot_v1.DeviceManagerClient() - - # Setup request - device = {} - update_mask = {} - - with pytest.raises(CustomException): - client.update_device(device, update_mask) - - def test_list_devices(self): - # Setup Expected Response - next_page_token = "" - devices_element = {} - devices = [devices_element] - expected_response = {"next_page_token": next_page_token, "devices": devices} - expected_response = device_manager_pb2.ListDevicesResponse(**expected_response) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = iot_v1.DeviceManagerClient() - - # Setup Request - parent = client.registry_path("[PROJECT]", "[LOCATION]", "[REGISTRY]") - - paged_list_response = client.list_devices(parent) - resources = list(paged_list_response) - assert len(resources) == 1 - - assert expected_response.devices[0] == resources[0] - - assert len(channel.requests) == 1 - expected_request = device_manager_pb2.ListDevicesRequest(parent=parent) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_list_devices_exception(self): - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = iot_v1.DeviceManagerClient() - - # Setup request - parent = client.registry_path("[PROJECT]", "[LOCATION]", "[REGISTRY]") - - paged_list_response = client.list_devices(parent) - with pytest.raises(CustomException): - list(paged_list_response) - - def test_list_device_config_versions(self): - # Setup Expected Response - expected_response = {} - expected_response = device_manager_pb2.ListDeviceConfigVersionsResponse( - **expected_response - ) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = iot_v1.DeviceManagerClient() - - # Setup Request - name = client.device_path("[PROJECT]", "[LOCATION]", "[REGISTRY]", "[DEVICE]") - - response = client.list_device_config_versions(name) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = device_manager_pb2.ListDeviceConfigVersionsRequest(name=name) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_list_device_config_versions_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = iot_v1.DeviceManagerClient() - - # Setup request - name = client.device_path("[PROJECT]", "[LOCATION]", "[REGISTRY]", "[DEVICE]") - - with pytest.raises(CustomException): - client.list_device_config_versions(name) - - def test_list_device_states(self): - # Setup Expected Response - expected_response = {} - expected_response = device_manager_pb2.ListDeviceStatesResponse( - **expected_response - ) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = iot_v1.DeviceManagerClient() - - # Setup Request - name = client.device_path("[PROJECT]", "[LOCATION]", "[REGISTRY]", "[DEVICE]") - - response = client.list_device_states(name) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = device_manager_pb2.ListDeviceStatesRequest(name=name) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_list_device_states_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = iot_v1.DeviceManagerClient() - - # Setup request - name = client.device_path("[PROJECT]", "[LOCATION]", "[REGISTRY]", "[DEVICE]") - - with pytest.raises(CustomException): - client.list_device_states(name) - - def test_set_iam_policy(self): - # Setup Expected Response - version = 351608024 - etag = b"21" - expected_response = {"version": version, "etag": etag} - expected_response = policy_pb2.Policy(**expected_response) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = iot_v1.DeviceManagerClient() - - # Setup Request - resource = "resource-341064690" - policy = {} - - response = client.set_iam_policy(resource, policy) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = iam_policy_pb2.SetIamPolicyRequest( - resource=resource, policy=policy - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_set_iam_policy_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = iot_v1.DeviceManagerClient() - - # Setup request - resource = "resource-341064690" - policy = {} - - with pytest.raises(CustomException): - client.set_iam_policy(resource, policy) - - def test_get_iam_policy(self): - # Setup Expected Response - version = 351608024 - etag = b"21" - expected_response = {"version": version, "etag": etag} - expected_response = policy_pb2.Policy(**expected_response) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = iot_v1.DeviceManagerClient() - - # Setup Request - resource = "resource-341064690" - - response = client.get_iam_policy(resource) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = iam_policy_pb2.GetIamPolicyRequest(resource=resource) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_get_iam_policy_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = iot_v1.DeviceManagerClient() - - # Setup request - resource = "resource-341064690" - - with pytest.raises(CustomException): - client.get_iam_policy(resource) - - def test_test_iam_permissions(self): - # Setup Expected Response - expected_response = {} - expected_response = iam_policy_pb2.TestIamPermissionsResponse( - **expected_response - ) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = iot_v1.DeviceManagerClient() - - # Setup Request - resource = "resource-341064690" - permissions = [] - - response = client.test_iam_permissions(resource, permissions) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = iam_policy_pb2.TestIamPermissionsRequest( - resource=resource, permissions=permissions - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_test_iam_permissions_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = iot_v1.DeviceManagerClient() - - # Setup request - resource = "resource-341064690" - permissions = [] - - with pytest.raises(CustomException): - client.test_iam_permissions(resource, permissions) - - def test_bind_device_to_gateway(self): - # Setup Expected Response - expected_response = {} - expected_response = device_manager_pb2.BindDeviceToGatewayResponse( - **expected_response - ) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = iot_v1.DeviceManagerClient() - - # Setup Request - parent = client.registry_path("[PROJECT]", "[LOCATION]", "[REGISTRY]") - gateway_id = "gatewayId955798774" - device_id = "deviceId25209764" - - response = client.bind_device_to_gateway(parent, gateway_id, device_id) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = device_manager_pb2.BindDeviceToGatewayRequest( - parent=parent, gateway_id=gateway_id, device_id=device_id - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_bind_device_to_gateway_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = iot_v1.DeviceManagerClient() - - # Setup request - parent = client.registry_path("[PROJECT]", "[LOCATION]", "[REGISTRY]") - gateway_id = "gatewayId955798774" - device_id = "deviceId25209764" - - with pytest.raises(CustomException): - client.bind_device_to_gateway(parent, gateway_id, device_id) - - def test_unbind_device_from_gateway(self): - # Setup Expected Response - expected_response = {} - expected_response = device_manager_pb2.UnbindDeviceFromGatewayResponse( - **expected_response - ) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = iot_v1.DeviceManagerClient() - - # Setup Request - parent = client.registry_path("[PROJECT]", "[LOCATION]", "[REGISTRY]") - gateway_id = "gatewayId955798774" - device_id = "deviceId25209764" - - response = client.unbind_device_from_gateway(parent, gateway_id, device_id) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = device_manager_pb2.UnbindDeviceFromGatewayRequest( - parent=parent, gateway_id=gateway_id, device_id=device_id - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_unbind_device_from_gateway_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = iot_v1.DeviceManagerClient() - - # Setup request - parent = client.registry_path("[PROJECT]", "[LOCATION]", "[REGISTRY]") - gateway_id = "gatewayId955798774" - device_id = "deviceId25209764" - - with pytest.raises(CustomException): - client.unbind_device_from_gateway(parent, gateway_id, device_id)