From db58059c88b76726e9de76d5d316a5ed1597be9e Mon Sep 17 00:00:00 2001 From: Ethan Ann Date: Thu, 20 Aug 2026 09:03:48 -0400 Subject: [PATCH 1/2] Migrate from msrest to azure-core --- .gitignore | 4 + samples/get_digital_twin_sample.py | 6 +- samples/invoke_command_sample.py | 6 +- samples/invoke_component_command_sample.py | 6 +- .../iothub_configuration_manager_sample.py | 6 +- ...iothub_job_manager_import_export_sample.py | 6 +- samples/iothub_job_manager_method_sample.py | 6 +- .../iothub_job_manager_twin_update_sample.py | 6 +- ...hub_registry_manager_bulk_create_sample.py | 6 +- ..._manager_c2d_amqp_over_websocket_sample.py | 6 +- samples/iothub_registry_manager_c2d_sample.py | 6 +- ...hub_registry_manager_edge_device_sample.py | 6 +- .../iothub_registry_manager_method_sample.py | 6 +- ...b_registry_manager_module_method_sample.py | 6 +- .../iothub_registry_manager_module_sample.py | 6 +- .../iothub_registry_manager_query_sample.py | 6 +- samples/iothub_registry_manager_sample.py | 6 +- ...thub_registry_manager_statistics_sample.py | 6 +- ...egistry_manager_token_credential_sample.py | 6 +- samples/iothub_registry_mgr_update_x509.py | 6 +- samples/registry_manager_pnp_sample.py | 6 +- samples/update_digital_twin_sample.py | 6 +- setup.py | 3 +- src/apiview-properties.json | 137 ++ src/azure/iot/hub/auth.py | 75 +- src/azure/iot/hub/digital_twin_client.py | 18 +- .../iot/hub/iothub_configuration_manager.py | 24 +- .../iot/hub/iothub_http_runtime_manager.py | 16 +- src/azure/iot/hub/iothub_job_manager.py | 26 +- src/azure/iot/hub/iothub_registry_manager.py | 95 +- src/azure/iot/hub/protocol/__init__.py | 29 +- src/azure/iot/hub/protocol/_configuration.py | 44 + .../protocol/_iot_hub_gateway_service_apis.py | 133 ++ src/azure/iot/hub/protocol/_patch.py | 21 + .../{version.py => _utils/__init__.py} | 8 +- .../iot/hub/protocol/_utils/serialization.py | 2041 +++++++++++++++++ src/azure/iot/hub/protocol/_version.py | 9 + src/azure/iot/hub/protocol/aio/__init__.py | 29 + .../iot/hub/protocol/aio/_configuration.py | 44 + .../aio/_iot_hub_gateway_service_apis.py | 135 ++ src/azure/iot/hub/protocol/aio/_patch.py | 21 + .../hub/protocol/aio/operations/__init__.py | 41 + .../operations/_bulk_registry_operations.py | 161 ++ .../_cloud_to_device_messages_operations.py | 249 ++ .../operations/_configuration_operations.py | 543 +++++ .../aio/operations/_devices_operations.py | 768 +++++++ .../operations/_digital_twin_operations.py | 413 ++++ .../aio/operations/_jobs_operations.py | 589 +++++ .../aio/operations/_modules_operations.py | 829 +++++++ .../iot/hub/protocol/aio/operations/_patch.py | 21 + .../aio/operations/_query_operations.py | 199 ++ .../aio/operations/_statistics_operations.py | 148 ++ .../protocol/iot_hub_gateway_service_ap_is.py | 112 - src/azure/iot/hub/protocol/models/__init__.py | 190 +- .../_iot_hub_gateway_service_apis_enums.py | 412 ++++ .../iot/hub/protocol/models/_models_py3.py | 1955 ++++++++++++++++ src/azure/iot/hub/protocol/models/_patch.py | 21 + .../models/authentication_mechanism.py | 36 - .../models/authentication_mechanism_py3.py | 36 - .../models/bulk_registry_operation_result.py | 32 - .../bulk_registry_operation_result_py3.py | 32 - .../protocol/models/cloud_to_device_method.py | 37 - .../models/cloud_to_device_method_py3.py | 45 - .../models/cloud_to_device_method_result.py | 28 - .../cloud_to_device_method_result_py3.py | 28 - .../iot/hub/protocol/models/configuration.py | 68 - .../protocol/models/configuration_content.py | 32 - .../models/configuration_content_py3.py | 34 - .../protocol/models/configuration_metrics.py | 28 - .../models/configuration_metrics_py3.py | 28 - .../hub/protocol/models/configuration_py3.py | 83 - .../configuration_queries_test_input.py | 30 - .../configuration_queries_test_input_py3.py | 32 - .../configuration_queries_test_response.py | 30 - ...configuration_queries_test_response_py3.py | 32 - src/azure/iot/hub/protocol/models/device.py | 91 - .../protocol/models/device_capabilities.py | 23 - .../models/device_capabilities_py3.py | 23 - .../protocol/models/device_job_statistics.py | 40 - .../models/device_job_statistics_py3.py | 49 - .../iot/hub/protocol/models/device_py3.py | 109 - .../models/device_registry_operation_error.py | 138 -- .../device_registry_operation_error_py3.py | 147 -- .../device_registry_operation_warning.py | 33 - .../device_registry_operation_warning_py3.py | 35 - .../protocol/models/export_import_device.py | 86 - .../models/export_import_device_py3.py | 103 - .../iot/hub/protocol/models/job_properties.py | 106 - .../hub/protocol/models/job_properties_py3.py | 126 - .../iot/hub/protocol/models/job_request.py | 56 - .../hub/protocol/models/job_request_py3.py | 67 - .../iot/hub/protocol/models/job_response.py | 83 - .../hub/protocol/models/job_response_py3.py | 100 - .../hub/protocol/models/managed_identity.py | 22 - .../protocol/models/managed_identity_py3.py | 22 - src/azure/iot/hub/protocol/models/module.py | 69 - .../iot/hub/protocol/models/module_py3.py | 83 - .../hub/protocol/models/property_container.py | 37 - .../protocol/models/property_container_py3.py | 37 - .../models/purge_message_queue_result.py | 32 - .../models/purge_message_queue_result_py3.py | 39 - .../iot/hub/protocol/models/query_result.py | 34 - .../hub/protocol/models/query_result_py3.py | 34 - .../protocol/models/query_specification.py | 22 - .../models/query_specification_py3.py | 22 - .../protocol/models/registry_statistics.py | 33 - .../models/registry_statistics_py3.py | 40 - .../hub/protocol/models/service_statistics.py | 22 - .../protocol/models/service_statistics_py3.py | 22 - .../iot/hub/protocol/models/symmetric_key.py | 28 - .../hub/protocol/models/symmetric_key_py3.py | 28 - src/azure/iot/hub/protocol/models/twin.py | 122 - .../hub/protocol/models/twin_properties.py | 37 - .../protocol/models/twin_properties_py3.py | 37 - src/azure/iot/hub/protocol/models/twin_py3.py | 144 -- .../hub/protocol/models/x509_thumbprint.py | 29 - .../protocol/models/x509_thumbprint_py3.py | 31 - .../iot/hub/protocol/operations/__init__.py | 35 +- .../operations/_bulk_registry_operations.py | 185 ++ .../_cloud_to_device_messages_operations.py | 329 +++ .../operations/_configuration_operations.py | 683 ++++++ .../operations/_devices_operations.py | 969 ++++++++ .../operations/_digital_twin_operations.py | 550 +++++ .../protocol/operations/_jobs_operations.py | 771 +++++++ .../operations/_modules_operations.py | 1043 +++++++++ .../iot/hub/protocol/operations/_patch.py | 21 + .../protocol/operations/_query_operations.py | 229 ++ .../operations/_statistics_operations.py | 185 ++ .../operations/bulk_registry_operations.py | 96 - .../cloud_to_device_messages_operations.py | 234 -- .../operations/configuration_operations.py | 376 --- .../protocol/operations/devices_operations.py | 536 ----- .../operations/digital_twin_operations.py | 341 --- .../protocol/operations/jobs_operations.py | 489 ---- .../protocol/operations/modules_operations.py | 572 ----- .../protocol/operations/query_operations.py | 120 - .../operations/statistics_operations.py | 133 -- src/azure/iot/hub/protocol/py.typed | 1 + swagger/README.md | 54 + tests/test_digital_twin_client.py | 14 +- tests/test_iothub_configuration_manager.py | 14 +- tests/test_iothub_http_runtime_manager.py | 14 +- tests/test_iothub_registry_manager.py | 62 +- tests/test_job_manager.py | 14 +- 144 files changed, 14390 insertions(+), 6481 deletions(-) create mode 100644 src/apiview-properties.json create mode 100644 src/azure/iot/hub/protocol/_configuration.py create mode 100644 src/azure/iot/hub/protocol/_iot_hub_gateway_service_apis.py create mode 100644 src/azure/iot/hub/protocol/_patch.py rename src/azure/iot/hub/protocol/{version.py => _utils/__init__.py} (61%) create mode 100644 src/azure/iot/hub/protocol/_utils/serialization.py create mode 100644 src/azure/iot/hub/protocol/_version.py create mode 100644 src/azure/iot/hub/protocol/aio/__init__.py create mode 100644 src/azure/iot/hub/protocol/aio/_configuration.py create mode 100644 src/azure/iot/hub/protocol/aio/_iot_hub_gateway_service_apis.py create mode 100644 src/azure/iot/hub/protocol/aio/_patch.py create mode 100644 src/azure/iot/hub/protocol/aio/operations/__init__.py create mode 100644 src/azure/iot/hub/protocol/aio/operations/_bulk_registry_operations.py create mode 100644 src/azure/iot/hub/protocol/aio/operations/_cloud_to_device_messages_operations.py create mode 100644 src/azure/iot/hub/protocol/aio/operations/_configuration_operations.py create mode 100644 src/azure/iot/hub/protocol/aio/operations/_devices_operations.py create mode 100644 src/azure/iot/hub/protocol/aio/operations/_digital_twin_operations.py create mode 100644 src/azure/iot/hub/protocol/aio/operations/_jobs_operations.py create mode 100644 src/azure/iot/hub/protocol/aio/operations/_modules_operations.py create mode 100644 src/azure/iot/hub/protocol/aio/operations/_patch.py create mode 100644 src/azure/iot/hub/protocol/aio/operations/_query_operations.py create mode 100644 src/azure/iot/hub/protocol/aio/operations/_statistics_operations.py delete mode 100644 src/azure/iot/hub/protocol/iot_hub_gateway_service_ap_is.py create mode 100644 src/azure/iot/hub/protocol/models/_iot_hub_gateway_service_apis_enums.py create mode 100644 src/azure/iot/hub/protocol/models/_models_py3.py create mode 100644 src/azure/iot/hub/protocol/models/_patch.py delete mode 100644 src/azure/iot/hub/protocol/models/authentication_mechanism.py delete mode 100644 src/azure/iot/hub/protocol/models/authentication_mechanism_py3.py delete mode 100644 src/azure/iot/hub/protocol/models/bulk_registry_operation_result.py delete mode 100644 src/azure/iot/hub/protocol/models/bulk_registry_operation_result_py3.py delete mode 100644 src/azure/iot/hub/protocol/models/cloud_to_device_method.py delete mode 100644 src/azure/iot/hub/protocol/models/cloud_to_device_method_py3.py delete mode 100644 src/azure/iot/hub/protocol/models/cloud_to_device_method_result.py delete mode 100644 src/azure/iot/hub/protocol/models/cloud_to_device_method_result_py3.py delete mode 100644 src/azure/iot/hub/protocol/models/configuration.py delete mode 100644 src/azure/iot/hub/protocol/models/configuration_content.py delete mode 100644 src/azure/iot/hub/protocol/models/configuration_content_py3.py delete mode 100644 src/azure/iot/hub/protocol/models/configuration_metrics.py delete mode 100644 src/azure/iot/hub/protocol/models/configuration_metrics_py3.py delete mode 100644 src/azure/iot/hub/protocol/models/configuration_py3.py delete mode 100644 src/azure/iot/hub/protocol/models/configuration_queries_test_input.py delete mode 100644 src/azure/iot/hub/protocol/models/configuration_queries_test_input_py3.py delete mode 100644 src/azure/iot/hub/protocol/models/configuration_queries_test_response.py delete mode 100644 src/azure/iot/hub/protocol/models/configuration_queries_test_response_py3.py delete mode 100644 src/azure/iot/hub/protocol/models/device.py delete mode 100644 src/azure/iot/hub/protocol/models/device_capabilities.py delete mode 100644 src/azure/iot/hub/protocol/models/device_capabilities_py3.py delete mode 100644 src/azure/iot/hub/protocol/models/device_job_statistics.py delete mode 100644 src/azure/iot/hub/protocol/models/device_job_statistics_py3.py delete mode 100644 src/azure/iot/hub/protocol/models/device_py3.py delete mode 100644 src/azure/iot/hub/protocol/models/device_registry_operation_error.py delete mode 100644 src/azure/iot/hub/protocol/models/device_registry_operation_error_py3.py delete mode 100644 src/azure/iot/hub/protocol/models/device_registry_operation_warning.py delete mode 100644 src/azure/iot/hub/protocol/models/device_registry_operation_warning_py3.py delete mode 100644 src/azure/iot/hub/protocol/models/export_import_device.py delete mode 100644 src/azure/iot/hub/protocol/models/export_import_device_py3.py delete mode 100644 src/azure/iot/hub/protocol/models/job_properties.py delete mode 100644 src/azure/iot/hub/protocol/models/job_properties_py3.py delete mode 100644 src/azure/iot/hub/protocol/models/job_request.py delete mode 100644 src/azure/iot/hub/protocol/models/job_request_py3.py delete mode 100644 src/azure/iot/hub/protocol/models/job_response.py delete mode 100644 src/azure/iot/hub/protocol/models/job_response_py3.py delete mode 100644 src/azure/iot/hub/protocol/models/managed_identity.py delete mode 100644 src/azure/iot/hub/protocol/models/managed_identity_py3.py delete mode 100644 src/azure/iot/hub/protocol/models/module.py delete mode 100644 src/azure/iot/hub/protocol/models/module_py3.py delete mode 100644 src/azure/iot/hub/protocol/models/property_container.py delete mode 100644 src/azure/iot/hub/protocol/models/property_container_py3.py delete mode 100644 src/azure/iot/hub/protocol/models/purge_message_queue_result.py delete mode 100644 src/azure/iot/hub/protocol/models/purge_message_queue_result_py3.py delete mode 100644 src/azure/iot/hub/protocol/models/query_result.py delete mode 100644 src/azure/iot/hub/protocol/models/query_result_py3.py delete mode 100644 src/azure/iot/hub/protocol/models/query_specification.py delete mode 100644 src/azure/iot/hub/protocol/models/query_specification_py3.py delete mode 100644 src/azure/iot/hub/protocol/models/registry_statistics.py delete mode 100644 src/azure/iot/hub/protocol/models/registry_statistics_py3.py delete mode 100644 src/azure/iot/hub/protocol/models/service_statistics.py delete mode 100644 src/azure/iot/hub/protocol/models/service_statistics_py3.py delete mode 100644 src/azure/iot/hub/protocol/models/symmetric_key.py delete mode 100644 src/azure/iot/hub/protocol/models/symmetric_key_py3.py delete mode 100644 src/azure/iot/hub/protocol/models/twin.py delete mode 100644 src/azure/iot/hub/protocol/models/twin_properties.py delete mode 100644 src/azure/iot/hub/protocol/models/twin_properties_py3.py delete mode 100644 src/azure/iot/hub/protocol/models/twin_py3.py delete mode 100644 src/azure/iot/hub/protocol/models/x509_thumbprint.py delete mode 100644 src/azure/iot/hub/protocol/models/x509_thumbprint_py3.py create mode 100644 src/azure/iot/hub/protocol/operations/_bulk_registry_operations.py create mode 100644 src/azure/iot/hub/protocol/operations/_cloud_to_device_messages_operations.py create mode 100644 src/azure/iot/hub/protocol/operations/_configuration_operations.py create mode 100644 src/azure/iot/hub/protocol/operations/_devices_operations.py create mode 100644 src/azure/iot/hub/protocol/operations/_digital_twin_operations.py create mode 100644 src/azure/iot/hub/protocol/operations/_jobs_operations.py create mode 100644 src/azure/iot/hub/protocol/operations/_modules_operations.py create mode 100644 src/azure/iot/hub/protocol/operations/_patch.py create mode 100644 src/azure/iot/hub/protocol/operations/_query_operations.py create mode 100644 src/azure/iot/hub/protocol/operations/_statistics_operations.py delete mode 100644 src/azure/iot/hub/protocol/operations/bulk_registry_operations.py delete mode 100644 src/azure/iot/hub/protocol/operations/cloud_to_device_messages_operations.py delete mode 100644 src/azure/iot/hub/protocol/operations/configuration_operations.py delete mode 100644 src/azure/iot/hub/protocol/operations/devices_operations.py delete mode 100644 src/azure/iot/hub/protocol/operations/digital_twin_operations.py delete mode 100644 src/azure/iot/hub/protocol/operations/jobs_operations.py delete mode 100644 src/azure/iot/hub/protocol/operations/modules_operations.py delete mode 100644 src/azure/iot/hub/protocol/operations/query_operations.py delete mode 100644 src/azure/iot/hub/protocol/operations/statistics_operations.py create mode 100644 src/azure/iot/hub/protocol/py.typed create mode 100644 swagger/README.md diff --git a/.gitignore b/.gitignore index 64b1e97..598507a 100644 --- a/.gitignore +++ b/.gitignore @@ -125,3 +125,7 @@ demoCA/ # e2e **/_e2e_settings.json + +# AutoRest codegen scratch (local install of @autorest/core, @autorest/python) +.autorest/ +node_modules/ diff --git a/samples/get_digital_twin_sample.py b/samples/get_digital_twin_sample.py index 8f5beab..e1dd7fa 100644 --- a/samples/get_digital_twin_sample.py +++ b/samples/get_digital_twin_sample.py @@ -5,7 +5,7 @@ # -------------------------------------------------------------------------- import os -import msrest +from azure.core.exceptions import HttpResponseError from azure.iot.hub import DigitalTwinClient @@ -25,8 +25,8 @@ print("No digital_twin found") -except msrest.exceptions.HttpOperationError as ex: - print("HttpOperationError error {0}".format(ex.response.text)) +except HttpResponseError as ex: + print("HttpResponseError error {0}".format(ex)) except Exception as exc: print("Unexpected error {0}".format(exc)) except KeyboardInterrupt: diff --git a/samples/invoke_command_sample.py b/samples/invoke_command_sample.py index c03133b..f78c2fa 100644 --- a/samples/invoke_command_sample.py +++ b/samples/invoke_command_sample.py @@ -5,7 +5,7 @@ # -------------------------------------------------------------------------- import os -import msrest +from azure.core.exceptions import HttpResponseError from azure.iot.hub import DigitalTwinClient @@ -30,8 +30,8 @@ else: print("No invoke_command_result found") -except msrest.exceptions.HttpOperationError as ex: - print("HttpOperationError error {0}".format(ex.response.text)) +except HttpResponseError as ex: + print("HttpResponseError error {0}".format(ex)) except Exception as exc: print("Unexpected error {0}".format(exc)) except KeyboardInterrupt: diff --git a/samples/invoke_component_command_sample.py b/samples/invoke_component_command_sample.py index f0d9d14..bcb7b39 100644 --- a/samples/invoke_component_command_sample.py +++ b/samples/invoke_component_command_sample.py @@ -5,7 +5,7 @@ # -------------------------------------------------------------------------- import os -import msrest +from azure.core.exceptions import HttpResponseError from azure.iot.hub import DigitalTwinClient @@ -38,8 +38,8 @@ else: print("No invoke_component_command_result found") -except msrest.exceptions.HttpOperationError as ex: - print("HttpOperationError error {0}".format(ex.response.text)) +except HttpResponseError as ex: + print("HttpResponseError error {0}".format(ex)) except Exception as exc: print("Unexpected error {0}".format(exc)) except KeyboardInterrupt: diff --git a/samples/iothub_configuration_manager_sample.py b/samples/iothub_configuration_manager_sample.py index c295b78..350af23 100644 --- a/samples/iothub_configuration_manager_sample.py +++ b/samples/iothub_configuration_manager_sample.py @@ -5,7 +5,7 @@ # -------------------------------------------------------------------------- import os -import msrest +from azure.core.exceptions import HttpResponseError from azure.iot.hub import IoTHubConfigurationManager from azure.iot.hub.models import Configuration, ConfigurationContent, ConfigurationMetrics @@ -69,8 +69,8 @@ def create_configuration(config_id): else: print("No configuration found") -except msrest.exceptions.HttpOperationError as ex: - print("HttpOperationError error {0}".format(ex.response.text)) +except HttpResponseError as ex: + print("HttpResponseError error {0}".format(ex)) except Exception as ex: print("Unexpected error {0}".format(ex)) except KeyboardInterrupt: diff --git a/samples/iothub_job_manager_import_export_sample.py b/samples/iothub_job_manager_import_export_sample.py index db58f13..9ac4f56 100644 --- a/samples/iothub_job_manager_import_export_sample.py +++ b/samples/iothub_job_manager_import_export_sample.py @@ -5,7 +5,7 @@ # -------------------------------------------------------------------------- import os -import msrest +from azure.core.exceptions import HttpResponseError from azure.iot.hub import IoTHubJobManager from azure.iot.hub.models import JobProperties @@ -85,8 +85,8 @@ def print_export_import_jobs(title, export_import_jobs): ) print(cancel_export_import_job) -except msrest.exceptions.HttpOperationError as ex: - print("HttpOperationError error {0}".format(ex.response.text)) +except HttpResponseError as ex: + print("HttpResponseError error {0}".format(ex)) except Exception as ex: print("Unexpected error {0}".format(ex)) except KeyboardInterrupt: diff --git a/samples/iothub_job_manager_method_sample.py b/samples/iothub_job_manager_method_sample.py index e7f91b2..8d6e3fa 100644 --- a/samples/iothub_job_manager_method_sample.py +++ b/samples/iothub_job_manager_method_sample.py @@ -8,8 +8,8 @@ import uuid import time import datetime -import msrest import pprint +from azure.core.exceptions import HttpResponseError from azure.iot.hub import IoTHubJobManager from azure.iot.hub.models import JobRequest, CloudToDeviceMethod @@ -56,8 +56,8 @@ def print_job_response(title, response): break time.sleep(5) -except msrest.exceptions.HttpOperationError as ex: - print("HttpOperationError error {0}".format(ex.response.text)) +except HttpResponseError as ex: + print("HttpResponseError error {0}".format(ex)) except Exception as ex: print("Unexpected error {0}".format(ex)) except KeyboardInterrupt: diff --git a/samples/iothub_job_manager_twin_update_sample.py b/samples/iothub_job_manager_twin_update_sample.py index 3f53fc6..69787f5 100644 --- a/samples/iothub_job_manager_twin_update_sample.py +++ b/samples/iothub_job_manager_twin_update_sample.py @@ -8,8 +8,8 @@ import datetime import time import uuid -import msrest import pprint +from azure.core.exceptions import HttpResponseError from azure.iot.hub import IoTHubJobManager from azure.iot.hub.models import JobRequest, Twin, TwinProperties @@ -50,8 +50,8 @@ def print_job_response(title, response): break time.sleep(5) -except msrest.exceptions.HttpOperationError as ex: - print("HttpOperationError error {0}".format(ex.response.text)) +except HttpResponseError as ex: + print("HttpResponseError error {0}".format(ex)) except Exception as ex: print("Unexpected error {0}".format(ex)) except KeyboardInterrupt: diff --git a/samples/iothub_registry_manager_bulk_create_sample.py b/samples/iothub_registry_manager_bulk_create_sample.py index 154b700..1d99491 100644 --- a/samples/iothub_registry_manager_bulk_create_sample.py +++ b/samples/iothub_registry_manager_bulk_create_sample.py @@ -5,9 +5,9 @@ # -------------------------------------------------------------------------- import os -import msrest import uuid import base64 +from azure.core.exceptions import HttpResponseError from azure.iot.hub import IoTHubRegistryManager from azure.iot.hub.models import ExportImportDevice, AuthenticationMechanism, SymmetricKey @@ -83,8 +83,8 @@ def print_device_info(title, iothub_device): # Set registry manager object to `None` so all open files get closed iothub_registry_manager = None -except msrest.exceptions.HttpOperationError as ex: - print("HttpOperationError error {0}".format(ex.response.text)) +except HttpResponseError as ex: + print("HttpResponseError error {0}".format(ex)) except Exception as ex: print("Unexpected error {0}".format(ex)) except KeyboardInterrupt: diff --git a/samples/iothub_registry_manager_c2d_amqp_over_websocket_sample.py b/samples/iothub_registry_manager_c2d_amqp_over_websocket_sample.py index b5a110a..8a1aa34 100644 --- a/samples/iothub_registry_manager_c2d_amqp_over_websocket_sample.py +++ b/samples/iothub_registry_manager_c2d_amqp_over_websocket_sample.py @@ -5,7 +5,7 @@ # -------------------------------------------------------------------------- import os -import msrest +from azure.core.exceptions import HttpResponseError from azure.iot.hub import IoTHubRegistryManager, TransportType connection_str = os.getenv("IOTHUB_CONNECTION_STRING") @@ -35,8 +35,8 @@ # Set registry manager object to `None` so all open files get closed iothub_registry_manager = None -except msrest.exceptions.HttpOperationError as ex: - print("HttpOperationError error {0}".format(ex.response.text)) +except HttpResponseError as ex: + print("HttpResponseError error {0}".format(ex)) except Exception as ex: print("Unexpected error {0}".format(ex)) except KeyboardInterrupt: diff --git a/samples/iothub_registry_manager_c2d_sample.py b/samples/iothub_registry_manager_c2d_sample.py index da2c6b3..5d7a698 100644 --- a/samples/iothub_registry_manager_c2d_sample.py +++ b/samples/iothub_registry_manager_c2d_sample.py @@ -5,7 +5,7 @@ # -------------------------------------------------------------------------- import os -import msrest +from azure.core.exceptions import HttpResponseError from azure.iot.hub import IoTHubRegistryManager connection_str = os.getenv("IOTHUB_CONNECTION_STRING") @@ -35,8 +35,8 @@ # Set registry manager object to `None` so all open files get closed iothub_registry_manager = None -except msrest.exceptions.HttpOperationError as ex: - print("HttpOperationError error {0}".format(ex.response.text)) +except HttpResponseError as ex: + print("HttpResponseError error {0}".format(ex)) except Exception as ex: print("Unexpected error {0}".format(ex)) except KeyboardInterrupt: diff --git a/samples/iothub_registry_manager_edge_device_sample.py b/samples/iothub_registry_manager_edge_device_sample.py index a77eba7..c86f0fc 100644 --- a/samples/iothub_registry_manager_edge_device_sample.py +++ b/samples/iothub_registry_manager_edge_device_sample.py @@ -5,9 +5,9 @@ # -------------------------------------------------------------------------- import os -import msrest import uuid import base64 +from azure.core.exceptions import HttpResponseError from azure.iot.hub import IoTHubRegistryManager iothub_connection_str = os.getenv("IOTHUB_CONNECTION_STRING") @@ -71,8 +71,8 @@ def print_device_info(title, iothub_device): # Set registry manager object to `None` so all open files get closed iothub_registry_manager = None -except msrest.exceptions.HttpOperationError as ex: - print("HttpOperationError error {0}".format(ex.response.text)) +except HttpResponseError as ex: + print("HttpResponseError error {0}".format(ex)) except Exception as ex: print("Unexpected error {0}".format(ex)) except KeyboardInterrupt: diff --git a/samples/iothub_registry_manager_method_sample.py b/samples/iothub_registry_manager_method_sample.py index 0223153..d2e7601 100644 --- a/samples/iothub_registry_manager_method_sample.py +++ b/samples/iothub_registry_manager_method_sample.py @@ -5,7 +5,7 @@ # -------------------------------------------------------------------------- import os -import msrest +from azure.core.exceptions import HttpResponseError from azure.iot.hub import IoTHubRegistryManager from azure.iot.hub.models import CloudToDeviceMethod @@ -26,8 +26,8 @@ # Set registry manager object to `None` so all open files get closed iothub_registry_manager = None -except msrest.exceptions.HttpOperationError as ex: - print("HttpOperationError error {0}".format(ex.response.text)) +except HttpResponseError as ex: + print("HttpResponseError error {0}".format(ex)) except Exception as ex: print("Unexpected error {0}".format(ex)) except KeyboardInterrupt: diff --git a/samples/iothub_registry_manager_module_method_sample.py b/samples/iothub_registry_manager_module_method_sample.py index 42ec7d2..1f4b219 100644 --- a/samples/iothub_registry_manager_module_method_sample.py +++ b/samples/iothub_registry_manager_module_method_sample.py @@ -5,9 +5,9 @@ # -------------------------------------------------------------------------- import os -import msrest import uuid import base64 +from azure.core.exceptions import HttpResponseError from azure.iot.hub import IoTHubRegistryManager from azure.iot.hub.models import CloudToDeviceMethod @@ -39,8 +39,8 @@ # Set registry manager object to `None` so all open files get closed iothub_registry_manager = None -except msrest.exceptions.HttpOperationError as ex: - print("HttpOperationError error {0}".format(ex.response.text)) +except HttpResponseError as ex: + print("HttpResponseError error {0}".format(ex)) except Exception as ex: print("Unexpected error {0}".format(ex)) except KeyboardInterrupt: diff --git a/samples/iothub_registry_manager_module_sample.py b/samples/iothub_registry_manager_module_sample.py index ce62127..3efffa4 100644 --- a/samples/iothub_registry_manager_module_sample.py +++ b/samples/iothub_registry_manager_module_sample.py @@ -5,9 +5,9 @@ # -------------------------------------------------------------------------- import os -import msrest import uuid import base64 +from azure.core.exceptions import HttpResponseError from azure.iot.hub import IoTHubRegistryManager from azure.iot.hub.models import Twin, TwinProperties @@ -107,8 +107,8 @@ def print_module_info(title, iothub_module): # Set registry manager object to `None` so all open files get closed iothub_registry_manager = None -except msrest.exceptions.HttpOperationError as ex: - print("HttpOperationError error {0}".format(ex.response.text)) +except HttpResponseError as ex: + print("HttpResponseError error {0}".format(ex)) except Exception as ex: print("Unexpected error {0}".format(ex)) except KeyboardInterrupt: diff --git a/samples/iothub_registry_manager_query_sample.py b/samples/iothub_registry_manager_query_sample.py index 5f1f39c..cb9e86d 100644 --- a/samples/iothub_registry_manager_query_sample.py +++ b/samples/iothub_registry_manager_query_sample.py @@ -5,7 +5,7 @@ # -------------------------------------------------------------------------- import os -import msrest +from azure.core.exceptions import HttpResponseError from azure.iot.hub import IoTHubRegistryManager from azure.iot.hub.models import QuerySpecification @@ -77,8 +77,8 @@ def print_query_result(title, query_result): iothub_registry_manager = None -except msrest.exceptions.HttpOperationError as ex: - print("HttpOperationError error {0}".format(ex.response.text)) +except HttpResponseError as ex: + print("HttpResponseError error {0}".format(ex)) except Exception as ex: print("Unexpected error {0}".format(ex)) except KeyboardInterrupt: diff --git a/samples/iothub_registry_manager_sample.py b/samples/iothub_registry_manager_sample.py index 98c61d2..9629583 100644 --- a/samples/iothub_registry_manager_sample.py +++ b/samples/iothub_registry_manager_sample.py @@ -5,9 +5,9 @@ # -------------------------------------------------------------------------- import os -import msrest import uuid import base64 +from azure.core.exceptions import HttpResponseError from azure.iot.hub import IoTHubRegistryManager from azure.iot.hub.models import Twin, TwinProperties @@ -127,8 +127,8 @@ def print_device_info(title, iothub_device): # Set registry manager object to `None` so all open files get closed iothub_registry_manager = None -except msrest.exceptions.HttpOperationError as ex: - print("HttpOperationError error {0}".format(ex.response.text)) +except HttpResponseError as ex: + print("HttpResponseError error {0}".format(ex)) except Exception as ex: print("Unexpected error {0}".format(ex)) except KeyboardInterrupt: diff --git a/samples/iothub_registry_manager_statistics_sample.py b/samples/iothub_registry_manager_statistics_sample.py index 1377d18..863b4b6 100644 --- a/samples/iothub_registry_manager_statistics_sample.py +++ b/samples/iothub_registry_manager_statistics_sample.py @@ -5,7 +5,7 @@ # -------------------------------------------------------------------------- import os -import msrest +from azure.core.exceptions import HttpResponseError from azure.iot.hub import IoTHubRegistryManager connection_str = os.getenv("IOTHUB_CONNECTION_STRING") @@ -48,8 +48,8 @@ # Set registry manager object to `None` so all open files get closed iothub_registry_manager = None -except msrest.exceptions.HttpOperationError as ex: - print("HttpOperationError error {0}".format(ex.response.text)) +except HttpResponseError as ex: + print("HttpResponseError error {0}".format(ex)) except Exception as ex: print("Unexpected error {0}".format(ex)) except KeyboardInterrupt: diff --git a/samples/iothub_registry_manager_token_credential_sample.py b/samples/iothub_registry_manager_token_credential_sample.py index 4d2f3d4..d71c48b 100644 --- a/samples/iothub_registry_manager_token_credential_sample.py +++ b/samples/iothub_registry_manager_token_credential_sample.py @@ -5,9 +5,9 @@ # -------------------------------------------------------------------------- import os -import msrest import uuid import base64 +from azure.core.exceptions import HttpResponseError from azure.iot.hub import IoTHubRegistryManager from azure.identity import DefaultAzureCredential @@ -88,8 +88,8 @@ def print_device_info(title, iothub_device): # Set registry manager object to `None` so all open files get closed iothub_registry_manager = None -except msrest.exceptions.HttpOperationError as ex: - print("HttpOperationError error {0}".format(ex.response.text)) +except HttpResponseError as ex: + print("HttpResponseError error {0}".format(ex)) except Exception as ex: print("Unexpected error {0}".format(ex)) except KeyboardInterrupt: diff --git a/samples/iothub_registry_mgr_update_x509.py b/samples/iothub_registry_mgr_update_x509.py index 47b0ff3..bfe559a 100644 --- a/samples/iothub_registry_mgr_update_x509.py +++ b/samples/iothub_registry_mgr_update_x509.py @@ -5,7 +5,7 @@ # -------------------------------------------------------------------------- import os -import msrest +from azure.core.exceptions import HttpResponseError from azure.iot.hub import IoTHubRegistryManager from azure.iot.hub.models import Twin, TwinProperties @@ -121,8 +121,8 @@ def print_device_info(title, iothub_device): # Set registry manager object to `None` so all open files get closed iothub_registry_manager = None -except msrest.exceptions.HttpOperationError as ex: - print("HttpOperationError error {0}".format(ex.response.text)) +except HttpResponseError as ex: + print("HttpResponseError error {0}".format(ex)) except Exception as ex: print("Unexpected error {0}".format(ex)) except KeyboardInterrupt: diff --git a/samples/registry_manager_pnp_sample.py b/samples/registry_manager_pnp_sample.py index 68cd7b7..2be4803 100644 --- a/samples/registry_manager_pnp_sample.py +++ b/samples/registry_manager_pnp_sample.py @@ -5,7 +5,7 @@ # -------------------------------------------------------------------------- import os -import msrest +from azure.core.exceptions import HttpResponseError from azure.iot.hub import IoTHubRegistryManager from azure.iot.hub.models import Twin, TwinProperties from azure.iot.hub.models import CloudToDeviceMethod @@ -61,8 +61,8 @@ # Set registry manager object to `None` so all open files get closed iothub_registry_manager = None -except msrest.exceptions.HttpOperationError as ex: - print("HttpOperationError error {0}".format(ex.response.text)) +except HttpResponseError as ex: + print("HttpResponseError error {0}".format(ex)) except Exception as ex: print("Unexpected error {0}".format(ex)) except KeyboardInterrupt: diff --git a/samples/update_digital_twin_sample.py b/samples/update_digital_twin_sample.py index d5e6aa7..1671f6b 100644 --- a/samples/update_digital_twin_sample.py +++ b/samples/update_digital_twin_sample.py @@ -5,7 +5,7 @@ # -------------------------------------------------------------------------- import os -import msrest +from azure.core.exceptions import HttpResponseError from azure.iot.hub import DigitalTwinClient @@ -23,8 +23,8 @@ print("Patch has been successfully applied") -except msrest.exceptions.HttpOperationError as ex: - print("HttpOperationError error {0}".format(ex.response.text)) +except HttpResponseError as ex: + print("HttpResponseError error {0}".format(ex)) except Exception as exc: print("Unexpected error {0}".format(exc)) except KeyboardInterrupt: diff --git a/setup.py b/setup.py index 123f5d2..aa46aa0 100644 --- a/setup.py +++ b/setup.py @@ -71,8 +71,7 @@ "Programming Language :: Python :: 3.14", ], install_requires=[ - "msrest>=0.6.21,<1.0.0", - "azure-core>=1.10.0,<2.0.0", + "azure-core>=1.29.0,<2.0.0", # Runtime dependencies of the vendored pyamqp (see src/azure/iot/hub/_pyamqp/VENDOR.md). "certifi>=2017.4.17", "typing_extensions>=4.0.1", diff --git a/src/apiview-properties.json b/src/apiview-properties.json new file mode 100644 index 0000000..528e1c1 --- /dev/null +++ b/src/apiview-properties.json @@ -0,0 +1,137 @@ +{ + "CrossLanguagePackageId": null, + "CrossLanguageDefinitionId": { + "azure.iot.hub.protocol.models.AuthenticationMechanism": null, + "azure.iot.hub.protocol.models.BulkRegistryOperationResult": null, + "azure.iot.hub.protocol.models.CloudToDeviceMethod": null, + "azure.iot.hub.protocol.models.CloudToDeviceMethodResult": null, + "azure.iot.hub.protocol.models.Configuration": null, + "azure.iot.hub.protocol.models.ConfigurationContent": null, + "azure.iot.hub.protocol.models.ConfigurationMetrics": null, + "azure.iot.hub.protocol.models.ConfigurationQueriesTestInput": null, + "azure.iot.hub.protocol.models.ConfigurationQueriesTestResponse": null, + "azure.iot.hub.protocol.models.Device": null, + "azure.iot.hub.protocol.models.DeviceCapabilities": null, + "azure.iot.hub.protocol.models.DeviceJobStatistics": null, + "azure.iot.hub.protocol.models.DeviceRegistryOperationError": null, + "azure.iot.hub.protocol.models.DeviceRegistryOperationWarning": null, + "azure.iot.hub.protocol.models.ExportImportDevice": null, + "azure.iot.hub.protocol.models.JobProperties": null, + "azure.iot.hub.protocol.models.JobRequest": null, + "azure.iot.hub.protocol.models.JobResponse": null, + "azure.iot.hub.protocol.models.ManagedIdentity": null, + "azure.iot.hub.protocol.models.Module": null, + "azure.iot.hub.protocol.models.PropertyContainer": null, + "azure.iot.hub.protocol.models.PurgeMessageQueueResult": null, + "azure.iot.hub.protocol.models.QueryResult": null, + "azure.iot.hub.protocol.models.QuerySpecification": null, + "azure.iot.hub.protocol.models.RegistryStatistics": null, + "azure.iot.hub.protocol.models.ServiceStatistics": null, + "azure.iot.hub.protocol.models.SymmetricKey": null, + "azure.iot.hub.protocol.models.Twin": null, + "azure.iot.hub.protocol.models.TwinProperties": null, + "azure.iot.hub.protocol.models.X509Thumbprint": null, + "azure.iot.hub.protocol.models.DeviceConnectionState": null, + "azure.iot.hub.protocol.models.DeviceStatus": null, + "azure.iot.hub.protocol.models.AuthenticationMechanismType": null, + "azure.iot.hub.protocol.models.ExportImportDeviceImportMode": null, + "azure.iot.hub.protocol.models.ExportImportDeviceStatus": null, + "azure.iot.hub.protocol.models.DeviceRegistryOperationErrorCode": null, + "azure.iot.hub.protocol.models.DeviceRegistryOperationWarningCode": null, + "azure.iot.hub.protocol.models.TwinStatus": null, + "azure.iot.hub.protocol.models.TwinConnectionState": null, + "azure.iot.hub.protocol.models.TwinAuthenticationType": null, + "azure.iot.hub.protocol.models.JobPropertiesType": null, + "azure.iot.hub.protocol.models.JobPropertiesStatus": null, + "azure.iot.hub.protocol.models.JobPropertiesStorageAuthenticationType": null, + "azure.iot.hub.protocol.models.ModuleConnectionState": null, + "azure.iot.hub.protocol.models.JobResponseType": null, + "azure.iot.hub.protocol.models.JobResponseStatus": null, + "azure.iot.hub.protocol.models.JobRequestType": null, + "azure.iot.hub.protocol.models.QueryResultType": null, + "azure.iot.hub.protocol.operations.ConfigurationOperations.get": null, + "azure.iot.hub.protocol.aio.operations.ConfigurationOperations.get": null, + "azure.iot.hub.protocol.operations.ConfigurationOperations.create_or_update": null, + "azure.iot.hub.protocol.aio.operations.ConfigurationOperations.create_or_update": null, + "azure.iot.hub.protocol.operations.ConfigurationOperations.delete": null, + "azure.iot.hub.protocol.aio.operations.ConfigurationOperations.delete": null, + "azure.iot.hub.protocol.operations.ConfigurationOperations.get_configurations": null, + "azure.iot.hub.protocol.aio.operations.ConfigurationOperations.get_configurations": null, + "azure.iot.hub.protocol.operations.ConfigurationOperations.test_queries": null, + "azure.iot.hub.protocol.aio.operations.ConfigurationOperations.test_queries": null, + "azure.iot.hub.protocol.operations.ConfigurationOperations.apply_on_edge_device": null, + "azure.iot.hub.protocol.aio.operations.ConfigurationOperations.apply_on_edge_device": null, + "azure.iot.hub.protocol.operations.StatisticsOperations.get_device_statistics": null, + "azure.iot.hub.protocol.aio.operations.StatisticsOperations.get_device_statistics": null, + "azure.iot.hub.protocol.operations.StatisticsOperations.get_service_statistics": null, + "azure.iot.hub.protocol.aio.operations.StatisticsOperations.get_service_statistics": null, + "azure.iot.hub.protocol.operations.DevicesOperations.get_devices": null, + "azure.iot.hub.protocol.aio.operations.DevicesOperations.get_devices": null, + "azure.iot.hub.protocol.operations.DevicesOperations.get_identity": null, + "azure.iot.hub.protocol.aio.operations.DevicesOperations.get_identity": null, + "azure.iot.hub.protocol.operations.DevicesOperations.create_or_update_identity": null, + "azure.iot.hub.protocol.aio.operations.DevicesOperations.create_or_update_identity": null, + "azure.iot.hub.protocol.operations.DevicesOperations.delete_identity": null, + "azure.iot.hub.protocol.aio.operations.DevicesOperations.delete_identity": null, + "azure.iot.hub.protocol.operations.DevicesOperations.get_twin": null, + "azure.iot.hub.protocol.aio.operations.DevicesOperations.get_twin": null, + "azure.iot.hub.protocol.operations.DevicesOperations.replace_twin": null, + "azure.iot.hub.protocol.aio.operations.DevicesOperations.replace_twin": null, + "azure.iot.hub.protocol.operations.DevicesOperations.update_twin": null, + "azure.iot.hub.protocol.aio.operations.DevicesOperations.update_twin": null, + "azure.iot.hub.protocol.operations.DevicesOperations.invoke_method": null, + "azure.iot.hub.protocol.aio.operations.DevicesOperations.invoke_method": null, + "azure.iot.hub.protocol.operations.BulkRegistryOperations.update_registry": null, + "azure.iot.hub.protocol.aio.operations.BulkRegistryOperations.update_registry": null, + "azure.iot.hub.protocol.operations.QueryOperations.get_twins": null, + "azure.iot.hub.protocol.aio.operations.QueryOperations.get_twins": null, + "azure.iot.hub.protocol.operations.JobsOperations.create_import_export_job": null, + "azure.iot.hub.protocol.aio.operations.JobsOperations.create_import_export_job": null, + "azure.iot.hub.protocol.operations.JobsOperations.get_import_export_jobs": null, + "azure.iot.hub.protocol.aio.operations.JobsOperations.get_import_export_jobs": null, + "azure.iot.hub.protocol.operations.JobsOperations.get_import_export_job": null, + "azure.iot.hub.protocol.aio.operations.JobsOperations.get_import_export_job": null, + "azure.iot.hub.protocol.operations.JobsOperations.cancel_import_export_job": null, + "azure.iot.hub.protocol.aio.operations.JobsOperations.cancel_import_export_job": null, + "azure.iot.hub.protocol.operations.JobsOperations.get_scheduled_job": null, + "azure.iot.hub.protocol.aio.operations.JobsOperations.get_scheduled_job": null, + "azure.iot.hub.protocol.operations.JobsOperations.create_scheduled_job": null, + "azure.iot.hub.protocol.aio.operations.JobsOperations.create_scheduled_job": null, + "azure.iot.hub.protocol.operations.JobsOperations.cancel_scheduled_job": null, + "azure.iot.hub.protocol.aio.operations.JobsOperations.cancel_scheduled_job": null, + "azure.iot.hub.protocol.operations.JobsOperations.query_scheduled_jobs": null, + "azure.iot.hub.protocol.aio.operations.JobsOperations.query_scheduled_jobs": null, + "azure.iot.hub.protocol.operations.CloudToDeviceMessagesOperations.purge_cloud_to_device_message_queue": null, + "azure.iot.hub.protocol.aio.operations.CloudToDeviceMessagesOperations.purge_cloud_to_device_message_queue": null, + "azure.iot.hub.protocol.operations.CloudToDeviceMessagesOperations.receive_feedback_notification": null, + "azure.iot.hub.protocol.aio.operations.CloudToDeviceMessagesOperations.receive_feedback_notification": null, + "azure.iot.hub.protocol.operations.CloudToDeviceMessagesOperations.complete_feedback_notification": null, + "azure.iot.hub.protocol.aio.operations.CloudToDeviceMessagesOperations.complete_feedback_notification": null, + "azure.iot.hub.protocol.operations.CloudToDeviceMessagesOperations.abandon_feedback_notification": null, + "azure.iot.hub.protocol.aio.operations.CloudToDeviceMessagesOperations.abandon_feedback_notification": null, + "azure.iot.hub.protocol.operations.ModulesOperations.get_twin": null, + "azure.iot.hub.protocol.aio.operations.ModulesOperations.get_twin": null, + "azure.iot.hub.protocol.operations.ModulesOperations.replace_twin": null, + "azure.iot.hub.protocol.aio.operations.ModulesOperations.replace_twin": null, + "azure.iot.hub.protocol.operations.ModulesOperations.update_twin": null, + "azure.iot.hub.protocol.aio.operations.ModulesOperations.update_twin": null, + "azure.iot.hub.protocol.operations.ModulesOperations.get_modules_on_device": null, + "azure.iot.hub.protocol.aio.operations.ModulesOperations.get_modules_on_device": null, + "azure.iot.hub.protocol.operations.ModulesOperations.get_identity": null, + "azure.iot.hub.protocol.aio.operations.ModulesOperations.get_identity": null, + "azure.iot.hub.protocol.operations.ModulesOperations.create_or_update_identity": null, + "azure.iot.hub.protocol.aio.operations.ModulesOperations.create_or_update_identity": null, + "azure.iot.hub.protocol.operations.ModulesOperations.delete_identity": null, + "azure.iot.hub.protocol.aio.operations.ModulesOperations.delete_identity": null, + "azure.iot.hub.protocol.operations.ModulesOperations.invoke_method": null, + "azure.iot.hub.protocol.aio.operations.ModulesOperations.invoke_method": null, + "azure.iot.hub.protocol.operations.DigitalTwinOperations.get_digital_twin": null, + "azure.iot.hub.protocol.aio.operations.DigitalTwinOperations.get_digital_twin": null, + "azure.iot.hub.protocol.operations.DigitalTwinOperations.update_digital_twin": null, + "azure.iot.hub.protocol.aio.operations.DigitalTwinOperations.update_digital_twin": null, + "azure.iot.hub.protocol.operations.DigitalTwinOperations.invoke_root_level_command": null, + "azure.iot.hub.protocol.aio.operations.DigitalTwinOperations.invoke_root_level_command": null, + "azure.iot.hub.protocol.operations.DigitalTwinOperations.invoke_component_command": null, + "azure.iot.hub.protocol.aio.operations.DigitalTwinOperations.invoke_component_command": null + } +} \ No newline at end of file diff --git a/src/azure/iot/hub/auth.py b/src/azure/iot/hub/auth.py index 876cf20..9d657b5 100644 --- a/src/azure/iot/hub/auth.py +++ b/src/azure/iot/hub/auth.py @@ -4,30 +4,28 @@ # license information. # -------------------------------------------------------------------------- -"""Provides authentication classes for use with the msrest library -""" +"""Provides authentication classes for use with the generated azure-core client.""" + +from azure.core.credentials import TokenCredential +from azure.core.pipeline import PipelineRequest +from azure.core.pipeline.policies import BearerTokenCredentialPolicy, SansIOHTTPPolicy -from msrest.authentication import Authentication, BasicTokenAuthentication from .connection_string import ConnectionString from .connection_string import HOST_NAME, SHARED_ACCESS_KEY_NAME, SHARED_ACCESS_KEY from .sastoken import SasToken -from azure.core.pipeline.policies import BearerTokenCredentialPolicy -from azure.core.pipeline import PipelineRequest, PipelineContext -from azure.core.pipeline.transport import HttpRequest __all__ = ["ConnectionStringAuthentication", "AzureIdentityCredentialAdapter"] -class ConnectionStringAuthentication(ConnectionString, Authentication): - """ConnectionString class that can be used with msrest to provide SasToken authentication +class ConnectionStringAuthentication(ConnectionString, SansIOHTTPPolicy): + """ConnectionString-backed pipeline policy that injects a fresh SAS token as + the ``Authorization`` header on every outgoing request. :param connection_string: The connection string to generate SasToken with """ def __init__(self, connection_string): - super(ConnectionStringAuthentication, self).__init__( - connection_string - ) # ConnectionString __init__ + ConnectionString.__init__(self, connection_string) @classmethod def create_with_parsed_values(cls, host_name, shared_access_key_name, shared_access_key): @@ -46,51 +44,20 @@ def create_with_parsed_values(cls, host_name, shared_access_key_name, shared_acc ) return cls(connection_string) - def signed_session(self, session=None): - """Create requests session with any required auth headers applied. - - If a session object is provided, configure it directly. Otherwise, - create a new session and return it. - - :param session: The session to configure for authentication - :type session: requests.Session - :rtype: requests.Session - """ - session = super(ConnectionStringAuthentication, self).signed_session(session) - - # Authorization header + def on_request(self, request): + # type: (PipelineRequest) -> None sastoken = SasToken(self[HOST_NAME], self[SHARED_ACCESS_KEY], self[SHARED_ACCESS_KEY_NAME]) - session.headers[self.header] = str(sastoken) - return session + request.http_request.headers["Authorization"] = str(sastoken) -class AzureIdentityCredentialAdapter(BasicTokenAuthentication): - def __init__(self, credential, resource_id="https://iothubs.azure.net/.default", **kwargs): - """Adapt any azure-identity credential to work with SDK that needs azure.common.credentials or msrestazure. - Default resource is ARM (syntax of endpoint v2) - :param credential: Any azure-identity credential (DefaultAzureCredential by default) - :param str resource_id: The scope to use to get the token (default ARM) - """ - super(AzureIdentityCredentialAdapter, self).__init__(None) - self._policy = BearerTokenCredentialPolicy(credential, resource_id, **kwargs) +class AzureIdentityCredentialAdapter(BearerTokenCredentialPolicy): + """Pipeline policy that authenticates requests using any azure-identity + :class:`~azure.core.credentials.TokenCredential`. - def _make_request(self): - return PipelineRequest( - HttpRequest("AzureIdentityCredentialAdapter", "https://fakeurl"), PipelineContext(None) - ) - - def set_token(self): - """Ask the azure-core BearerTokenCredentialPolicy policy to get a token. - Using the policy gives us for free the caching system of azure-core. - We could make this code simpler by using private method, but by definition - I can't assure they will be there forever, so mocking a fake call to the policy - to extract the token, using 100% public API.""" - request = self._make_request() - self._policy.on_request(request) - # Read Authorization, and get the second part after Bearer - token = request.http_request.headers["Authorization"].split(" ", 1)[1] - self.token = {"access_token": token} + :param credential: Any azure-identity credential (for example DefaultAzureCredential). + :param str resource_id: The scope used to acquire tokens. Defaults to the IoT Hub audience. + """ - def signed_session(self, session=None): - self.set_token() - return super(AzureIdentityCredentialAdapter, self).signed_session(session) + def __init__(self, credential, resource_id="https://iothubs.azure.net/.default", **kwargs): + # type: (TokenCredential, str, ...) -> None + super().__init__(credential, resource_id, **kwargs) diff --git a/src/azure/iot/hub/digital_twin_client.py b/src/azure/iot/hub/digital_twin_client.py index 91b4f14..0ffa579 100644 --- a/src/azure/iot/hub/digital_twin_client.py +++ b/src/azure/iot/hub/digital_twin_client.py @@ -4,7 +4,7 @@ # license information. # -------------------------------------------------------------------------- from .auth import ConnectionStringAuthentication, AzureIdentityCredentialAdapter -from .protocol.iot_hub_gateway_service_ap_is import IotHubGatewayServiceAPIs as protocol_client +from .protocol import IotHubGatewayServiceAPIs as protocol_client class DigitalTwinClient(object): @@ -30,10 +30,14 @@ def __init__(self, connection_string=None, host=None, auth=None): """ if connection_string is not None: self.auth = ConnectionStringAuthentication(connection_string) - self.protocol = protocol_client(self.auth, "https://" + self.auth["HostName"]) + self.protocol = protocol_client( + "https://" + self.auth["HostName"], authentication_policy=self.auth + ) else: self.auth = auth - self.protocol = protocol_client(self.auth, "https://" + host) + self.protocol = protocol_client( + "https://" + host, authentication_policy=self.auth + ) @classmethod def from_connection_string(cls, connection_string): @@ -72,7 +76,7 @@ def get_digital_twin(self, digital_twin_id): """Retrieve the Digital Twin of a given device. :param str digital_twin__id: The digital twin Id of the given device. - :raises: `HttpOperationError` + :raises: `HttpResponseError` if the HTTP response status is not in [200]. :returns: The return object containing the Digital Twin. @@ -86,7 +90,7 @@ def update_digital_twin(self, digital_twin_id, digital_twin_patch, etag=None): :param list[object]: The json-patch object to update the Digital Twin. :param str etag: The etag (if_match) value to use for the update operation. - :raises: `HttpOperationError` + :raises: `HttpResponseError` if the HTTP response status is not in [200]. :returns: The return object containing the updated Digital Twin. @@ -115,7 +119,7 @@ def invoke_component_command( :param int response_timeout_in_seconds: Maximum interval of time, in seconds, that the digital twin command will wait for the response. The value must be within 5-300. :type response_timeout_in_seconds: int - :raises: `HttpOperationError` + :raises: `HttpResponseError` if the HTTP response status is not in [200]. :returns: The result of the invoked command. @@ -145,7 +149,7 @@ def invoke_command( :param int connect_timeout_in_seconds: Maximum interval of time, in seconds, that the digital twin command will wait for the answer. :param int response_timeout_in_seconds: Maximum interval of time, in seconds, that the digital twin command will wait for the response. The value must be within 5-300. - :raises: `HttpOperationError` + :raises: `HttpResponseError` if the HTTP response status is not in [200]. :returns: The result of the invoked command. diff --git a/src/azure/iot/hub/iothub_configuration_manager.py b/src/azure/iot/hub/iothub_configuration_manager.py index 72c1d6c..58edad7 100644 --- a/src/azure/iot/hub/iothub_configuration_manager.py +++ b/src/azure/iot/hub/iothub_configuration_manager.py @@ -5,7 +5,7 @@ # -------------------------------------------------------------------------- from .auth import ConnectionStringAuthentication, AzureIdentityCredentialAdapter -from .protocol.iot_hub_gateway_service_ap_is import IotHubGatewayServiceAPIs as protocol_client +from .protocol import IotHubGatewayServiceAPIs as protocol_client class IoTHubConfigurationManager(object): @@ -31,10 +31,14 @@ def __init__(self, connection_string=None, host=None, auth=None): """ if connection_string is not None: self.auth = ConnectionStringAuthentication(connection_string) - self.protocol = protocol_client(self.auth, "https://" + self.auth["HostName"]) + self.protocol = protocol_client( + "https://" + self.auth["HostName"], authentication_policy=self.auth + ) else: self.auth = auth - self.protocol = protocol_client(self.auth, "https://" + host) + self.protocol = protocol_client( + "https://" + host, authentication_policy=self.auth + ) @classmethod def from_connection_string(cls, connection_string): @@ -74,7 +78,7 @@ def get_configuration(self, configuration_id): :param str configuration_id: The id of the configuration. - :raises: `HttpOperationError` + :raises: `HttpResponseError` if the HTTP response status is not in [200]. :returns: The Configuration object. @@ -87,7 +91,7 @@ def create_configuration(self, configuration): :param str configuration_id: The id of the configuration. :param Configuration configuration: The configuration to create. - :raises: `HttpOperationError` + :raises: `HttpResponseError` if the HTTP response status is not in [200]. :returns: Configuration object containing the created configuration. @@ -102,7 +106,7 @@ def update_configuration(self, configuration, etag): :param Configuration configuration: The configuration contains the updated configuration. :param str etag: The etag (if_match) value to use for the update operation. - :raises: `HttpOperationError` + :raises: `HttpResponseError` if the HTTP response status is not in [200]. :returns: Configuration object containing the updated configuration. @@ -116,7 +120,7 @@ def delete_configuration(self, configuration_id, etag=None): :param Configuration configuration: The configuration to create. :param str etag: The etag (if_match) value to use for the delete operation. - :raises: `HttpOperationError` + :raises: `HttpResponseError` if the HTTP response status is not in [200]. :returns: Configuration object containing the updated configuration. @@ -132,7 +136,7 @@ def get_configurations(self, max_count=None): :param int max_count: The maximum number of configurations requested. - :raises: `HttpOperationError` + :raises: `HttpResponseError` if the HTTP response status is not in [200]. :returns: The list[Configuration] object. @@ -145,7 +149,7 @@ def test_configuration_queries(self, configuration_queries_test_input): :param ConfigurationQueriesTestInput configuration_queries_test_input: The queries test input. - :raises: `HttpOperationError` + :raises: `HttpResponseError` if the HTTP response status is not in [200]. :returns: The ConfigurationQueriesTestResponse object. @@ -158,7 +162,7 @@ def apply_configuration_on_edge_device(self, device_id, configuration_content): :param ConfigurationContent configuration_content: The name (Id) of the edge device. - :raises: `HttpOperationError` + :raises: `HttpResponseError` if the HTTP response status is not in [200]. :returns: An object. diff --git a/src/azure/iot/hub/iothub_http_runtime_manager.py b/src/azure/iot/hub/iothub_http_runtime_manager.py index cc35f7b..8243d0d 100644 --- a/src/azure/iot/hub/iothub_http_runtime_manager.py +++ b/src/azure/iot/hub/iothub_http_runtime_manager.py @@ -5,7 +5,7 @@ # -------------------------------------------------------------------------- from .auth import ConnectionStringAuthentication, AzureIdentityCredentialAdapter -from .protocol.iot_hub_gateway_service_ap_is import IotHubGatewayServiceAPIs as protocol_client +from .protocol import IotHubGatewayServiceAPIs as protocol_client class IoTHubHttpRuntimeManager(object): @@ -31,10 +31,14 @@ def __init__(self, connection_string=None, host=None, auth=None): """ if connection_string is not None: self.auth = ConnectionStringAuthentication(connection_string) - self.protocol = protocol_client(self.auth, "https://" + self.auth["HostName"]) + self.protocol = protocol_client( + "https://" + self.auth["HostName"], authentication_policy=self.auth + ) else: self.auth = auth - self.protocol = protocol_client(self.auth, "https://" + host) + self.protocol = protocol_client( + "https://" + host, authentication_policy=self.auth + ) @classmethod def from_connection_string(cls, connection_string): @@ -72,7 +76,7 @@ def from_token_credential(cls, url, token_credential): def receive_feedback_notification(self): """This method is used to retrieve feedback of a cloud-to-device message. - :raises: `HttpOperationError` + :raises: `HttpResponseError` if the HTTP response status is not in [200]. :returns: None. @@ -84,7 +88,7 @@ def complete_feedback_notification(self, lock_token): :param str lock_token: Lock token. - :raises: `HttpOperationError` + :raises: `HttpResponseError` if the HTTP response status is not in [200]. :returns: None. @@ -96,7 +100,7 @@ def abandon_feedback_notification(self, lock_token): :param str lock_token: Lock token. - :raises: `HttpOperationError` + :raises: `HttpResponseError` if the HTTP response status is not in [200]. :returns: None. diff --git a/src/azure/iot/hub/iothub_job_manager.py b/src/azure/iot/hub/iothub_job_manager.py index 8e12cff..71a2b78 100644 --- a/src/azure/iot/hub/iothub_job_manager.py +++ b/src/azure/iot/hub/iothub_job_manager.py @@ -5,7 +5,7 @@ # -------------------------------------------------------------------------- from .auth import ConnectionStringAuthentication, AzureIdentityCredentialAdapter -from .protocol.iot_hub_gateway_service_ap_is import IotHubGatewayServiceAPIs as protocol_client +from .protocol import IotHubGatewayServiceAPIs as protocol_client class IoTHubJobManager(object): @@ -31,10 +31,14 @@ def __init__(self, connection_string=None, host=None, auth=None): """ if connection_string is not None: self.auth = ConnectionStringAuthentication(connection_string) - self.protocol = protocol_client(self.auth, "https://" + self.auth["HostName"]) + self.protocol = protocol_client( + "https://" + self.auth["HostName"], authentication_policy=self.auth + ) else: self.auth = auth - self.protocol = protocol_client(self.auth, "https://" + host) + self.protocol = protocol_client( + "https://" + host, authentication_policy=self.auth + ) @classmethod def from_connection_string(cls, connection_string): @@ -75,7 +79,7 @@ def create_import_export_job(self, job_properties): :param job_properties: Specifies the job specification. :type job_properties: :class:`azure.iot.hub.models.JobProperties` - :raises: `HttpOperationError` + :raises: `HttpResponseError` if the HTTP response status is not in [200]. :returns: JobProperties object containing the created job. @@ -86,7 +90,7 @@ def create_import_export_job(self, job_properties): def get_import_export_jobs(self): """Retrieves the status of all import/export jobs on an IoTHub. - :raises: `HttpOperationError` + :raises: `HttpResponseError` if the HTTP response status is not in [200]. :returns: The list[job_properties] object. @@ -99,7 +103,7 @@ def get_import_export_job(self, job_id): :param str job_id: The ID of the job. - :raises: `HttpOperationError` + :raises: `HttpResponseError` if the HTTP response status is not in [200]. :returns: The JobProperties object containing the requested job. @@ -112,7 +116,7 @@ def cancel_import_export_job(self, job_id): :param str job_id: The ID of the job. - :raises: `HttpOperationError` + :raises: `HttpResponseError` if the HTTP response status is not in [200]. :returns: Object. @@ -126,7 +130,7 @@ def create_scheduled_job(self, job_id, job_request): :param job_request: Specifies the job. :type job_request: :class:`azure.iot.hub.models.JobRequest` - :raises: `HttpOperationError` + :raises: `HttpResponseError` if the HTTP response status is not in [200]. :returns: JobResponse object containing the created job. @@ -139,7 +143,7 @@ def get_scheduled_job(self, job_id): :param str job_id: The ID of the job. - :raises: `HttpOperationError` + :raises: `HttpResponseError` if the HTTP response status is not in [200]. :returns: The JobResponse object containing the requested details. @@ -152,7 +156,7 @@ def cancel_scheduled_job(self, job_id): :param str job_id: The ID of the job. - :raises: `HttpOperationError` + :raises: `HttpResponseError` if the HTTP response status is not in [200]. :returns: JobResponse object containing the cancelled job. @@ -166,7 +170,7 @@ def query_scheduled_jobs(self, job_type, job_status): :param str job_type: The type of the jobs. :param str job_status: The status of the jobs. - :raises: `HttpOperationError` + :raises: `HttpResponseError` if the HTTP response status is not in [200]. :returns: QueryResult object containing the jobs. diff --git a/src/azure/iot/hub/iothub_registry_manager.py b/src/azure/iot/hub/iothub_registry_manager.py index b674444..014a76a 100644 --- a/src/azure/iot/hub/iothub_registry_manager.py +++ b/src/azure/iot/hub/iothub_registry_manager.py @@ -5,7 +5,7 @@ # -------------------------------------------------------------------------- from . import iothub_amqp_client from .auth import ConnectionStringAuthentication, AzureIdentityCredentialAdapter -from .protocol.iot_hub_gateway_service_ap_is import IotHubGatewayServiceAPIs as protocol_client +from .protocol import IotHubGatewayServiceAPIs as protocol_client from .protocol.models import ( Device, Module, @@ -75,19 +75,22 @@ def __init__(self, connection_string=None, host=None, token_credential=None, tra """ self.amqp_svc_client = None if connection_string is not None: - conn_string_auth = ConnectionStringAuthentication(connection_string) + self.auth = ConnectionStringAuthentication(connection_string) self.protocol = protocol_client( - conn_string_auth, "https://" + conn_string_auth["HostName"] + "https://" + self.auth["HostName"], + authentication_policy=self.auth, ) self.amqp_svc_client = iothub_amqp_client.IoTHubAmqpClientSharedAccessKeyAuth( - conn_string_auth["HostName"], - conn_string_auth["SharedAccessKeyName"], - conn_string_auth["SharedAccessKey"], + self.auth["HostName"], + self.auth["SharedAccessKeyName"], + self.auth["SharedAccessKey"], transport_type, ) else: + self.auth = AzureIdentityCredentialAdapter(token_credential) self.protocol = protocol_client( - AzureIdentityCredentialAdapter(token_credential), "https://" + host + "https://" + host, + authentication_policy=self.auth, ) self.amqp_svc_client = iothub_amqp_client.IoTHubAmqpClientTokenAuth( host, token_credential, transport_type=transport_type @@ -164,7 +167,7 @@ def create_device_with_sas( For edge devices, the value to set a parent edge device can be retrieved from the parent edge device's device_scope property. For leaf devices, this could be set to the same value as device_scope or left for the service to copy over. - :raises: `HttpOperationError` + :raises: `HttpResponseError` if the HTTP response status is not in [200]. :returns: Device object containing the created device. @@ -214,7 +217,7 @@ def create_device_with_x509( For edge devices, the value to set a parent edge device can be retrieved from the parent edge device's device_scope property. For leaf devices, this could be set to the same value as device_scope or left for the service to copy over. - :raises: `HttpOperationError` + :raises: `HttpResponseError` if the HTTP response status is not in [200]. :returns: Device object containing the created device. @@ -264,7 +267,7 @@ def create_device_with_certificate_authority( For edge devices, the value to set a parent edge device can be retrieved from the parent edge device's device_scope property. For leaf devices, this could be set to the same value as device_scope or left for the service to copy over. - :raises: `HttpOperationError` + :raises: `HttpResponseError` if the HTTP response status is not in [200]. :returns: Device object containing the created device. @@ -314,7 +317,7 @@ def update_device_with_sas( For edge devices, the value to set a parent edge device can be retrieved from the parent edge device's device_scope property. For leaf devices, this could be set to the same value as device_scope or left for the service to copy over. - :raises: `HttpOperationError` + :raises: `HttpResponseError` if the HTTP response status is not in [200]. :returns: The updated Device object containing the created device. @@ -371,7 +374,7 @@ def update_device_with_x509( For edge devices, the value to set a parent edge device can be retrieved from the parent edge device's device_scope property. For leaf devices, this could be set to the same value as device_scope or left for the service to copy over. - :raises: `HttpOperationError` + :raises: `HttpResponseError` if the HTTP response status is not in [200]. :returns: The updated Device object containing the created device. @@ -428,7 +431,7 @@ def update_device_with_certificate_authority( For edge devices, the value to set a parent edge device can be retrieved from the parent edge device's device_scope property. For leaf devices, this could be set to the same value as device_scope or left for the service to copy over. - :raises: `HttpOperationError` + :raises: `HttpResponseError` if the HTTP response status is not in [200]. :returns: The updated Device object containing the created device. @@ -459,7 +462,7 @@ def get_device(self, device_id): :param str device_id: The name (Id) of the device. - :raises: `HttpOperationError` + :raises: `HttpResponseError` if the HTTP response status is not in [200]. :returns: The Device object containing the requested device. @@ -472,7 +475,7 @@ def delete_device(self, device_id, etag=None): :param str device_id: The name (Id) of the device. :param str etag: The etag (if_match) value to use for the delete operation. - :raises: `HttpOperationError` + :raises: `HttpResponseError` if the HTTP response status is not in [200]. :returns: None. @@ -491,7 +494,7 @@ def create_module_with_sas(self, device_id, module_id, managed_by, primary_key, :param str primary_key: Primary authentication key. :param str secondary_key: Secondary authentication key. - :raises: `HttpOperationError` + :raises: `HttpResponseError` if the HTTP response status is not in [200]. :returns: Module object containing the created module. @@ -519,7 +522,7 @@ def create_module_with_x509( :param str primary_thumbprint: Primary X509 thumbprint. :param str secondary_thumbprint: Secondary X509 thumbprint. - :raises: `HttpOperationError` + :raises: `HttpResponseError` if the HTTP response status is not in [200]. :returns: Module object containing the created module. @@ -547,7 +550,7 @@ def create_module_with_certificate_authority(self, device_id, module_id, managed :param str module_id: The name (Id) of the module. :param str managed_by: The name of the manager device (edge). - :raises: `HttpOperationError` + :raises: `HttpResponseError` if the HTTP response status is not in [200]. :returns: Module object containing the created module. @@ -574,7 +577,7 @@ def update_module_with_sas( :param str primary_key: Primary authentication key. :param str secondary_key: Secondary authentication key. - :raises: `HttpOperationError` + :raises: `HttpResponseError` if the HTTP response status is not in [200]. :returns: The updated Module object containing the created module. @@ -608,7 +611,7 @@ def update_module_with_x509( :param str primary_thumbprint: Primary X509 thumbprint. :param str secondary_thumbprint: Secondary X509 thumbprint. - :raises: `HttpOperationError` + :raises: `HttpResponseError` if the HTTP response status is not in [200]. :returns: The updated Module object containing the created module. @@ -642,7 +645,7 @@ def update_module_with_certificate_authority(self, device_id, module_id, managed :param str managed_by: The name of the manager device (edge). :param str etag: The etag (if_match) value to use for the update operation. - :raises: `HttpOperationError` + :raises: `HttpResponseError` if the HTTP response status is not in [200]. :returns: The updated Module object containing the created module. @@ -669,7 +672,7 @@ def get_module(self, device_id, module_id): :param str device_id: The name (Id) of the device. :param str module_id: The name (Id) of the module. - :raises: `HttpOperationError` + :raises: `HttpResponseError` if the HTTP response status is not in [200]. :returns: The Module object containing the requested module. @@ -681,7 +684,7 @@ def get_modules(self, device_id): :param str device_id: The name (Id) of the device. - :raises: `HttpOperationError` + :raises: `HttpResponseError` if the HTTP response status is not in [200]. :returns: The list[Module] containing all the modules on the device. @@ -695,7 +698,7 @@ def delete_module(self, device_id, module_id, etag=None): :param str module_id: The name (Id) of the module. :param str etag: The etag (if_match) value to use for the delete operation. - :raises: `HttpOperationError` + :raises: `HttpResponseError` if the HTTP response status is not in [200]. :returns: None. @@ -708,7 +711,7 @@ def delete_module(self, device_id, module_id, etag=None): def get_service_statistics(self): """Retrieves the IoTHub service statistics. - :raises: `HttpOperationError` + :raises: `HttpResponseError` if the HTTP response status is not in [200]. :returns: The ServiceStatistics object. @@ -718,7 +721,7 @@ def get_service_statistics(self): def get_device_registry_statistics(self): """Retrieves the IoTHub device registry statistics. - :raises: `HttpOperationError` + :raises: `HttpResponseError` if the HTTP response status is not in [200]. :returns: The RegistryStatistics object. @@ -738,7 +741,7 @@ def get_devices(self, max_number_of_devices=None): of device identities that are returned. Any value outside the range of 1-1000 is considered to be 1000 - :raises: `HttpOperationError` + :raises: `HttpResponseError` if the HTTP response status is not in [200]. :returns: List of device info. @@ -759,7 +762,7 @@ def bulk_create_or_update_devices(self, devices): :param list[ExportImportDevice] devices: The list of device objects to operate on. - :raises: `HttpOperationError` + :raises: `HttpResponseError` if the HTTP response status is not in [200]. :returns: The BulkRegistryOperationResult object. @@ -777,20 +780,26 @@ def query_iot_hub(self, query_specification, continuation_token=None, max_item_c :param str continuation_token: Continuation token for paging :param str max_item_count: Maximum number of requested device twins - :raises: `HttpOperationError` + :raises: `HttpResponseError` if the HTTP response status is not in [200]. :returns: The QueryResult object. """ - raw_response = self.protocol.query.get_twins( - query_specification, continuation_token, max_item_count, None, True + response_headers = {} + + def _capture_headers(pipeline_response, deserialized, headers): + response_headers.update(headers or {}) + return deserialized + + items = self.protocol.query.get_twins( + query_specification, continuation_token, max_item_count, cls=_capture_headers ) queryResult = QueryResult() - if raw_response.headers: - queryResult.type = raw_response.headers["x-ms-item-type"] - queryResult.continuation_token = raw_response.headers["x-ms-continuation"] - queryResult.items = raw_response.output + if response_headers: + queryResult.type = response_headers.get("x-ms-item-type") + queryResult.continuation_token = response_headers.get("x-ms-continuation") + queryResult.items = items return queryResult @@ -799,7 +808,7 @@ def get_twin(self, device_id): :param str device_id: The name (Id) of the device. - :raises: `HttpOperationError` + :raises: `HttpResponseError` if the HTTP response status is not in [200]. :returns: The Twin object. @@ -813,7 +822,7 @@ def replace_twin(self, device_id, device_twin, etag=None): :param Twin device_twin: The twin info of the device. :param str etag: The etag (if_match) value to use for the replace operation. - :raises: `HttpOperationError` + :raises: `HttpResponseError` if the HTTP response status is not in [200]. :returns: The Twin object. @@ -830,7 +839,7 @@ def update_twin(self, device_id, device_twin, etag=None): :param Twin device_twin: The twin info of the device. :param str etag: The etag (if_match) value to use for the update operation. - :raises: `HttpOperationError` + :raises: `HttpResponseError` if the HTTP response status is not in [200]. :returns: The Twin object. @@ -846,7 +855,7 @@ def get_module_twin(self, device_id, module_id): :param str device_id: The name (Id) of the device. :param str module_id: The name (Id) of the module. - :raises: `HttpOperationError` + :raises: `HttpResponseError` if the HTTP response status is not in [200]. :returns: The Twin object. @@ -861,7 +870,7 @@ def replace_module_twin(self, device_id, module_id, module_twin, etag=None): :param Twin module_twin: The twin info of the module. :param str etag: The etag (if_match) value to use for the replace operation. - :raises: `HttpOperationError` + :raises: `HttpResponseError` if the HTTP response status is not in [200]. :returns: The Twin object. @@ -881,7 +890,7 @@ def update_module_twin(self, device_id, module_id, module_twin, etag=None): :param Twin module_twin: The twin info of the module. :param str etag: The etag (if_match) value to use for the update operation. - :raises: `HttpOperationError` + :raises: `HttpResponseError` if the HTTP response status is not in [200]. :returns: The Twin object. @@ -899,7 +908,7 @@ def invoke_device_method(self, device_id, direct_method_request): :param str device_id: The name (Id) of the device. :param CloudToDeviceMethod direct_method_request: The method request. - :raises: `HttpOperationError` + :raises: `HttpResponseError` if the HTTP response status is not in [200]. :returns: The CloudToDeviceMethodResult object. @@ -916,7 +925,7 @@ def invoke_device_module_method(self, device_id, module_id, direct_method_reques :param str module_id: The name (Id) of the module. :param CloudToDeviceMethod direct_method_request: The method request. - :raises: `HttpOperationError` + :raises: `HttpResponseError` if the HTTP response status is not in [200]. :returns: The CloudToDeviceMethodResult object. diff --git a/src/azure/iot/hub/protocol/__init__.py b/src/azure/iot/hub/protocol/__init__.py index 7b51cac..2c0469c 100644 --- a/src/azure/iot/hub/protocol/__init__.py +++ b/src/azure/iot/hub/protocol/__init__.py @@ -1,13 +1,32 @@ # coding=utf-8 # -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is -# regenerated. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position -from .iot_hub_gateway_service_ap_is import IotHubGatewayServiceAPIs -from .version import VERSION +from typing import TYPE_CHECKING -__all__ = ["IotHubGatewayServiceAPIs"] +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._iot_hub_gateway_service_apis import IotHubGatewayServiceAPIs # type: ignore +from ._version import VERSION __version__ = VERSION + +try: + from ._patch import __all__ as _patch_all + from ._patch import * +except ImportError: + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "IotHubGatewayServiceAPIs", +] +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore + +_patch_sdk() diff --git a/src/azure/iot/hub/protocol/_configuration.py b/src/azure/iot/hub/protocol/_configuration.py new file mode 100644 index 0000000..724aa6f --- /dev/null +++ b/src/azure/iot/hub/protocol/_configuration.py @@ -0,0 +1,44 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from typing import Any + +from azure.core.pipeline import policies + +from ._version import VERSION + + +class IotHubGatewayServiceAPIsConfiguration: # pylint: disable=too-many-instance-attributes + """Configuration for IotHubGatewayServiceAPIs. + + Note that all parameters used to create this instance are saved as instance + attributes. + + :keyword api_version: Api Version. Default value is "2021-04-12". Note that overriding this + default value may result in unsupported behavior. + :paramtype api_version: str + """ + + def __init__(self, **kwargs: Any) -> None: + api_version: str = kwargs.pop("api_version", "2021-04-12") + + self.api_version = api_version + kwargs.setdefault("sdk_moniker", "iot-hub/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) + self._configure(**kwargs) + + def _configure(self, **kwargs: Any) -> None: + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or policies.HttpLoggingPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.RedirectPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.RetryPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") diff --git a/src/azure/iot/hub/protocol/_iot_hub_gateway_service_apis.py b/src/azure/iot/hub/protocol/_iot_hub_gateway_service_apis.py new file mode 100644 index 0000000..394b6c3 --- /dev/null +++ b/src/azure/iot/hub/protocol/_iot_hub_gateway_service_apis.py @@ -0,0 +1,133 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from copy import deepcopy +from typing import Any +from typing_extensions import Self + +from azure.core import PipelineClient +from azure.core.pipeline import policies +from azure.core.rest import HttpRequest, HttpResponse + +from . import models as _models +from ._configuration import IotHubGatewayServiceAPIsConfiguration +from ._utils.serialization import Deserializer, Serializer +from .operations import ( + BulkRegistryOperations, + CloudToDeviceMessagesOperations, + ConfigurationOperations, + DevicesOperations, + DigitalTwinOperations, + JobsOperations, + ModulesOperations, + QueryOperations, + StatisticsOperations, +) + + +class IotHubGatewayServiceAPIs: # pylint: disable=too-many-instance-attributes + """IotHubGatewayServiceAPIs. + + :ivar configuration: ConfigurationOperations operations + :vartype configuration: azure.iot.hub.protocol.operations.ConfigurationOperations + :ivar statistics: StatisticsOperations operations + :vartype statistics: azure.iot.hub.protocol.operations.StatisticsOperations + :ivar devices: DevicesOperations operations + :vartype devices: azure.iot.hub.protocol.operations.DevicesOperations + :ivar bulk_registry: BulkRegistryOperations operations + :vartype bulk_registry: azure.iot.hub.protocol.operations.BulkRegistryOperations + :ivar query: QueryOperations operations + :vartype query: azure.iot.hub.protocol.operations.QueryOperations + :ivar jobs: JobsOperations operations + :vartype jobs: azure.iot.hub.protocol.operations.JobsOperations + :ivar cloud_to_device_messages: CloudToDeviceMessagesOperations operations + :vartype cloud_to_device_messages: + azure.iot.hub.protocol.operations.CloudToDeviceMessagesOperations + :ivar modules: ModulesOperations operations + :vartype modules: azure.iot.hub.protocol.operations.ModulesOperations + :ivar digital_twin: DigitalTwinOperations operations + :vartype digital_twin: azure.iot.hub.protocol.operations.DigitalTwinOperations + :param base_url: Service URL. Default value is + "https://fully-qualified-iothubname.azure-devices.net". + :type base_url: str + :keyword api_version: Api Version. Default value is "2021-04-12". Note that overriding this + default value may result in unsupported behavior. + :paramtype api_version: str + """ + + def __init__( # pylint: disable=missing-client-constructor-parameter-credential + self, base_url: str = "https://fully-qualified-iothubname.azure-devices.net", **kwargs: Any + ) -> None: + self._config = IotHubGatewayServiceAPIsConfiguration(**kwargs) + + _policies = kwargs.pop("policies", None) + if _policies is None: + _policies = [ + policies.RequestIdPolicy(**kwargs), + self._config.headers_policy, + self._config.user_agent_policy, + self._config.proxy_policy, + policies.ContentDecodePolicy(**kwargs), + self._config.redirect_policy, + self._config.retry_policy, + self._config.authentication_policy, + self._config.custom_hook_policy, + self._config.logging_policy, + policies.DistributedTracingPolicy(**kwargs), + policies.SensitiveHeaderCleanupPolicy(**kwargs) if self._config.redirect_policy else None, + self._config.http_logging_policy, + ] + self._client: PipelineClient = PipelineClient(base_url=base_url, policies=_policies, **kwargs) + + client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)} + self._serialize = Serializer(client_models) + self._deserialize = Deserializer(client_models) + self._serialize.client_side_validation = False + self.configuration = ConfigurationOperations(self._client, self._config, self._serialize, self._deserialize) + self.statistics = StatisticsOperations(self._client, self._config, self._serialize, self._deserialize) + self.devices = DevicesOperations(self._client, self._config, self._serialize, self._deserialize) + self.bulk_registry = BulkRegistryOperations(self._client, self._config, self._serialize, self._deserialize) + self.query = QueryOperations(self._client, self._config, self._serialize, self._deserialize) + self.jobs = JobsOperations(self._client, self._config, self._serialize, self._deserialize) + self.cloud_to_device_messages = CloudToDeviceMessagesOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.modules = ModulesOperations(self._client, self._config, self._serialize, self._deserialize) + self.digital_twin = DigitalTwinOperations(self._client, self._config, self._serialize, self._deserialize) + + def _send_request(self, request: HttpRequest, *, stream: bool = False, **kwargs: Any) -> HttpResponse: + """Runs the network request through the client's chained policies. + + >>> from azure.core.rest import HttpRequest + >>> request = HttpRequest("GET", "https://www.example.org/") + + >>> response = client._send_request(request) + + + For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request + + :param request: The network request you want to make. Required. + :type request: ~azure.core.rest.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to False. + :return: The response of your network call. Does not do error handling on your response. + :rtype: ~azure.core.rest.HttpResponse + """ + + request_copy = deepcopy(request) + request_copy.url = self._client.format_url(request_copy.url) + return self._client.send_request(request_copy, stream=stream, **kwargs) # type: ignore + + def close(self) -> None: + self._client.close() + + def __enter__(self) -> Self: + self._client.__enter__() + return self + + def __exit__(self, *exc_details: Any) -> None: + self._client.__exit__(*exc_details) diff --git a/src/azure/iot/hub/protocol/_patch.py b/src/azure/iot/hub/protocol/_patch.py new file mode 100644 index 0000000..87676c6 --- /dev/null +++ b/src/azure/iot/hub/protocol/_patch.py @@ -0,0 +1,21 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------- +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" + + +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/src/azure/iot/hub/protocol/version.py b/src/azure/iot/hub/protocol/_utils/__init__.py similarity index 61% rename from src/azure/iot/hub/protocol/version.py rename to src/azure/iot/hub/protocol/_utils/__init__.py index e645847..0af9b28 100644 --- a/src/azure/iot/hub/protocol/version.py +++ b/src/azure/iot/hub/protocol/_utils/__init__.py @@ -1,8 +1,6 @@ -# coding=utf-8 # -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is -# regenerated. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- - -VERSION = "2021-04-12" diff --git a/src/azure/iot/hub/protocol/_utils/serialization.py b/src/azure/iot/hub/protocol/_utils/serialization.py new file mode 100644 index 0000000..6da830e --- /dev/null +++ b/src/azure/iot/hub/protocol/_utils/serialization.py @@ -0,0 +1,2041 @@ +# pylint: disable=line-too-long,useless-suppression,too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +# pyright: reportUnnecessaryTypeIgnoreComment=false + +from base64 import b64decode, b64encode +import calendar +import datetime +import decimal +import email +from enum import Enum +import json +import logging +import re +import sys +import codecs +from typing import ( + Any, + cast, + Optional, + Union, + AnyStr, + IO, + Mapping, + Callable, + MutableMapping, +) + +try: + from urllib import quote # type: ignore +except ImportError: + from urllib.parse import quote +import xml.etree.ElementTree as ET + +import isodate # type: ignore +from typing_extensions import Self + +from azure.core.exceptions import DeserializationError, SerializationError +from azure.core.serialization import NULL as CoreNull + +_BOM = codecs.BOM_UTF8.decode(encoding="utf-8") + +JSON = MutableMapping[str, Any] + + +class RawDeserializer: + + # Accept "text" because we're open minded people... + JSON_REGEXP = re.compile(r"^(application|text)/([a-z+.]+\+)?json$") + + # Name used in context + CONTEXT_NAME = "deserialized_data" + + @classmethod + def deserialize_from_text(cls, data: Optional[Union[AnyStr, IO]], content_type: Optional[str] = None) -> Any: + """Decode data according to content-type. + + Accept a stream of data as well, but will be load at once in memory for now. + + If no content-type, will return the string version (not bytes, not stream) + + :param data: Input, could be bytes or stream (will be decoded with UTF8) or text + :type data: str or bytes or IO + :param str content_type: The content type. + :return: The deserialized data. + :rtype: object + """ + if hasattr(data, "read"): + # Assume a stream + data = cast(IO, data).read() + + if isinstance(data, bytes): + data_as_str = data.decode(encoding="utf-8-sig") + else: + # Explain to mypy the correct type. + data_as_str = cast(str, data) + + # Remove Byte Order Mark if present in string + data_as_str = data_as_str.lstrip(_BOM) + + if content_type is None: + return data + + if cls.JSON_REGEXP.match(content_type): + try: + return json.loads(data_as_str) + except ValueError as err: + raise DeserializationError("JSON is invalid: {}".format(err), err) from err + elif "xml" in (content_type or []): + try: + + try: + if isinstance(data, unicode): # type: ignore + # If I'm Python 2.7 and unicode XML will scream if I try a "fromstring" on unicode string + data_as_str = data_as_str.encode(encoding="utf-8") # type: ignore + except NameError: + pass + + return ET.fromstring(data_as_str) # nosec + except ET.ParseError as err: + # It might be because the server has an issue, and returned JSON with + # content-type XML.... + # So let's try a JSON load, and if it's still broken + # let's flow the initial exception + def _json_attemp(data): + try: + return True, json.loads(data) + except ValueError: + return False, None # Don't care about this one + + success, json_result = _json_attemp(data) + if success: + return json_result + # If i'm here, it's not JSON, it's not XML, let's scream + # and raise the last context in this block (the XML exception) + # The function hack is because Py2.7 messes up with exception + # context otherwise. + _LOGGER.critical("Wasn't XML not JSON, failing") + raise DeserializationError("XML is invalid") from err + elif content_type.startswith("text/"): + return data_as_str + raise DeserializationError("Cannot deserialize content-type: {}".format(content_type)) + + @classmethod + def deserialize_from_http_generics(cls, body_bytes: Optional[Union[AnyStr, IO]], headers: Mapping) -> Any: + """Deserialize from HTTP response. + + Use bytes and headers to NOT use any requests/aiohttp or whatever + specific implementation. + Headers will tested for "content-type" + + :param bytes body_bytes: The body of the response. + :param dict headers: The headers of the response. + :returns: The deserialized data. + :rtype: object + """ + # Try to use content-type from headers if available + content_type = None + if "content-type" in headers: + content_type = headers["content-type"].split(";")[0].strip().lower() + # Ouch, this server did not declare what it sent... + # Let's guess it's JSON... + # Also, since Autorest was considering that an empty body was a valid JSON, + # need that test as well.... + else: + content_type = "application/json" + + if body_bytes: + return cls.deserialize_from_text(body_bytes, content_type) + return None + + +_LOGGER = logging.getLogger(__name__) + +try: + _long_type = long # type: ignore +except NameError: + _long_type = int + +TZ_UTC = datetime.timezone.utc + +_FLATTEN = re.compile(r"(? None: + self.additional_properties: Optional[dict[str, Any]] = {} + for k in kwargs: # pylint: disable=consider-using-dict-items + if k not in self._attribute_map: + _LOGGER.warning("%s is not a known attribute of class %s and will be ignored", k, self.__class__) + elif k in self._validation and self._validation[k].get("readonly", False): + _LOGGER.warning("Readonly attribute %s will be ignored in class %s", k, self.__class__) + else: + setattr(self, k, kwargs[k]) + + def __eq__(self, other: Any) -> bool: + """Compare objects by comparing all attributes. + + :param object other: The object to compare + :returns: True if objects are equal + :rtype: bool + """ + if isinstance(other, self.__class__): + return self.__dict__ == other.__dict__ + return False + + def __ne__(self, other: Any) -> bool: + """Compare objects by comparing all attributes. + + :param object other: The object to compare + :returns: True if objects are not equal + :rtype: bool + """ + return not self.__eq__(other) + + def __str__(self) -> str: + return str(self.__dict__) + + @classmethod + def enable_additional_properties_sending(cls) -> None: + cls._attribute_map["additional_properties"] = {"key": "", "type": "{object}"} + + @classmethod + def is_xml_model(cls) -> bool: + try: + cls._xml_map # type: ignore + except AttributeError: + return False + return True + + @classmethod + def _create_xml_node(cls): + """Create XML node. + + :returns: The XML node + :rtype: xml.etree.ElementTree.Element + """ + try: + xml_map = cls._xml_map # type: ignore + except AttributeError: + xml_map = {} + + return _create_xml_node(xml_map.get("name", cls.__name__), xml_map.get("prefix", None), xml_map.get("ns", None)) + + def serialize(self, keep_readonly: bool = False, **kwargs: Any) -> JSON: + """Return the JSON that would be sent to server from this model. + + This is an alias to `as_dict(full_restapi_key_transformer, keep_readonly=False)`. + + If you want XML serialization, you can pass the kwargs is_xml=True. + + :param bool keep_readonly: If you want to serialize the readonly attributes + :returns: A dict JSON compatible object + :rtype: dict + """ + serializer = Serializer(self._infer_class_models()) + return serializer._serialize( # type: ignore # pylint: disable=protected-access + self, keep_readonly=keep_readonly, **kwargs + ) + + def as_dict( + self, + keep_readonly: bool = True, + key_transformer: Callable[[str, dict[str, Any], Any], Any] = attribute_transformer, + **kwargs: Any + ) -> JSON: + """Return a dict that can be serialized using json.dump. + + Advanced usage might optionally use a callback as parameter: + + .. code::python + + def my_key_transformer(key, attr_desc, value): + return key + + Key is the attribute name used in Python. Attr_desc + is a dict of metadata. Currently contains 'type' with the + msrest type and 'key' with the RestAPI encoded key. + Value is the current value in this object. + + The string returned will be used to serialize the key. + If the return type is a list, this is considered hierarchical + result dict. + + See the three examples in this file: + + - attribute_transformer + - full_restapi_key_transformer + - last_restapi_key_transformer + + If you want XML serialization, you can pass the kwargs is_xml=True. + + :param bool keep_readonly: If you want to serialize the readonly attributes + :param function key_transformer: A key transformer function. + :returns: A dict JSON compatible object + :rtype: dict + """ + serializer = Serializer(self._infer_class_models()) + return serializer._serialize( # type: ignore # pylint: disable=protected-access + self, key_transformer=key_transformer, keep_readonly=keep_readonly, **kwargs + ) + + @classmethod + def _infer_class_models(cls): + try: + str_models = cls.__module__.rsplit(".", 1)[0] + models = sys.modules[str_models] + client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} + if cls.__name__ not in client_models: + raise ValueError("Not Autorest generated code") + except Exception: # pylint: disable=broad-exception-caught + # Assume it's not Autorest generated (tests?). Add ourselves as dependencies. + client_models = {cls.__name__: cls} + return client_models + + @classmethod + def deserialize(cls, data: Any, content_type: Optional[str] = None) -> Self: + """Parse a str using the RestAPI syntax and return a model. + + :param str data: A str using RestAPI structure. JSON by default. + :param str content_type: JSON by default, set application/xml if XML. + :returns: An instance of this model + :raises DeserializationError: if something went wrong + :rtype: Self + """ + deserializer = Deserializer(cls._infer_class_models()) + return deserializer(cls.__name__, data, content_type=content_type) # type: ignore + + @classmethod + def from_dict( + cls, + data: Any, + key_extractors: Optional[Callable[[str, dict[str, Any], Any], Any]] = None, + content_type: Optional[str] = None, + ) -> Self: + """Parse a dict using given key extractor return a model. + + By default consider key + extractors (rest_key_case_insensitive_extractor, attribute_key_case_insensitive_extractor + and last_rest_key_case_insensitive_extractor) + + :param dict data: A dict using RestAPI structure + :param function key_extractors: A key extractor function. + :param str content_type: JSON by default, set application/xml if XML. + :returns: An instance of this model + :raises DeserializationError: if something went wrong + :rtype: Self + """ + deserializer = Deserializer(cls._infer_class_models()) + deserializer.key_extractors = ( # type: ignore + [ # type: ignore + attribute_key_case_insensitive_extractor, + rest_key_case_insensitive_extractor, + last_rest_key_case_insensitive_extractor, + ] + if key_extractors is None + else key_extractors + ) + return deserializer(cls.__name__, data, content_type=content_type) # type: ignore + + @classmethod + def _flatten_subtype(cls, key, objects): + if "_subtype_map" not in cls.__dict__: + return {} + result = dict(cls._subtype_map[key]) + for valuetype in cls._subtype_map[key].values(): + result |= objects[valuetype]._flatten_subtype(key, objects) # pylint: disable=protected-access + return result + + @classmethod + def _classify(cls, response, objects): + """Check the class _subtype_map for any child classes. + We want to ignore any inherited _subtype_maps. + + :param dict response: The initial data + :param dict objects: The class objects + :returns: The class to be used + :rtype: class + """ + for subtype_key in cls.__dict__.get("_subtype_map", {}).keys(): + subtype_value = None + + if not isinstance(response, ET.Element): + rest_api_response_key = cls._get_rest_key_parts(subtype_key)[-1] + subtype_value = response.get(rest_api_response_key, None) or response.get(subtype_key, None) + else: + subtype_value = xml_key_extractor(subtype_key, cls._attribute_map[subtype_key], response) + if subtype_value: + # Try to match base class. Can be class name only + # (bug to fix in Autorest to support x-ms-discriminator-name) + if cls.__name__ == subtype_value: + return cls + flatten_mapping_type = cls._flatten_subtype(subtype_key, objects) + try: + return objects[flatten_mapping_type[subtype_value]] # type: ignore + except KeyError: + _LOGGER.warning( + "Subtype value %s has no mapping, use base class %s.", + subtype_value, + cls.__name__, + ) + break + else: + _LOGGER.warning("Discriminator %s is absent or null, use base class %s.", subtype_key, cls.__name__) + break + return cls + + @classmethod + def _get_rest_key_parts(cls, attr_key): + """Get the RestAPI key of this attr, split it and decode part + :param str attr_key: Attribute key must be in attribute_map. + :returns: A list of RestAPI part + :rtype: list + """ + rest_split_key = _FLATTEN.split(cls._attribute_map[attr_key]["key"]) + return [_decode_attribute_map_key(key_part) for key_part in rest_split_key] + + +def _decode_attribute_map_key(key): + """This decode a key in an _attribute_map to the actual key we want to look at + inside the received data. + + :param str key: A key string from the generated code + :returns: The decoded key + :rtype: str + """ + return key.replace("\\.", ".") + + +class Serializer: # pylint: disable=too-many-public-methods + """Request object model serializer.""" + + basic_types = {str: "str", int: "int", bool: "bool", float: "float"} + + _xml_basic_types_serializers = {"bool": lambda x: str(x).lower()} + days = {0: "Mon", 1: "Tue", 2: "Wed", 3: "Thu", 4: "Fri", 5: "Sat", 6: "Sun"} + months = { + 1: "Jan", + 2: "Feb", + 3: "Mar", + 4: "Apr", + 5: "May", + 6: "Jun", + 7: "Jul", + 8: "Aug", + 9: "Sep", + 10: "Oct", + 11: "Nov", + 12: "Dec", + } + validation = { + "min_length": lambda x, y: len(x) < y, + "max_length": lambda x, y: len(x) > y, + "minimum": lambda x, y: x < y, + "maximum": lambda x, y: x > y, + "minimum_ex": lambda x, y: x <= y, + "maximum_ex": lambda x, y: x >= y, + "min_items": lambda x, y: len(x) < y, + "max_items": lambda x, y: len(x) > y, + "pattern": lambda x, y: not re.match(y, x, re.UNICODE), + "unique": lambda x, y: len(x) != len(set(x)), + "multiple": lambda x, y: x % y != 0, + } + + def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: + self.serialize_type = { + "iso-8601": Serializer.serialize_iso, + "rfc-1123": Serializer.serialize_rfc, + "unix-time": Serializer.serialize_unix, + "duration": Serializer.serialize_duration, + "date": Serializer.serialize_date, + "time": Serializer.serialize_time, + "decimal": Serializer.serialize_decimal, + "long": Serializer.serialize_long, + "bytearray": Serializer.serialize_bytearray, + "base64": Serializer.serialize_base64, + "object": self.serialize_object, + "[]": self.serialize_iter, + "{}": self.serialize_dict, + } + self.dependencies: dict[str, type] = dict(classes) if classes else {} + self.key_transformer = full_restapi_key_transformer + self.client_side_validation = True + + def _serialize( # pylint: disable=too-many-nested-blocks, too-many-branches, too-many-statements, too-many-locals + self, target_obj, data_type=None, **kwargs + ): + """Serialize data into a string according to type. + + :param object target_obj: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: str, dict + :raises SerializationError: if serialization fails. + :returns: The serialized data. + """ + key_transformer = kwargs.get("key_transformer", self.key_transformer) + keep_readonly = kwargs.get("keep_readonly", False) + if target_obj is None: + return None + + attr_name = None + class_name = target_obj.__class__.__name__ + + if data_type: + return self.serialize_data(target_obj, data_type, **kwargs) + + if not hasattr(target_obj, "_attribute_map"): + data_type = type(target_obj).__name__ + if data_type in self.basic_types.values(): + return self.serialize_data(target_obj, data_type, **kwargs) + + # Force "is_xml" kwargs if we detect a XML model + try: + is_xml_model_serialization = kwargs["is_xml"] + except KeyError: + is_xml_model_serialization = kwargs.setdefault("is_xml", target_obj.is_xml_model()) + + serialized = {} + if is_xml_model_serialization: + serialized = target_obj._create_xml_node() # pylint: disable=protected-access + try: + attributes = target_obj._attribute_map # pylint: disable=protected-access + for attr, attr_desc in attributes.items(): + attr_name = attr + if not keep_readonly and target_obj._validation.get( # pylint: disable=protected-access + attr_name, {} + ).get("readonly", False): + continue + + if attr_name == "additional_properties" and attr_desc["key"] == "": + if target_obj.additional_properties is not None: + serialized |= target_obj.additional_properties + continue + try: + + orig_attr = getattr(target_obj, attr) + if is_xml_model_serialization: + pass # Don't provide "transformer" for XML for now. Keep "orig_attr" + else: # JSON + keys, orig_attr = key_transformer(attr, attr_desc.copy(), orig_attr) + keys = keys if isinstance(keys, list) else [keys] + + kwargs["serialization_ctxt"] = attr_desc + new_attr = self.serialize_data(orig_attr, attr_desc["type"], **kwargs) + + if is_xml_model_serialization: + xml_desc = attr_desc.get("xml", {}) + xml_name = xml_desc.get("name", attr_desc["key"]) + xml_prefix = xml_desc.get("prefix", None) + xml_ns = xml_desc.get("ns", None) + if xml_desc.get("attr", False): + if xml_ns: + ET.register_namespace(xml_prefix, xml_ns) + xml_name = "{{{}}}{}".format(xml_ns, xml_name) + serialized.set(xml_name, new_attr) # type: ignore + continue + if xml_desc.get("text", False): + serialized.text = new_attr # type: ignore + continue + if isinstance(new_attr, list): + serialized.extend(new_attr) # type: ignore + elif isinstance(new_attr, ET.Element): + # If the down XML has no XML/Name, + # we MUST replace the tag with the local tag. But keeping the namespaces. + if "name" not in getattr(orig_attr, "_xml_map", {}): + splitted_tag = new_attr.tag.split("}") + if len(splitted_tag) == 2: # Namespace + new_attr.tag = "}".join([splitted_tag[0], xml_name]) + else: + new_attr.tag = xml_name + serialized.append(new_attr) # type: ignore + else: # That's a basic type + # Integrate namespace if necessary + local_node = _create_xml_node(xml_name, xml_prefix, xml_ns) + local_node.text = str(new_attr) + serialized.append(local_node) # type: ignore + else: # JSON + for k in reversed(keys): # type: ignore + new_attr = {k: new_attr} + + _new_attr = new_attr + _serialized = serialized + for k in keys: # type: ignore + if k not in _serialized: + _serialized.update(_new_attr) # type: ignore + _new_attr = _new_attr[k] # type: ignore + _serialized = _serialized[k] + except ValueError as err: + if isinstance(err, SerializationError): + raise + + except (AttributeError, KeyError, TypeError) as err: + msg = "Attribute {} in object {} cannot be serialized.\n{}".format(attr_name, class_name, str(target_obj)) + raise SerializationError(msg) from err + return serialized + + def body(self, data, data_type, **kwargs): + """Serialize data intended for a request body. + + :param object data: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: dict + :raises SerializationError: if serialization fails. + :raises ValueError: if data is None + :returns: The serialized request body + """ + + # Just in case this is a dict + internal_data_type_str = data_type.strip("[]{}") + internal_data_type = self.dependencies.get(internal_data_type_str, None) + try: + is_xml_model_serialization = kwargs["is_xml"] + except KeyError: + if internal_data_type and issubclass(internal_data_type, Model): + is_xml_model_serialization = kwargs.setdefault("is_xml", internal_data_type.is_xml_model()) + else: + is_xml_model_serialization = False + if internal_data_type and not isinstance(internal_data_type, Enum): + try: + deserializer = Deserializer(self.dependencies) + # Since it's on serialization, it's almost sure that format is not JSON REST + # We're not able to deal with additional properties for now. + deserializer.additional_properties_detection = False + if is_xml_model_serialization: + deserializer.key_extractors = [ # type: ignore + attribute_key_case_insensitive_extractor, + ] + else: + deserializer.key_extractors = [ + rest_key_case_insensitive_extractor, + attribute_key_case_insensitive_extractor, + last_rest_key_case_insensitive_extractor, + ] + data = deserializer._deserialize(data_type, data) # pylint: disable=protected-access + except DeserializationError as err: + raise SerializationError("Unable to build a model: " + str(err)) from err + + return self._serialize(data, data_type, **kwargs) + + def url(self, name, data, data_type, **kwargs): + """Serialize data intended for a URL path. + + :param str name: The name of the URL path parameter. + :param object data: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: str + :returns: The serialized URL path + :raises TypeError: if serialization fails. + :raises ValueError: if data is None + """ + try: + output = self.serialize_data(data, data_type, **kwargs) + if data_type == "bool": + output = json.dumps(output) + + if kwargs.get("skip_quote") is True: + output = str(output) + output = output.replace("{", quote("{")).replace("}", quote("}")) + else: + output = quote(str(output), safe="") + except SerializationError as exc: + raise TypeError("{} must be type {}.".format(name, data_type)) from exc + return output + + def query(self, name, data, data_type, **kwargs): + """Serialize data intended for a URL query. + + :param str name: The name of the query parameter. + :param object data: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: str, list + :raises TypeError: if serialization fails. + :raises ValueError: if data is None + :returns: The serialized query parameter + """ + try: + # Treat the list aside, since we don't want to encode the div separator + if data_type.startswith("["): + internal_data_type = data_type[1:-1] + do_quote = not kwargs.get("skip_quote", False) + return self.serialize_iter(data, internal_data_type, do_quote=do_quote, **kwargs) + + # Not a list, regular serialization + output = self.serialize_data(data, data_type, **kwargs) + if data_type == "bool": + output = json.dumps(output) + if kwargs.get("skip_quote") is True: + output = str(output) + else: + output = quote(str(output), safe="") + except SerializationError as exc: + raise TypeError("{} must be type {}.".format(name, data_type)) from exc + return str(output) + + def header(self, name, data, data_type, **kwargs): + """Serialize data intended for a request header. + + :param str name: The name of the header. + :param object data: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: str + :raises TypeError: if serialization fails. + :raises ValueError: if data is None + :returns: The serialized header + """ + try: + if data_type in ["[str]"]: + data = ["" if d is None else d for d in data] + + output = self.serialize_data(data, data_type, **kwargs) + if data_type == "bool": + output = json.dumps(output) + except SerializationError as exc: + raise TypeError("{} must be type {}.".format(name, data_type)) from exc + return str(output) + + def serialize_data(self, data, data_type, **kwargs): + """Serialize generic data according to supplied data type. + + :param object data: The data to be serialized. + :param str data_type: The type to be serialized from. + :raises AttributeError: if required data is None. + :raises ValueError: if data is None + :raises SerializationError: if serialization fails. + :returns: The serialized data. + :rtype: str, int, float, bool, dict, list + """ + if data is None: + raise ValueError("No value for given attribute") + + try: + if data is CoreNull: + return None + if data_type in self.basic_types.values(): + return self.serialize_basic(data, data_type, **kwargs) + + if data_type in self.serialize_type: + return self.serialize_type[data_type](data, **kwargs) + + # If dependencies is empty, try with current data class + # It has to be a subclass of Enum anyway + enum_type = self.dependencies.get(data_type, cast(type, data.__class__)) + if issubclass(enum_type, Enum): + return Serializer.serialize_enum(data, enum_obj=enum_type) + + iter_type = data_type[0] + data_type[-1] + if iter_type in self.serialize_type: + return self.serialize_type[iter_type](data, data_type[1:-1], **kwargs) + + except (ValueError, TypeError) as err: + msg = "Unable to serialize value: {!r} as type: {!r}." + raise SerializationError(msg.format(data, data_type)) from err + return self._serialize(data, **kwargs) + + @classmethod + def _get_custom_serializers(cls, data_type, **kwargs): # pylint: disable=inconsistent-return-statements + custom_serializer = kwargs.get("basic_types_serializers", {}).get(data_type) + if custom_serializer: + return custom_serializer + if kwargs.get("is_xml", False): + return cls._xml_basic_types_serializers.get(data_type) + + @classmethod + def serialize_basic(cls, data, data_type, **kwargs): + """Serialize basic builting data type. + Serializes objects to str, int, float or bool. + + Possible kwargs: + - basic_types_serializers dict[str, callable] : If set, use the callable as serializer + - is_xml bool : If set, use xml_basic_types_serializers + + :param obj data: Object to be serialized. + :param str data_type: Type of object in the iterable. + :rtype: str, int, float, bool + :return: serialized object + :raises TypeError: raise if data_type is not one of str, int, float, bool. + """ + custom_serializer = cls._get_custom_serializers(data_type, **kwargs) + if custom_serializer: + return custom_serializer(data) + if data_type == "str": + return cls.serialize_unicode(data) + if data_type == "int": + return int(data) + if data_type == "float": + return float(data) + if data_type == "bool": + return bool(data) + raise TypeError("Unknown basic data type: {}".format(data_type)) + + @classmethod + def serialize_unicode(cls, data): + """Special handling for serializing unicode strings in Py2. + Encode to UTF-8 if unicode, otherwise handle as a str. + + :param str data: Object to be serialized. + :rtype: str + :return: serialized object + """ + try: # If I received an enum, return its value + return data.value + except AttributeError: + pass + + try: + if isinstance(data, unicode): # type: ignore + # Don't change it, JSON and XML ElementTree are totally able + # to serialize correctly u'' strings + return data + except NameError: + return str(data) + return str(data) + + def serialize_iter(self, data, iter_type, div=None, **kwargs): + """Serialize iterable. + + Supported kwargs: + - serialization_ctxt dict : The current entry of _attribute_map, or same format. + serialization_ctxt['type'] should be same as data_type. + - is_xml bool : If set, serialize as XML + + :param list data: Object to be serialized. + :param str iter_type: Type of object in the iterable. + :param str div: If set, this str will be used to combine the elements + in the iterable into a combined string. Default is 'None'. + Defaults to False. + :rtype: list, str + :return: serialized iterable + """ + if isinstance(data, str): + raise SerializationError("Refuse str type as a valid iter type.") + + serialization_ctxt = kwargs.get("serialization_ctxt", {}) + is_xml = kwargs.get("is_xml", False) + + serialized = [] + for d in data: + try: + serialized.append(self.serialize_data(d, iter_type, **kwargs)) + except ValueError as err: + if isinstance(err, SerializationError): + raise + serialized.append(None) + + if kwargs.get("do_quote", False): + serialized = ["" if s is None else quote(str(s), safe="") for s in serialized] + + if div: + serialized = ["" if s is None else str(s) for s in serialized] + serialized = div.join(serialized) + + if "xml" in serialization_ctxt or is_xml: + # XML serialization is more complicated + xml_desc = serialization_ctxt.get("xml", {}) + xml_name = xml_desc.get("name") + if not xml_name: + xml_name = serialization_ctxt["key"] + + # Create a wrap node if necessary (use the fact that Element and list have "append") + is_wrapped = xml_desc.get("wrapped", False) + node_name = xml_desc.get("itemsName", xml_name) + if is_wrapped: + final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) + else: + final_result = [] + # All list elements to "local_node" + for el in serialized: + if isinstance(el, ET.Element): + el_node = el + else: + el_node = _create_xml_node(node_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) + if el is not None: # Otherwise it writes "None" :-p + el_node.text = str(el) + final_result.append(el_node) + return final_result + return serialized + + def serialize_dict(self, attr, dict_type, **kwargs): + """Serialize a dictionary of objects. + + :param dict attr: Object to be serialized. + :param str dict_type: Type of object in the dictionary. + :rtype: dict + :return: serialized dictionary + """ + serialization_ctxt = kwargs.get("serialization_ctxt", {}) + serialized = {} + for key, value in attr.items(): + try: + serialized[self.serialize_unicode(key)] = self.serialize_data(value, dict_type, **kwargs) + except ValueError as err: + if isinstance(err, SerializationError): + raise + serialized[self.serialize_unicode(key)] = None + + if "xml" in serialization_ctxt: + # XML serialization is more complicated + xml_desc = serialization_ctxt["xml"] + xml_name = xml_desc["name"] + + final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) + for key, value in serialized.items(): + ET.SubElement(final_result, key).text = value + return final_result + + return serialized + + def serialize_object(self, attr, **kwargs): # pylint: disable=too-many-return-statements + """Serialize a generic object. + This will be handled as a dictionary. If object passed in is not + a basic type (str, int, float, dict, list) it will simply be + cast to str. + + :param dict attr: Object to be serialized. + :rtype: dict or str + :return: serialized object + """ + if attr is None: + return None + if isinstance(attr, ET.Element): + return attr + obj_type = type(attr) + if obj_type in self.basic_types: + return self.serialize_basic(attr, self.basic_types[obj_type], **kwargs) + if obj_type is _long_type: + return self.serialize_long(attr) + if obj_type is str: + return self.serialize_unicode(attr) + if obj_type is datetime.datetime: + return self.serialize_iso(attr) + if obj_type is datetime.date: + return self.serialize_date(attr) + if obj_type is datetime.time: + return self.serialize_time(attr) + if obj_type is datetime.timedelta: + return self.serialize_duration(attr) + if obj_type is decimal.Decimal: + return self.serialize_decimal(attr) + + # If it's a model or I know this dependency, serialize as a Model + if obj_type in self.dependencies.values() or isinstance(attr, Model): + return self._serialize(attr) + + if obj_type == dict: + serialized = {} + for key, value in attr.items(): + try: + serialized[self.serialize_unicode(key)] = self.serialize_object(value, **kwargs) + except ValueError: + serialized[self.serialize_unicode(key)] = None + return serialized + + if obj_type == list: + serialized = [] + for obj in attr: + try: + serialized.append(self.serialize_object(obj, **kwargs)) + except ValueError: + pass + return serialized + return str(attr) + + @staticmethod + def serialize_enum(attr, enum_obj=None): + try: + result = attr.value + except AttributeError: + result = attr + try: + enum_obj(result) # type: ignore + return result + except ValueError as exc: + for enum_value in enum_obj: # type: ignore + if enum_value.value.lower() == str(attr).lower(): + return enum_value.value + error = "{!r} is not valid value for enum {!r}" + raise SerializationError(error.format(attr, enum_obj)) from exc + + @staticmethod + def serialize_bytearray(attr, **kwargs): # pylint: disable=unused-argument + """Serialize bytearray into base-64 string. + + :param str attr: Object to be serialized. + :rtype: str + :return: serialized base64 + """ + return b64encode(attr).decode() + + @staticmethod + def serialize_base64(attr, **kwargs): # pylint: disable=unused-argument + """Serialize str into base-64 string. + + :param str attr: Object to be serialized. + :rtype: str + :return: serialized base64 + """ + encoded = b64encode(attr).decode("ascii") + return encoded.strip("=").replace("+", "-").replace("/", "_") + + @staticmethod + def serialize_decimal(attr, **kwargs): # pylint: disable=unused-argument + """Serialize Decimal object to float. + + :param decimal attr: Object to be serialized. + :rtype: float + :return: serialized decimal + """ + return float(attr) + + @staticmethod + def serialize_long(attr, **kwargs): # pylint: disable=unused-argument + """Serialize long (Py2) or int (Py3). + + :param int attr: Object to be serialized. + :rtype: int/long + :return: serialized long + """ + return _long_type(attr) + + @staticmethod + def serialize_date(attr, **kwargs): # pylint: disable=unused-argument + """Serialize Date object into ISO-8601 formatted string. + + :param Date attr: Object to be serialized. + :rtype: str + :return: serialized date + """ + if isinstance(attr, str): + attr = isodate.parse_date(attr) + t = "{:04}-{:02}-{:02}".format(attr.year, attr.month, attr.day) + return t + + @staticmethod + def serialize_time(attr, **kwargs): # pylint: disable=unused-argument + """Serialize Time object into ISO-8601 formatted string. + + :param datetime.time attr: Object to be serialized. + :rtype: str + :return: serialized time + """ + if isinstance(attr, str): + attr = isodate.parse_time(attr) + t = "{:02}:{:02}:{:02}".format(attr.hour, attr.minute, attr.second) + if attr.microsecond: + t += ".{:02}".format(attr.microsecond) + return t + + @staticmethod + def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into ISO-8601 formatted string. + + :param TimeDelta attr: Object to be serialized. + :rtype: str + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + return isodate.duration_isoformat(attr) + + @staticmethod + def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument + """Serialize Datetime object into RFC-1123 formatted string. + + :param Datetime attr: Object to be serialized. + :rtype: str + :raises TypeError: if format invalid. + :return: serialized rfc + """ + try: + if not attr.tzinfo: + _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") + utc = attr.utctimetuple() + except AttributeError as exc: + raise TypeError("RFC1123 object must be valid Datetime object.") from exc + + return "{}, {:02} {} {:04} {:02}:{:02}:{:02} GMT".format( + Serializer.days[utc.tm_wday], + utc.tm_mday, + Serializer.months[utc.tm_mon], + utc.tm_year, + utc.tm_hour, + utc.tm_min, + utc.tm_sec, + ) + + @staticmethod + def serialize_iso(attr, **kwargs): # pylint: disable=unused-argument + """Serialize Datetime object into ISO-8601 formatted string. + + :param Datetime attr: Object to be serialized. + :rtype: str + :raises SerializationError: if format invalid. + :return: serialized iso + """ + if isinstance(attr, str): + attr = isodate.parse_datetime(attr) + try: + if not attr.tzinfo: + _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") + utc = attr.utctimetuple() + if utc.tm_year > 9999 or utc.tm_year < 1: + raise OverflowError("Hit max or min date") + + microseconds = str(attr.microsecond).rjust(6, "0").rstrip("0").ljust(3, "0") + if microseconds: + microseconds = "." + microseconds + date = "{:04}-{:02}-{:02}T{:02}:{:02}:{:02}".format( + utc.tm_year, utc.tm_mon, utc.tm_mday, utc.tm_hour, utc.tm_min, utc.tm_sec + ) + return date + microseconds + "Z" + except (ValueError, OverflowError) as err: + msg = "Unable to serialize datetime object." + raise SerializationError(msg) from err + except AttributeError as err: + msg = "ISO-8601 object must be valid Datetime object." + raise TypeError(msg) from err + + @staticmethod + def serialize_unix(attr, **kwargs): # pylint: disable=unused-argument + """Serialize Datetime object into IntTime format. + This is represented as seconds. + + :param Datetime attr: Object to be serialized. + :rtype: int + :raises SerializationError: if format invalid + :return: serialied unix + """ + if isinstance(attr, int): + return attr + try: + if not attr.tzinfo: + _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") + return int(calendar.timegm(attr.utctimetuple())) + except AttributeError as exc: + raise TypeError("Unix time object must be valid Datetime object.") from exc + + +def rest_key_extractor(attr, attr_desc, data): # pylint: disable=unused-argument + key = attr_desc["key"] + working_data = data + + while "." in key: + # Need the cast, as for some reasons "split" is typed as list[str | Any] + dict_keys = cast(list[str], _FLATTEN.split(key)) + if len(dict_keys) == 1: + key = _decode_attribute_map_key(dict_keys[0]) + break + working_key = _decode_attribute_map_key(dict_keys[0]) + working_data = working_data.get(working_key, data) + if working_data is None: + # If at any point while following flatten JSON path see None, it means + # that all properties under are None as well + return None + key = ".".join(dict_keys[1:]) + + return working_data.get(key) + + +def rest_key_case_insensitive_extractor( # pylint: disable=unused-argument, inconsistent-return-statements + attr, attr_desc, data +): + key = attr_desc["key"] + working_data = data + + while "." in key: + dict_keys = _FLATTEN.split(key) + if len(dict_keys) == 1: + key = _decode_attribute_map_key(dict_keys[0]) + break + working_key = _decode_attribute_map_key(dict_keys[0]) + working_data = attribute_key_case_insensitive_extractor(working_key, None, working_data) + if working_data is None: + # If at any point while following flatten JSON path see None, it means + # that all properties under are None as well + return None + key = ".".join(dict_keys[1:]) + + if working_data: + return attribute_key_case_insensitive_extractor(key, None, working_data) + + +def last_rest_key_extractor(attr, attr_desc, data): # pylint: disable=unused-argument + """Extract the attribute in "data" based on the last part of the JSON path key. + + :param str attr: The attribute to extract + :param dict attr_desc: The attribute description + :param dict data: The data to extract from + :rtype: object + :returns: The extracted attribute + """ + key = attr_desc["key"] + dict_keys = _FLATTEN.split(key) + return attribute_key_extractor(dict_keys[-1], None, data) + + +def last_rest_key_case_insensitive_extractor(attr, attr_desc, data): # pylint: disable=unused-argument + """Extract the attribute in "data" based on the last part of the JSON path key. + + This is the case insensitive version of "last_rest_key_extractor" + :param str attr: The attribute to extract + :param dict attr_desc: The attribute description + :param dict data: The data to extract from + :rtype: object + :returns: The extracted attribute + """ + key = attr_desc["key"] + dict_keys = _FLATTEN.split(key) + return attribute_key_case_insensitive_extractor(dict_keys[-1], None, data) + + +def attribute_key_extractor(attr, _, data): + return data.get(attr) + + +def attribute_key_case_insensitive_extractor(attr, _, data): + found_key = None + lower_attr = attr.lower() + for key in data: + if lower_attr == key.lower(): + found_key = key + break + + return data.get(found_key) + + +def _extract_name_from_internal_type(internal_type): + """Given an internal type XML description, extract correct XML name with namespace. + + :param dict internal_type: An model type + :rtype: tuple + :returns: A tuple XML name + namespace dict + """ + internal_type_xml_map = getattr(internal_type, "_xml_map", {}) + xml_name = internal_type_xml_map.get("name", internal_type.__name__) + xml_ns = internal_type_xml_map.get("ns", None) + if xml_ns: + xml_name = "{{{}}}{}".format(xml_ns, xml_name) + return xml_name + + +def xml_key_extractor(attr, attr_desc, data): # pylint: disable=unused-argument,too-many-return-statements + if isinstance(data, dict): + return None + + # Test if this model is XML ready first + if not isinstance(data, ET.Element): + return None + + xml_desc = attr_desc.get("xml", {}) + xml_name = xml_desc.get("name", attr_desc["key"]) + + # Look for a children + is_iter_type = attr_desc["type"].startswith("[") + is_wrapped = xml_desc.get("wrapped", False) + internal_type = attr_desc.get("internalType", None) + internal_type_xml_map = getattr(internal_type, "_xml_map", {}) + + # Integrate namespace if necessary + xml_ns = xml_desc.get("ns", internal_type_xml_map.get("ns", None)) + if xml_ns: + xml_name = "{{{}}}{}".format(xml_ns, xml_name) + + # If it's an attribute, that's simple + if xml_desc.get("attr", False): + return data.get(xml_name) + + # If it's x-ms-text, that's simple too + if xml_desc.get("text", False): + return data.text + + # Scenario where I take the local name: + # - Wrapped node + # - Internal type is an enum (considered basic types) + # - Internal type has no XML/Name node + if is_wrapped or (internal_type and (issubclass(internal_type, Enum) or "name" not in internal_type_xml_map)): + children = data.findall(xml_name) + # If internal type has a local name and it's not a list, I use that name + elif not is_iter_type and internal_type and "name" in internal_type_xml_map: + xml_name = _extract_name_from_internal_type(internal_type) + children = data.findall(xml_name) + # That's an array + else: + if internal_type: # Complex type, ignore itemsName and use the complex type name + items_name = _extract_name_from_internal_type(internal_type) + else: + items_name = xml_desc.get("itemsName", xml_name) + children = data.findall(items_name) + + if len(children) == 0: + if is_iter_type: + if is_wrapped: + return None # is_wrapped no node, we want None + return [] # not wrapped, assume empty list + return None # Assume it's not there, maybe an optional node. + + # If is_iter_type and not wrapped, return all found children + if is_iter_type: + if not is_wrapped: + return children + # Iter and wrapped, should have found one node only (the wrap one) + if len(children) != 1: + raise DeserializationError( + "Tried to deserialize an array not wrapped, and found several nodes '{}'. Maybe you should declare this array as wrapped?".format( + xml_name + ) + ) + return list(children[0]) # Might be empty list and that's ok. + + # Here it's not a itertype, we should have found one element only or empty + if len(children) > 1: + raise DeserializationError("Find several XML '{}' where it was not expected".format(xml_name)) + return children[0] + + +class Deserializer: + """Response object model deserializer. + + :param dict classes: Class type dictionary for deserializing complex types. + :ivar list key_extractors: Ordered list of extractors to be used by this deserializer. + """ + + basic_types = {str: "str", int: "int", bool: "bool", float: "float"} + + valid_date = re.compile(r"\d{4}[-]\d{2}[-]\d{2}T\d{2}:\d{2}:\d{2}\.?\d*Z?[-+]?[\d{2}]?:?[\d{2}]?") + + def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: + self.deserialize_type = { + "iso-8601": Deserializer.deserialize_iso, + "rfc-1123": Deserializer.deserialize_rfc, + "unix-time": Deserializer.deserialize_unix, + "duration": Deserializer.deserialize_duration, + "date": Deserializer.deserialize_date, + "time": Deserializer.deserialize_time, + "decimal": Deserializer.deserialize_decimal, + "long": Deserializer.deserialize_long, + "bytearray": Deserializer.deserialize_bytearray, + "base64": Deserializer.deserialize_base64, + "object": self.deserialize_object, + "[]": self.deserialize_iter, + "{}": self.deserialize_dict, + } + self.deserialize_expected_types = { + "duration": (isodate.Duration, datetime.timedelta), + "iso-8601": (datetime.datetime), + } + self.dependencies: dict[str, type] = dict(classes) if classes else {} + self.key_extractors = [rest_key_extractor, xml_key_extractor] + # Additional properties only works if the "rest_key_extractor" is used to + # extract the keys. Making it to work whatever the key extractor is too much + # complicated, with no real scenario for now. + # So adding a flag to disable additional properties detection. This flag should be + # used if your expect the deserialization to NOT come from a JSON REST syntax. + # Otherwise, result are unexpected + self.additional_properties_detection = True + + def __call__(self, target_obj, response_data, content_type=None): + """Call the deserializer to process a REST response. + + :param str target_obj: Target data type to deserialize to. + :param requests.Response response_data: REST response object. + :param str content_type: Swagger "produces" if available. + :raises DeserializationError: if deserialization fails. + :return: Deserialized object. + :rtype: object + """ + data = self._unpack_content(response_data, content_type) + return self._deserialize(target_obj, data) + + def _deserialize(self, target_obj, data): # pylint: disable=inconsistent-return-statements + """Call the deserializer on a model. + + Data needs to be already deserialized as JSON or XML ElementTree + + :param str target_obj: Target data type to deserialize to. + :param object data: Object to deserialize. + :raises DeserializationError: if deserialization fails. + :return: Deserialized object. + :rtype: object + """ + # This is already a model, go recursive just in case + if hasattr(data, "_attribute_map"): + constants = [name for name, config in getattr(data, "_validation", {}).items() if config.get("constant")] + try: + for attr, mapconfig in data._attribute_map.items(): # pylint: disable=protected-access + if attr in constants: + continue + value = getattr(data, attr) + if value is None: + continue + local_type = mapconfig["type"] + internal_data_type = local_type.strip("[]{}") + if internal_data_type not in self.dependencies or isinstance(internal_data_type, Enum): + continue + setattr(data, attr, self._deserialize(local_type, value)) + return data + except AttributeError: + return + + response, class_name = self._classify_target(target_obj, data) + + if isinstance(response, str): + return self.deserialize_data(data, response) + if isinstance(response, type) and issubclass(response, Enum): + return self.deserialize_enum(data, response) + + if data is None or data is CoreNull: + return data + try: + attributes = response._attribute_map # type: ignore # pylint: disable=protected-access + d_attrs = {} + for attr, attr_desc in attributes.items(): + # Check empty string. If it's not empty, someone has a real "additionalProperties"... + if attr == "additional_properties" and attr_desc["key"] == "": + continue + raw_value = None + # Enhance attr_desc with some dynamic data + attr_desc = attr_desc.copy() # Do a copy, do not change the real one + internal_data_type = attr_desc["type"].strip("[]{}") + if internal_data_type in self.dependencies: + attr_desc["internalType"] = self.dependencies[internal_data_type] + + for key_extractor in self.key_extractors: + found_value = key_extractor(attr, attr_desc, data) + if found_value is not None: + if raw_value is not None and raw_value != found_value: + msg = ( + "Ignoring extracted value '%s' from %s for key '%s'" + " (duplicate extraction, follow extractors order)" + ) + _LOGGER.warning(msg, found_value, key_extractor, attr) + continue + raw_value = found_value + + value = self.deserialize_data(raw_value, attr_desc["type"]) + d_attrs[attr] = value + except (AttributeError, TypeError, KeyError) as err: + msg = "Unable to deserialize to object: " + class_name # type: ignore + raise DeserializationError(msg) from err + additional_properties = self._build_additional_properties(attributes, data) + return self._instantiate_model(response, d_attrs, additional_properties) + + def _build_additional_properties(self, attribute_map, data): + if not self.additional_properties_detection: + return None + if "additional_properties" in attribute_map and attribute_map.get("additional_properties", {}).get("key") != "": + # Check empty string. If it's not empty, someone has a real "additionalProperties" + return None + if isinstance(data, ET.Element): + data = {el.tag: el.text for el in data} + + known_keys = { + _decode_attribute_map_key(_FLATTEN.split(desc["key"])[0]) + for desc in attribute_map.values() + if desc["key"] != "" + } + present_keys = set(data.keys()) + missing_keys = present_keys - known_keys + return {key: data[key] for key in missing_keys} + + def _classify_target(self, target, data): + """Check to see whether the deserialization target object can + be classified into a subclass. + Once classification has been determined, initialize object. + + :param str target: The target object type to deserialize to. + :param str/dict data: The response data to deserialize. + :return: The classified target object and its class name. + :rtype: tuple + """ + if target is None: + return None, None + + if isinstance(target, str): + try: + target = self.dependencies[target] + except KeyError: + return target, target + + try: + target = target._classify(data, self.dependencies) # type: ignore # pylint: disable=protected-access + except AttributeError: + pass # Target is not a Model, no classify + return target, target.__class__.__name__ # type: ignore + + def failsafe_deserialize(self, target_obj, data, content_type=None): + """Ignores any errors encountered in deserialization, + and falls back to not deserializing the object. Recommended + for use in error deserialization, as we want to return the + HttpResponseError to users, and not have them deal with + a deserialization error. + + :param str target_obj: The target object type to deserialize to. + :param str/dict data: The response data to deserialize. + :param str content_type: Swagger "produces" if available. + :return: Deserialized object. + :rtype: object + """ + try: + return self(target_obj, data, content_type=content_type) + except: # pylint: disable=bare-except + _LOGGER.debug( + "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True + ) + return None + + @staticmethod + def _unpack_content(raw_data, content_type=None): + """Extract the correct structure for deserialization. + + If raw_data is a PipelineResponse, try to extract the result of RawDeserializer. + if we can't, raise. Your Pipeline should have a RawDeserializer. + + If not a pipeline response and raw_data is bytes or string, use content-type + to decode it. If no content-type, try JSON. + + If raw_data is something else, bypass all logic and return it directly. + + :param obj raw_data: Data to be processed. + :param str content_type: How to parse if raw_data is a string/bytes. + :raises JSONDecodeError: If JSON is requested and parsing is impossible. + :raises UnicodeDecodeError: If bytes is not UTF8 + :rtype: object + :return: Unpacked content. + """ + # Assume this is enough to detect a Pipeline Response without importing it + context = getattr(raw_data, "context", {}) + if context: + if RawDeserializer.CONTEXT_NAME in context: + return context[RawDeserializer.CONTEXT_NAME] + raise ValueError("This pipeline didn't have the RawDeserializer policy; can't deserialize") + + # Assume this is enough to recognize universal_http.ClientResponse without importing it + if hasattr(raw_data, "body"): + return RawDeserializer.deserialize_from_http_generics(raw_data.text(), raw_data.headers) + + # Assume this enough to recognize requests.Response without importing it. + if hasattr(raw_data, "_content_consumed"): + return RawDeserializer.deserialize_from_http_generics(raw_data.text, raw_data.headers) + + if isinstance(raw_data, (str, bytes)) or hasattr(raw_data, "read"): + return RawDeserializer.deserialize_from_text(raw_data, content_type) # type: ignore + return raw_data + + def _instantiate_model(self, response, attrs, additional_properties=None): + """Instantiate a response model passing in deserialized args. + + :param Response response: The response model class. + :param dict attrs: The deserialized response attributes. + :param dict additional_properties: Additional properties to be set. + :rtype: Response + :return: The instantiated response model. + """ + if callable(response): + subtype = getattr(response, "_subtype_map", {}) + try: + readonly = [ + k + for k, v in response._validation.items() # pylint: disable=protected-access # type: ignore + if v.get("readonly") + ] + const = [ + k + for k, v in response._validation.items() # pylint: disable=protected-access # type: ignore + if v.get("constant") + ] + kwargs = {k: v for k, v in attrs.items() if k not in subtype and k not in readonly + const} + response_obj = response(**kwargs) + for attr in readonly: + setattr(response_obj, attr, attrs.get(attr)) + if additional_properties: + response_obj.additional_properties = additional_properties # type: ignore + return response_obj + except TypeError as err: + msg = "Unable to deserialize {} into model {}. ".format(kwargs, response) # type: ignore + raise DeserializationError(msg + str(err)) from err + else: + try: + for attr, value in attrs.items(): + setattr(response, attr, value) + return response + except Exception as exp: + msg = "Unable to populate response model. " + msg += "Type: {}, Error: {}".format(type(response), exp) + raise DeserializationError(msg) from exp + + def deserialize_data(self, data, data_type): # pylint: disable=too-many-return-statements + """Process data for deserialization according to data type. + + :param str data: The response string to be deserialized. + :param str data_type: The type to deserialize to. + :raises DeserializationError: if deserialization fails. + :return: Deserialized object. + :rtype: object + """ + if data is None: + return data + + try: + if not data_type: + return data + if data_type in self.basic_types.values(): + return self.deserialize_basic(data, data_type) + if data_type in self.deserialize_type: + if isinstance(data, self.deserialize_expected_types.get(data_type, tuple())): + return data + + is_a_text_parsing_type = lambda x: x not in [ # pylint: disable=unnecessary-lambda-assignment + "object", + "[]", + r"{}", + ] + if isinstance(data, ET.Element) and is_a_text_parsing_type(data_type) and not data.text: + return None + data_val = self.deserialize_type[data_type](data) + return data_val + + iter_type = data_type[0] + data_type[-1] + if iter_type in self.deserialize_type: + return self.deserialize_type[iter_type](data, data_type[1:-1]) + + obj_type = self.dependencies[data_type] + if issubclass(obj_type, Enum): + if isinstance(data, ET.Element): + data = data.text + return self.deserialize_enum(data, obj_type) + + except (ValueError, TypeError, AttributeError) as err: + msg = "Unable to deserialize response data." + msg += " Data: {}, {}".format(data, data_type) + raise DeserializationError(msg) from err + return self._deserialize(obj_type, data) + + def deserialize_iter(self, attr, iter_type): + """Deserialize an iterable. + + :param list attr: Iterable to be deserialized. + :param str iter_type: The type of object in the iterable. + :return: Deserialized iterable. + :rtype: list + """ + if attr is None: + return None + if isinstance(attr, ET.Element): # If I receive an element here, get the children + attr = list(attr) + if not isinstance(attr, (list, set)): + raise DeserializationError("Cannot deserialize as [{}] an object of type {}".format(iter_type, type(attr))) + return [self.deserialize_data(a, iter_type) for a in attr] + + def deserialize_dict(self, attr, dict_type): + """Deserialize a dictionary. + + :param dict/list attr: Dictionary to be deserialized. Also accepts + a list of key, value pairs. + :param str dict_type: The object type of the items in the dictionary. + :return: Deserialized dictionary. + :rtype: dict + """ + if isinstance(attr, list): + return {x["key"]: self.deserialize_data(x["value"], dict_type) for x in attr} + + if isinstance(attr, ET.Element): + # Transform value into {"Key": "value"} + attr = {el.tag: el.text for el in attr} + return {k: self.deserialize_data(v, dict_type) for k, v in attr.items()} + + def deserialize_object(self, attr, **kwargs): # pylint: disable=too-many-return-statements + """Deserialize a generic object. + This will be handled as a dictionary. + + :param dict attr: Dictionary to be deserialized. + :return: Deserialized object. + :rtype: dict + :raises TypeError: if non-builtin datatype encountered. + """ + if attr is None: + return None + if isinstance(attr, ET.Element): + # Do no recurse on XML, just return the tree as-is + return attr + if isinstance(attr, str): + return self.deserialize_basic(attr, "str") + obj_type = type(attr) + if obj_type in self.basic_types: + return self.deserialize_basic(attr, self.basic_types[obj_type]) + if obj_type is _long_type: + return self.deserialize_long(attr) + + if obj_type == dict: + deserialized = {} + for key, value in attr.items(): + try: + deserialized[key] = self.deserialize_object(value, **kwargs) + except ValueError: + deserialized[key] = None + return deserialized + + if obj_type == list: + deserialized = [] + for obj in attr: + try: + deserialized.append(self.deserialize_object(obj, **kwargs)) + except ValueError: + pass + return deserialized + + error = "Cannot deserialize generic object with type: " + raise TypeError(error + str(obj_type)) + + def deserialize_basic(self, attr, data_type): # pylint: disable=too-many-return-statements + """Deserialize basic builtin data type from string. + Will attempt to convert to str, int, float and bool. + This function will also accept '1', '0', 'true' and 'false' as + valid bool values. + + :param str attr: response string to be deserialized. + :param str data_type: deserialization data type. + :return: Deserialized basic type. + :rtype: str, int, float or bool + :raises TypeError: if string format is not valid or data_type is not one of str, int, float, bool. + """ + # If we're here, data is supposed to be a basic type. + # If it's still an XML node, take the text + if isinstance(attr, ET.Element): + attr = attr.text + if not attr: + if data_type == "str": + # None or '', node is empty string. + return "" + # None or '', node with a strong type is None. + # Don't try to model "empty bool" or "empty int" + return None + + if data_type == "bool": + if attr in [True, False, 1, 0]: + return bool(attr) + if isinstance(attr, str): + if attr.lower() in ["true", "1"]: + return True + if attr.lower() in ["false", "0"]: + return False + raise TypeError("Invalid boolean value: {}".format(attr)) + + if data_type == "str": + return self.deserialize_unicode(attr) + if data_type == "int": + return int(attr) + if data_type == "float": + return float(attr) + raise TypeError("Unknown basic data type: {}".format(data_type)) + + @staticmethod + def deserialize_unicode(data): + """Preserve unicode objects in Python 2, otherwise return data + as a string. + + :param str data: response string to be deserialized. + :return: Deserialized string. + :rtype: str or unicode + """ + # We might be here because we have an enum modeled as string, + # and we try to deserialize a partial dict with enum inside + if isinstance(data, Enum): + return data + + # Consider this is real string + try: + if isinstance(data, unicode): # type: ignore + return data + except NameError: + return str(data) + return str(data) + + @staticmethod + def deserialize_enum(data, enum_obj): + """Deserialize string into enum object. + + If the string is not a valid enum value it will be returned as-is + and a warning will be logged. + + :param str data: Response string to be deserialized. If this value is + None or invalid it will be returned as-is. + :param Enum enum_obj: Enum object to deserialize to. + :return: Deserialized enum object. + :rtype: Enum + """ + if isinstance(data, enum_obj) or data is None: + return data + if isinstance(data, Enum): + data = data.value + if isinstance(data, int): + # Workaround. We might consider remove it in the future. + try: + return list(enum_obj.__members__.values())[data] + except IndexError as exc: + error = "{!r} is not a valid index for enum {!r}" + raise DeserializationError(error.format(data, enum_obj)) from exc + try: + return enum_obj(str(data)) + except ValueError: + for enum_value in enum_obj: + if enum_value.value.lower() == str(data).lower(): + return enum_value + # We don't fail anymore for unknown value, we deserialize as a string + _LOGGER.warning("Deserializer is not able to find %s as valid enum in %s", data, enum_obj) + return Deserializer.deserialize_unicode(data) + + @staticmethod + def deserialize_bytearray(attr): + """Deserialize string into bytearray. + + :param str attr: response string to be deserialized. + :return: Deserialized bytearray + :rtype: bytearray + :raises TypeError: if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + return bytearray(b64decode(attr)) # type: ignore + + @staticmethod + def deserialize_base64(attr): + """Deserialize base64 encoded string into string. + + :param str attr: response string to be deserialized. + :return: Deserialized base64 string + :rtype: bytearray + :raises TypeError: if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + padding = "=" * (3 - (len(attr) + 3) % 4) # type: ignore + attr = attr + padding # type: ignore + encoded = attr.replace("-", "+").replace("_", "/") + return b64decode(encoded) + + @staticmethod + def deserialize_decimal(attr): + """Deserialize string into Decimal object. + + :param str attr: response string to be deserialized. + :return: Deserialized decimal + :raises DeserializationError: if string format invalid. + :rtype: decimal + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + return decimal.Decimal(str(attr)) # type: ignore + except decimal.DecimalException as err: + msg = "Invalid decimal {}".format(attr) + raise DeserializationError(msg) from err + + @staticmethod + def deserialize_long(attr): + """Deserialize string into long (Py2) or int (Py3). + + :param str attr: response string to be deserialized. + :return: Deserialized int + :rtype: long or int + :raises ValueError: if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + return _long_type(attr) # type: ignore + + @staticmethod + def deserialize_duration(attr): + """Deserialize ISO-8601 formatted string into TimeDelta object. + + :param str attr: response string to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = isodate.parse_duration(attr) + except (ValueError, OverflowError, AttributeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_date(attr): + """Deserialize ISO-8601 formatted string into Date object. + + :param str attr: response string to be deserialized. + :return: Deserialized date + :rtype: Date + :raises DeserializationError: if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + if re.search(r"[^\W\d_]", attr, re.I + re.U): # type: ignore + raise DeserializationError("Date must have only digits and -. Received: %s" % attr) + # This must NOT use defaultmonth/defaultday. Using None ensure this raises an exception. + return isodate.parse_date(attr, defaultmonth=0, defaultday=0) + + @staticmethod + def deserialize_time(attr): + """Deserialize ISO-8601 formatted string into time object. + + :param str attr: response string to be deserialized. + :return: Deserialized time + :rtype: datetime.time + :raises DeserializationError: if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + if re.search(r"[^\W\d_]", attr, re.I + re.U): # type: ignore + raise DeserializationError("Date must have only digits and -. Received: %s" % attr) + return isodate.parse_time(attr) + + @staticmethod + def deserialize_rfc(attr): + """Deserialize RFC-1123 formatted string into Datetime object. + + :param str attr: response string to be deserialized. + :return: Deserialized RFC datetime + :rtype: Datetime + :raises DeserializationError: if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + parsed_date = email.utils.parsedate_tz(attr) # type: ignore + date_obj = datetime.datetime( + *parsed_date[:6], tzinfo=datetime.timezone(datetime.timedelta(minutes=(parsed_date[9] or 0) / 60)) + ) + if not date_obj.tzinfo: + date_obj = date_obj.astimezone(tz=TZ_UTC) + except ValueError as err: + msg = "Cannot deserialize to rfc datetime object." + raise DeserializationError(msg) from err + return date_obj + + @staticmethod + def deserialize_iso(attr): + """Deserialize ISO-8601 formatted string into Datetime object. + + :param str attr: response string to be deserialized. + :return: Deserialized ISO datetime + :rtype: Datetime + :raises DeserializationError: if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + attr = attr.upper() # type: ignore + match = Deserializer.valid_date.match(attr) + if not match: + raise ValueError("Invalid datetime string: " + attr) + + check_decimal = attr.split(".") + if len(check_decimal) > 1: + decimal_str = "" + for digit in check_decimal[1]: + if digit.isdigit(): + decimal_str += digit + else: + break + if len(decimal_str) > 6: + attr = attr.replace(decimal_str, decimal_str[0:6]) + + date_obj = isodate.parse_datetime(attr) + test_utc = date_obj.utctimetuple() + if test_utc.tm_year > 9999 or test_utc.tm_year < 1: + raise OverflowError("Hit max or min date") + except (ValueError, OverflowError, AttributeError) as err: + msg = "Cannot deserialize datetime object." + raise DeserializationError(msg) from err + return date_obj + + @staticmethod + def deserialize_unix(attr): + """Serialize Datetime object into IntTime format. + This is represented as seconds. + + :param int attr: Object to be serialized. + :return: Deserialized datetime + :rtype: Datetime + :raises DeserializationError: if format invalid + """ + if isinstance(attr, ET.Element): + attr = int(attr.text) # type: ignore + try: + attr = int(attr) + date_obj = datetime.datetime.fromtimestamp(attr, TZ_UTC) + except ValueError as err: + msg = "Cannot deserialize to unix datetime object." + raise DeserializationError(msg) from err + return date_obj diff --git a/src/azure/iot/hub/protocol/_version.py b/src/azure/iot/hub/protocol/_version.py new file mode 100644 index 0000000..5819b88 --- /dev/null +++ b/src/azure/iot/hub/protocol/_version.py @@ -0,0 +1,9 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +VERSION = "3.0.0b1" diff --git a/src/azure/iot/hub/protocol/aio/__init__.py b/src/azure/iot/hub/protocol/aio/__init__.py new file mode 100644 index 0000000..e74cc9f --- /dev/null +++ b/src/azure/iot/hub/protocol/aio/__init__.py @@ -0,0 +1,29 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._iot_hub_gateway_service_apis import IotHubGatewayServiceAPIs # type: ignore + +try: + from ._patch import __all__ as _patch_all + from ._patch import * +except ImportError: + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "IotHubGatewayServiceAPIs", +] +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore + +_patch_sdk() diff --git a/src/azure/iot/hub/protocol/aio/_configuration.py b/src/azure/iot/hub/protocol/aio/_configuration.py new file mode 100644 index 0000000..1613bc2 --- /dev/null +++ b/src/azure/iot/hub/protocol/aio/_configuration.py @@ -0,0 +1,44 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from typing import Any + +from azure.core.pipeline import policies + +from .._version import VERSION + + +class IotHubGatewayServiceAPIsConfiguration: # pylint: disable=too-many-instance-attributes + """Configuration for IotHubGatewayServiceAPIs. + + Note that all parameters used to create this instance are saved as instance + attributes. + + :keyword api_version: Api Version. Default value is "2021-04-12". Note that overriding this + default value may result in unsupported behavior. + :paramtype api_version: str + """ + + def __init__(self, **kwargs: Any) -> None: + api_version: str = kwargs.pop("api_version", "2021-04-12") + + self.api_version = api_version + kwargs.setdefault("sdk_moniker", "iot-hub/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) + self._configure(**kwargs) + + def _configure(self, **kwargs: Any) -> None: + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or policies.HttpLoggingPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.AsyncRedirectPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.AsyncRetryPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") diff --git a/src/azure/iot/hub/protocol/aio/_iot_hub_gateway_service_apis.py b/src/azure/iot/hub/protocol/aio/_iot_hub_gateway_service_apis.py new file mode 100644 index 0000000..877fd3c --- /dev/null +++ b/src/azure/iot/hub/protocol/aio/_iot_hub_gateway_service_apis.py @@ -0,0 +1,135 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from copy import deepcopy +from typing import Any, Awaitable +from typing_extensions import Self + +from azure.core import AsyncPipelineClient +from azure.core.pipeline import policies +from azure.core.rest import AsyncHttpResponse, HttpRequest + +from .. import models as _models +from .._utils.serialization import Deserializer, Serializer +from ._configuration import IotHubGatewayServiceAPIsConfiguration +from .operations import ( + BulkRegistryOperations, + CloudToDeviceMessagesOperations, + ConfigurationOperations, + DevicesOperations, + DigitalTwinOperations, + JobsOperations, + ModulesOperations, + QueryOperations, + StatisticsOperations, +) + + +class IotHubGatewayServiceAPIs: # pylint: disable=too-many-instance-attributes + """IotHubGatewayServiceAPIs. + + :ivar configuration: ConfigurationOperations operations + :vartype configuration: azure.iot.hub.protocol.aio.operations.ConfigurationOperations + :ivar statistics: StatisticsOperations operations + :vartype statistics: azure.iot.hub.protocol.aio.operations.StatisticsOperations + :ivar devices: DevicesOperations operations + :vartype devices: azure.iot.hub.protocol.aio.operations.DevicesOperations + :ivar bulk_registry: BulkRegistryOperations operations + :vartype bulk_registry: azure.iot.hub.protocol.aio.operations.BulkRegistryOperations + :ivar query: QueryOperations operations + :vartype query: azure.iot.hub.protocol.aio.operations.QueryOperations + :ivar jobs: JobsOperations operations + :vartype jobs: azure.iot.hub.protocol.aio.operations.JobsOperations + :ivar cloud_to_device_messages: CloudToDeviceMessagesOperations operations + :vartype cloud_to_device_messages: + azure.iot.hub.protocol.aio.operations.CloudToDeviceMessagesOperations + :ivar modules: ModulesOperations operations + :vartype modules: azure.iot.hub.protocol.aio.operations.ModulesOperations + :ivar digital_twin: DigitalTwinOperations operations + :vartype digital_twin: azure.iot.hub.protocol.aio.operations.DigitalTwinOperations + :param base_url: Service URL. Default value is + "https://fully-qualified-iothubname.azure-devices.net". + :type base_url: str + :keyword api_version: Api Version. Default value is "2021-04-12". Note that overriding this + default value may result in unsupported behavior. + :paramtype api_version: str + """ + + def __init__( # pylint: disable=missing-client-constructor-parameter-credential + self, base_url: str = "https://fully-qualified-iothubname.azure-devices.net", **kwargs: Any + ) -> None: + self._config = IotHubGatewayServiceAPIsConfiguration(**kwargs) + + _policies = kwargs.pop("policies", None) + if _policies is None: + _policies = [ + policies.RequestIdPolicy(**kwargs), + self._config.headers_policy, + self._config.user_agent_policy, + self._config.proxy_policy, + policies.ContentDecodePolicy(**kwargs), + self._config.redirect_policy, + self._config.retry_policy, + self._config.authentication_policy, + self._config.custom_hook_policy, + self._config.logging_policy, + policies.DistributedTracingPolicy(**kwargs), + policies.SensitiveHeaderCleanupPolicy(**kwargs) if self._config.redirect_policy else None, + self._config.http_logging_policy, + ] + self._client: AsyncPipelineClient = AsyncPipelineClient(base_url=base_url, policies=_policies, **kwargs) + + client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)} + self._serialize = Serializer(client_models) + self._deserialize = Deserializer(client_models) + self._serialize.client_side_validation = False + self.configuration = ConfigurationOperations(self._client, self._config, self._serialize, self._deserialize) + self.statistics = StatisticsOperations(self._client, self._config, self._serialize, self._deserialize) + self.devices = DevicesOperations(self._client, self._config, self._serialize, self._deserialize) + self.bulk_registry = BulkRegistryOperations(self._client, self._config, self._serialize, self._deserialize) + self.query = QueryOperations(self._client, self._config, self._serialize, self._deserialize) + self.jobs = JobsOperations(self._client, self._config, self._serialize, self._deserialize) + self.cloud_to_device_messages = CloudToDeviceMessagesOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.modules = ModulesOperations(self._client, self._config, self._serialize, self._deserialize) + self.digital_twin = DigitalTwinOperations(self._client, self._config, self._serialize, self._deserialize) + + def _send_request( + self, request: HttpRequest, *, stream: bool = False, **kwargs: Any + ) -> Awaitable[AsyncHttpResponse]: + """Runs the network request through the client's chained policies. + + >>> from azure.core.rest import HttpRequest + >>> request = HttpRequest("GET", "https://www.example.org/") + + >>> response = await client._send_request(request) + + + For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request + + :param request: The network request you want to make. Required. + :type request: ~azure.core.rest.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to False. + :return: The response of your network call. Does not do error handling on your response. + :rtype: ~azure.core.rest.AsyncHttpResponse + """ + + request_copy = deepcopy(request) + request_copy.url = self._client.format_url(request_copy.url) + return self._client.send_request(request_copy, stream=stream, **kwargs) # type: ignore + + async def close(self) -> None: + await self._client.close() + + async def __aenter__(self) -> Self: + await self._client.__aenter__() + return self + + async def __aexit__(self, *exc_details: Any) -> None: + await self._client.__aexit__(*exc_details) diff --git a/src/azure/iot/hub/protocol/aio/_patch.py b/src/azure/iot/hub/protocol/aio/_patch.py new file mode 100644 index 0000000..87676c6 --- /dev/null +++ b/src/azure/iot/hub/protocol/aio/_patch.py @@ -0,0 +1,21 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------- +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" + + +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/src/azure/iot/hub/protocol/aio/operations/__init__.py b/src/azure/iot/hub/protocol/aio/operations/__init__.py new file mode 100644 index 0000000..d05751c --- /dev/null +++ b/src/azure/iot/hub/protocol/aio/operations/__init__.py @@ -0,0 +1,41 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._configuration_operations import ConfigurationOperations # type: ignore +from ._statistics_operations import StatisticsOperations # type: ignore +from ._devices_operations import DevicesOperations # type: ignore +from ._bulk_registry_operations import BulkRegistryOperations # type: ignore +from ._query_operations import QueryOperations # type: ignore +from ._jobs_operations import JobsOperations # type: ignore +from ._cloud_to_device_messages_operations import CloudToDeviceMessagesOperations # type: ignore +from ._modules_operations import ModulesOperations # type: ignore +from ._digital_twin_operations import DigitalTwinOperations # type: ignore + +from ._patch import __all__ as _patch_all +from ._patch import * +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "ConfigurationOperations", + "StatisticsOperations", + "DevicesOperations", + "BulkRegistryOperations", + "QueryOperations", + "JobsOperations", + "CloudToDeviceMessagesOperations", + "ModulesOperations", + "DigitalTwinOperations", +] +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore +_patch_sdk() diff --git a/src/azure/iot/hub/protocol/aio/operations/_bulk_registry_operations.py b/src/azure/iot/hub/protocol/aio/operations/_bulk_registry_operations.py new file mode 100644 index 0000000..7b67aff --- /dev/null +++ b/src/azure/iot/hub/protocol/aio/operations/_bulk_registry_operations.py @@ -0,0 +1,161 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from collections.abc import MutableMapping +from io import IOBase +from typing import Any, Callable, IO, Optional, TypeVar, Union, overload + +from azure.core import AsyncPipelineClient +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.rest import AsyncHttpResponse, HttpRequest +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict + +from ... import models as _models +from ..._utils.serialization import Deserializer, Serializer +from ...operations._bulk_registry_operations import build_update_registry_request +from .._configuration import IotHubGatewayServiceAPIsConfiguration + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] + + +class BulkRegistryOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.iot.hub.protocol.aio.IotHubGatewayServiceAPIs`'s + :attr:`bulk_registry` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: IotHubGatewayServiceAPIsConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @overload + async def update_registry( + self, devices: list[_models.ExportImportDevice], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.BulkRegistryOperationResult: + """Creates, updates, or deletes the identities of multiple devices from the IoT Hub identity + registry. A device identity can be specified only once in the list. Different operations + (create, update, delete) on different devices are allowed. A maximum of 100 devices can be + specified per invocation. For large scale operations, use the import feature using blob storage + (https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-identity-registry#import-and-export-device-identities). + + :param devices: The registry operations to perform. Required. + :type devices: list[~azure.iot.hub.protocol.models.ExportImportDevice] + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: BulkRegistryOperationResult or the result of cls(response) + :rtype: ~azure.iot.hub.protocol.models.BulkRegistryOperationResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def update_registry( + self, devices: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.BulkRegistryOperationResult: + """Creates, updates, or deletes the identities of multiple devices from the IoT Hub identity + registry. A device identity can be specified only once in the list. Different operations + (create, update, delete) on different devices are allowed. A maximum of 100 devices can be + specified per invocation. For large scale operations, use the import feature using blob storage + (https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-identity-registry#import-and-export-device-identities). + + :param devices: The registry operations to perform. Required. + :type devices: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: BulkRegistryOperationResult or the result of cls(response) + :rtype: ~azure.iot.hub.protocol.models.BulkRegistryOperationResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def update_registry( + self, devices: Union[list[_models.ExportImportDevice], IO[bytes]], **kwargs: Any + ) -> _models.BulkRegistryOperationResult: + """Creates, updates, or deletes the identities of multiple devices from the IoT Hub identity + registry. A device identity can be specified only once in the list. Different operations + (create, update, delete) on different devices are allowed. A maximum of 100 devices can be + specified per invocation. For large scale operations, use the import feature using blob storage + (https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-identity-registry#import-and-export-device-identities). + + :param devices: The registry operations to perform. Is either a [ExportImportDevice] type or a + IO[bytes] type. Required. + :type devices: list[~azure.iot.hub.protocol.models.ExportImportDevice] or IO[bytes] + :return: BulkRegistryOperationResult or the result of cls(response) + :rtype: ~azure.iot.hub.protocol.models.BulkRegistryOperationResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.BulkRegistryOperationResult] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(devices, (IOBase, bytes)): + _content = devices + else: + _json = self._serialize.body(devices, "[ExportImportDevice]") + + _request = build_update_registry_request( + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 400]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + deserialized = self._deserialize("BulkRegistryOperationResult", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore diff --git a/src/azure/iot/hub/protocol/aio/operations/_cloud_to_device_messages_operations.py b/src/azure/iot/hub/protocol/aio/operations/_cloud_to_device_messages_operations.py new file mode 100644 index 0000000..52a1ace --- /dev/null +++ b/src/azure/iot/hub/protocol/aio/operations/_cloud_to_device_messages_operations.py @@ -0,0 +1,249 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from collections.abc import MutableMapping +from typing import Any, Callable, Optional, TypeVar + +from azure.core import AsyncPipelineClient +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.rest import AsyncHttpResponse, HttpRequest +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict + +from ... import models as _models +from ..._utils.serialization import Deserializer, Serializer +from ...operations._cloud_to_device_messages_operations import ( + build_abandon_feedback_notification_request, + build_complete_feedback_notification_request, + build_purge_cloud_to_device_message_queue_request, + build_receive_feedback_notification_request, +) +from .._configuration import IotHubGatewayServiceAPIsConfiguration + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] + + +class CloudToDeviceMessagesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.iot.hub.protocol.aio.IotHubGatewayServiceAPIs`'s + :attr:`cloud_to_device_messages` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: IotHubGatewayServiceAPIsConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace_async + async def purge_cloud_to_device_message_queue(self, id: str, **kwargs: Any) -> _models.PurgeMessageQueueResult: + """Deletes all the pending commands for a device in the IoT Hub. + + :param id: The unique identifier of the device. Required. + :type id: str + :return: PurgeMessageQueueResult or the result of cls(response) + :rtype: ~azure.iot.hub.protocol.models.PurgeMessageQueueResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.PurgeMessageQueueResult] = kwargs.pop("cls", None) + + _request = build_purge_cloud_to_device_message_queue_request( + id=id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + deserialized = self._deserialize("PurgeMessageQueueResult", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def receive_feedback_notification(self, **kwargs: Any) -> None: + """Gets the feedback for cloud-to-device messages. See + https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-messaging for more information. This + capability is only available in the standard tier IoT Hub. For more information, see `Choose + the right IoT Hub tier `_. + + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_receive_feedback_notification_request( + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @distributed_trace_async + async def complete_feedback_notification(self, lock_token: str, **kwargs: Any) -> None: + """Completes the cloud-to-device feedback message. A completed message is deleted from the + feedback queue of the service. See + https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-messaging for more information. + + :param lock_token: The lock token obtained when the cloud-to-device message is received. This + is used to resolve race conditions when completing a feedback message. Required. + :type lock_token: str + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_complete_feedback_notification_request( + lock_token=lock_token, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @distributed_trace_async + async def abandon_feedback_notification(self, lock_token: str, **kwargs: Any) -> None: + """Abandons the lock on a cloud-to-device feedback message. See + https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-messaging for more information. + + :param lock_token: The lock token obtained when the cloud-to-device message is received. + Required. + :type lock_token: str + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_abandon_feedback_notification_request( + lock_token=lock_token, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore diff --git a/src/azure/iot/hub/protocol/aio/operations/_configuration_operations.py b/src/azure/iot/hub/protocol/aio/operations/_configuration_operations.py new file mode 100644 index 0000000..16041ee --- /dev/null +++ b/src/azure/iot/hub/protocol/aio/operations/_configuration_operations.py @@ -0,0 +1,543 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from collections.abc import MutableMapping +from io import IOBase +from typing import Any, Callable, IO, Optional, TypeVar, Union, overload + +from azure.core import AsyncPipelineClient +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.rest import AsyncHttpResponse, HttpRequest +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict + +from ... import models as _models +from ..._utils.serialization import Deserializer, Serializer +from ...operations._configuration_operations import ( + build_apply_on_edge_device_request, + build_create_or_update_request, + build_delete_request, + build_get_configurations_request, + build_get_request, + build_test_queries_request, +) +from .._configuration import IotHubGatewayServiceAPIsConfiguration + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] + + +class ConfigurationOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.iot.hub.protocol.aio.IotHubGatewayServiceAPIs`'s + :attr:`configuration` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: IotHubGatewayServiceAPIsConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace_async + async def get(self, id: str, **kwargs: Any) -> _models.Configuration: + """Gets a configuration on the IoT Hub for automatic device/module management. + + :param id: The unique identifier of the configuration. Required. + :type id: str + :return: Configuration or the result of cls(response) + :rtype: ~azure.iot.hub.protocol.models.Configuration + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.Configuration] = kwargs.pop("cls", None) + + _request = build_get_request( + id=id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + deserialized = self._deserialize("Configuration", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def create_or_update( + self, + id: str, + configuration: _models.Configuration, + if_match: Optional[str] = None, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Configuration: + """Creates or updates a configuration on the IoT Hub for automatic device/module management. + Configuration identifier and Content cannot be updated. + + :param id: The unique identifier of the configuration. Required. + :type id: str + :param configuration: The configuration to be created or updated. Required. + :type configuration: ~azure.iot.hub.protocol.models.Configuration + :param if_match: The string representing a weak ETag for the configuration, as per RFC7232. + This should not be set when creating a configuration, but may be set when updating a + configuration. Default value is None. + :type if_match: str + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: Configuration or the result of cls(response) + :rtype: ~azure.iot.hub.protocol.models.Configuration + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_or_update( + self, + id: str, + configuration: IO[bytes], + if_match: Optional[str] = None, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Configuration: + """Creates or updates a configuration on the IoT Hub for automatic device/module management. + Configuration identifier and Content cannot be updated. + + :param id: The unique identifier of the configuration. Required. + :type id: str + :param configuration: The configuration to be created or updated. Required. + :type configuration: IO[bytes] + :param if_match: The string representing a weak ETag for the configuration, as per RFC7232. + This should not be set when creating a configuration, but may be set when updating a + configuration. Default value is None. + :type if_match: str + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: Configuration or the result of cls(response) + :rtype: ~azure.iot.hub.protocol.models.Configuration + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create_or_update( + self, + id: str, + configuration: Union[_models.Configuration, IO[bytes]], + if_match: Optional[str] = None, + **kwargs: Any + ) -> _models.Configuration: + """Creates or updates a configuration on the IoT Hub for automatic device/module management. + Configuration identifier and Content cannot be updated. + + :param id: The unique identifier of the configuration. Required. + :type id: str + :param configuration: The configuration to be created or updated. Is either a Configuration + type or a IO[bytes] type. Required. + :type configuration: ~azure.iot.hub.protocol.models.Configuration or IO[bytes] + :param if_match: The string representing a weak ETag for the configuration, as per RFC7232. + This should not be set when creating a configuration, but may be set when updating a + configuration. Default value is None. + :type if_match: str + :return: Configuration or the result of cls(response) + :rtype: ~azure.iot.hub.protocol.models.Configuration + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.Configuration] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(configuration, (IOBase, bytes)): + _content = configuration + else: + _json = self._serialize.body(configuration, "Configuration") + + _request = build_create_or_update_request( + id=id, + if_match=if_match, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + deserialized = self._deserialize("Configuration", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def delete(self, id: str, if_match: Optional[str] = None, **kwargs: Any) -> None: + """Deletes a configuration on the IoT Hub for automatic device/module management. + + :param id: The unique identifier of the configuration. Required. + :type id: str + :param if_match: The string representing a weak ETag for the configuration, as per RFC7232. The + delete operation is performed only if this ETag matches the value maintained by the server, + indicating that the configuration has not been modified since it was last retrieved. To force + an unconditional delete, set If-Match to the wildcard character (*). Default value is None. + :type if_match: str + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_delete_request( + id=id, + if_match=if_match, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @distributed_trace_async + async def get_configurations(self, top: Optional[int] = None, **kwargs: Any) -> list[_models.Configuration]: + """Gets configurations on the IoT Hub for automatic device/module management. Pagination is not + supported. + + :param top: The number of configurations to retrieve. Value will be overridden if greater than + the maximum deployment count for the IoT Hub. Default value is None. + :type top: int + :return: list of Configuration or the result of cls(response) + :rtype: list[~azure.iot.hub.protocol.models.Configuration] + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[list[_models.Configuration]] = kwargs.pop("cls", None) + + _request = build_get_configurations_request( + top=top, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + deserialized = self._deserialize("[Configuration]", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def test_queries( + self, input: _models.ConfigurationQueriesTestInput, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.ConfigurationQueriesTestResponse: + """Validates target condition and custom metric queries for a configuration on the IoT Hub. + + :param input: The configuration for target condition and custom metric queries. Required. + :type input: ~azure.iot.hub.protocol.models.ConfigurationQueriesTestInput + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: ConfigurationQueriesTestResponse or the result of cls(response) + :rtype: ~azure.iot.hub.protocol.models.ConfigurationQueriesTestResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def test_queries( + self, input: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.ConfigurationQueriesTestResponse: + """Validates target condition and custom metric queries for a configuration on the IoT Hub. + + :param input: The configuration for target condition and custom metric queries. Required. + :type input: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: ConfigurationQueriesTestResponse or the result of cls(response) + :rtype: ~azure.iot.hub.protocol.models.ConfigurationQueriesTestResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def test_queries( + self, input: Union[_models.ConfigurationQueriesTestInput, IO[bytes]], **kwargs: Any + ) -> _models.ConfigurationQueriesTestResponse: + """Validates target condition and custom metric queries for a configuration on the IoT Hub. + + :param input: The configuration for target condition and custom metric queries. Is either a + ConfigurationQueriesTestInput type or a IO[bytes] type. Required. + :type input: ~azure.iot.hub.protocol.models.ConfigurationQueriesTestInput or IO[bytes] + :return: ConfigurationQueriesTestResponse or the result of cls(response) + :rtype: ~azure.iot.hub.protocol.models.ConfigurationQueriesTestResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.ConfigurationQueriesTestResponse] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(input, (IOBase, bytes)): + _content = input + else: + _json = self._serialize.body(input, "ConfigurationQueriesTestInput") + + _request = build_test_queries_request( + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + deserialized = self._deserialize("ConfigurationQueriesTestResponse", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def apply_on_edge_device( + self, id: str, content: _models.ConfigurationContent, *, content_type: str = "application/json", **kwargs: Any + ) -> None: + """Applies the configuration content to an edge device. + + :param id: The unique identifier of the edge device. Required. + :type id: str + :param content: The configuration content. Required. + :type content: ~azure.iot.hub.protocol.models.ConfigurationContent + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def apply_on_edge_device( + self, id: str, content: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> None: + """Applies the configuration content to an edge device. + + :param id: The unique identifier of the edge device. Required. + :type id: str + :param content: The configuration content. Required. + :type content: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def apply_on_edge_device( + self, id: str, content: Union[_models.ConfigurationContent, IO[bytes]], **kwargs: Any + ) -> None: + """Applies the configuration content to an edge device. + + :param id: The unique identifier of the edge device. Required. + :type id: str + :param content: The configuration content. Is either a ConfigurationContent type or a IO[bytes] + type. Required. + :type content: ~azure.iot.hub.protocol.models.ConfigurationContent or IO[bytes] + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[None] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(content, (IOBase, bytes)): + _content = content + else: + _json = self._serialize.body(content, "ConfigurationContent") + + _request = build_apply_on_edge_device_request( + id=id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore diff --git a/src/azure/iot/hub/protocol/aio/operations/_devices_operations.py b/src/azure/iot/hub/protocol/aio/operations/_devices_operations.py new file mode 100644 index 0000000..cfd92ab --- /dev/null +++ b/src/azure/iot/hub/protocol/aio/operations/_devices_operations.py @@ -0,0 +1,768 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from collections.abc import MutableMapping +from io import IOBase +from typing import Any, Callable, IO, Optional, TypeVar, Union, overload + +from azure.core import AsyncPipelineClient +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.rest import AsyncHttpResponse, HttpRequest +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict + +from ... import models as _models +from ..._utils.serialization import Deserializer, Serializer +from ...operations._devices_operations import ( + build_create_or_update_identity_request, + build_delete_identity_request, + build_get_devices_request, + build_get_identity_request, + build_get_twin_request, + build_invoke_method_request, + build_replace_twin_request, + build_update_twin_request, +) +from .._configuration import IotHubGatewayServiceAPIsConfiguration + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] + + +class DevicesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.iot.hub.protocol.aio.IotHubGatewayServiceAPIs`'s + :attr:`devices` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: IotHubGatewayServiceAPIsConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace_async + async def get_devices(self, top: Optional[int] = None, **kwargs: Any) -> list[_models.Device]: + """Gets the identities of multiple devices from the IoT Hub identity registry. Not recommended. + Use the IoT Hub query API to retrieve device twin and device identity information. See + https://docs.microsoft.com/en-us/rest/api/iothub/service/queryiothub and + https://docs.microsoft.com/en-us/azure/iot-hub/iot-hub-devguide-query-language for more + information. + + :param top: The maximum number of device identities returned by the query. Any value outside + the range of 1-1000 is considered to be 1000. Default value is None. + :type top: int + :return: list of Device or the result of cls(response) + :rtype: list[~azure.iot.hub.protocol.models.Device] + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[list[_models.Device]] = kwargs.pop("cls", None) + + _request = build_get_devices_request( + top=top, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + deserialized = self._deserialize("[Device]", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def get_identity(self, id: str, **kwargs: Any) -> _models.Device: + """Gets a device from the identity registry of the IoT Hub. + + :param id: The unique identifier of the device. Required. + :type id: str + :return: Device or the result of cls(response) + :rtype: ~azure.iot.hub.protocol.models.Device + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.Device] = kwargs.pop("cls", None) + + _request = build_get_identity_request( + id=id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + deserialized = self._deserialize("Device", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def create_or_update_identity( + self, + id: str, + device: _models.Device, + if_match: Optional[str] = None, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Device: + """Creates or updates the identity of a device in the identity registry of the IoT Hub. + + :param id: The unique identifier of the device. Required. + :type id: str + :param device: The contents of the device identity. Required. + :type device: ~azure.iot.hub.protocol.models.Device + :param if_match: The string representing a weak ETag for the device identity, as per RFC7232. + This should not be set when creating a device, but may be set when updating a device. Default + value is None. + :type if_match: str + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: Device or the result of cls(response) + :rtype: ~azure.iot.hub.protocol.models.Device + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_or_update_identity( + self, + id: str, + device: IO[bytes], + if_match: Optional[str] = None, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Device: + """Creates or updates the identity of a device in the identity registry of the IoT Hub. + + :param id: The unique identifier of the device. Required. + :type id: str + :param device: The contents of the device identity. Required. + :type device: IO[bytes] + :param if_match: The string representing a weak ETag for the device identity, as per RFC7232. + This should not be set when creating a device, but may be set when updating a device. Default + value is None. + :type if_match: str + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: Device or the result of cls(response) + :rtype: ~azure.iot.hub.protocol.models.Device + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create_or_update_identity( + self, id: str, device: Union[_models.Device, IO[bytes]], if_match: Optional[str] = None, **kwargs: Any + ) -> _models.Device: + """Creates or updates the identity of a device in the identity registry of the IoT Hub. + + :param id: The unique identifier of the device. Required. + :type id: str + :param device: The contents of the device identity. Is either a Device type or a IO[bytes] + type. Required. + :type device: ~azure.iot.hub.protocol.models.Device or IO[bytes] + :param if_match: The string representing a weak ETag for the device identity, as per RFC7232. + This should not be set when creating a device, but may be set when updating a device. Default + value is None. + :type if_match: str + :return: Device or the result of cls(response) + :rtype: ~azure.iot.hub.protocol.models.Device + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.Device] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(device, (IOBase, bytes)): + _content = device + else: + _json = self._serialize.body(device, "Device") + + _request = build_create_or_update_identity_request( + id=id, + if_match=if_match, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + deserialized = self._deserialize("Device", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def delete_identity(self, id: str, if_match: Optional[str] = None, **kwargs: Any) -> None: + """Deletes the identity of a device from the identity registry of the IoT Hub. + + :param id: The unique identifier of the device. Required. + :type id: str + :param if_match: The string representing a weak ETag for the device identity, as per RFC7232. + The delete operation is performed only if this ETag matches the value maintained by the server, + indicating that the device identity has not been modified since it was last retrieved. To force + an unconditional delete, set If-Match to the wildcard character (*). Default value is None. + :type if_match: str + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_delete_identity_request( + id=id, + if_match=if_match, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @distributed_trace_async + async def get_twin(self, id: str, **kwargs: Any) -> _models.Twin: + """Gets the device twin. See + https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-device-twins for more information. + + :param id: The unique identifier of the device. Required. + :type id: str + :return: Twin or the result of cls(response) + :rtype: ~azure.iot.hub.protocol.models.Twin + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.Twin] = kwargs.pop("cls", None) + + _request = build_get_twin_request( + id=id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + deserialized = self._deserialize("Twin", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def replace_twin( + self, + id: str, + device_twin_info: _models.Twin, + if_match: Optional[str] = None, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Twin: + """Replaces the tags and desired properties of a device twin. See + https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-device-twins for more information. + + :param id: The unique identifier of the device. Required. + :type id: str + :param device_twin_info: The device twin info that will replace the existing info. Required. + :type device_twin_info: ~azure.iot.hub.protocol.models.Twin + :param if_match: The string representing a weak ETag for the device twin, as per RFC7232. It + determines if the replace operation should be carried out. Default value is None. + :type if_match: str + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: Twin or the result of cls(response) + :rtype: ~azure.iot.hub.protocol.models.Twin + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def replace_twin( + self, + id: str, + device_twin_info: IO[bytes], + if_match: Optional[str] = None, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Twin: + """Replaces the tags and desired properties of a device twin. See + https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-device-twins for more information. + + :param id: The unique identifier of the device. Required. + :type id: str + :param device_twin_info: The device twin info that will replace the existing info. Required. + :type device_twin_info: IO[bytes] + :param if_match: The string representing a weak ETag for the device twin, as per RFC7232. It + determines if the replace operation should be carried out. Default value is None. + :type if_match: str + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: Twin or the result of cls(response) + :rtype: ~azure.iot.hub.protocol.models.Twin + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def replace_twin( + self, id: str, device_twin_info: Union[_models.Twin, IO[bytes]], if_match: Optional[str] = None, **kwargs: Any + ) -> _models.Twin: + """Replaces the tags and desired properties of a device twin. See + https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-device-twins for more information. + + :param id: The unique identifier of the device. Required. + :type id: str + :param device_twin_info: The device twin info that will replace the existing info. Is either a + Twin type or a IO[bytes] type. Required. + :type device_twin_info: ~azure.iot.hub.protocol.models.Twin or IO[bytes] + :param if_match: The string representing a weak ETag for the device twin, as per RFC7232. It + determines if the replace operation should be carried out. Default value is None. + :type if_match: str + :return: Twin or the result of cls(response) + :rtype: ~azure.iot.hub.protocol.models.Twin + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.Twin] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(device_twin_info, (IOBase, bytes)): + _content = device_twin_info + else: + _json = self._serialize.body(device_twin_info, "Twin") + + _request = build_replace_twin_request( + id=id, + if_match=if_match, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + deserialized = self._deserialize("Twin", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def update_twin( + self, + id: str, + device_twin_info: _models.Twin, + if_match: Optional[str] = None, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Twin: + """Updates the tags and desired properties of a device twin. See + https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-device-twins for more information. + + :param id: The unique identifier of the device. Required. + :type id: str + :param device_twin_info: The device twin info containing the tags and desired properties to be + updated. Required. + :type device_twin_info: ~azure.iot.hub.protocol.models.Twin + :param if_match: The string representing a weak ETag for the device twin, as per RFC7232. It + determines if the update operation should be carried out. Default value is None. + :type if_match: str + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: Twin or the result of cls(response) + :rtype: ~azure.iot.hub.protocol.models.Twin + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def update_twin( + self, + id: str, + device_twin_info: IO[bytes], + if_match: Optional[str] = None, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Twin: + """Updates the tags and desired properties of a device twin. See + https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-device-twins for more information. + + :param id: The unique identifier of the device. Required. + :type id: str + :param device_twin_info: The device twin info containing the tags and desired properties to be + updated. Required. + :type device_twin_info: IO[bytes] + :param if_match: The string representing a weak ETag for the device twin, as per RFC7232. It + determines if the update operation should be carried out. Default value is None. + :type if_match: str + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: Twin or the result of cls(response) + :rtype: ~azure.iot.hub.protocol.models.Twin + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def update_twin( + self, id: str, device_twin_info: Union[_models.Twin, IO[bytes]], if_match: Optional[str] = None, **kwargs: Any + ) -> _models.Twin: + """Updates the tags and desired properties of a device twin. See + https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-device-twins for more information. + + :param id: The unique identifier of the device. Required. + :type id: str + :param device_twin_info: The device twin info containing the tags and desired properties to be + updated. Is either a Twin type or a IO[bytes] type. Required. + :type device_twin_info: ~azure.iot.hub.protocol.models.Twin or IO[bytes] + :param if_match: The string representing a weak ETag for the device twin, as per RFC7232. It + determines if the update operation should be carried out. Default value is None. + :type if_match: str + :return: Twin or the result of cls(response) + :rtype: ~azure.iot.hub.protocol.models.Twin + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.Twin] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(device_twin_info, (IOBase, bytes)): + _content = device_twin_info + else: + _json = self._serialize.body(device_twin_info, "Twin") + + _request = build_update_twin_request( + id=id, + if_match=if_match, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + deserialized = self._deserialize("Twin", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def invoke_method( + self, + device_id: str, + direct_method_request: _models.CloudToDeviceMethod, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.CloudToDeviceMethodResult: + """Invokes a direct method on a device. See + https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-direct-methods for more information. + + :param device_id: The unique identifier of the device. Required. + :type device_id: str + :param direct_method_request: The parameters to execute a direct method on the device. + Required. + :type direct_method_request: ~azure.iot.hub.protocol.models.CloudToDeviceMethod + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: CloudToDeviceMethodResult or the result of cls(response) + :rtype: ~azure.iot.hub.protocol.models.CloudToDeviceMethodResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def invoke_method( + self, device_id: str, direct_method_request: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.CloudToDeviceMethodResult: + """Invokes a direct method on a device. See + https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-direct-methods for more information. + + :param device_id: The unique identifier of the device. Required. + :type device_id: str + :param direct_method_request: The parameters to execute a direct method on the device. + Required. + :type direct_method_request: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: CloudToDeviceMethodResult or the result of cls(response) + :rtype: ~azure.iot.hub.protocol.models.CloudToDeviceMethodResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def invoke_method( + self, device_id: str, direct_method_request: Union[_models.CloudToDeviceMethod, IO[bytes]], **kwargs: Any + ) -> _models.CloudToDeviceMethodResult: + """Invokes a direct method on a device. See + https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-direct-methods for more information. + + :param device_id: The unique identifier of the device. Required. + :type device_id: str + :param direct_method_request: The parameters to execute a direct method on the device. Is + either a CloudToDeviceMethod type or a IO[bytes] type. Required. + :type direct_method_request: ~azure.iot.hub.protocol.models.CloudToDeviceMethod or IO[bytes] + :return: CloudToDeviceMethodResult or the result of cls(response) + :rtype: ~azure.iot.hub.protocol.models.CloudToDeviceMethodResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.CloudToDeviceMethodResult] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(direct_method_request, (IOBase, bytes)): + _content = direct_method_request + else: + _json = self._serialize.body(direct_method_request, "CloudToDeviceMethod") + + _request = build_invoke_method_request( + device_id=device_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + deserialized = self._deserialize("CloudToDeviceMethodResult", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore diff --git a/src/azure/iot/hub/protocol/aio/operations/_digital_twin_operations.py b/src/azure/iot/hub/protocol/aio/operations/_digital_twin_operations.py new file mode 100644 index 0000000..3753125 --- /dev/null +++ b/src/azure/iot/hub/protocol/aio/operations/_digital_twin_operations.py @@ -0,0 +1,413 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from collections.abc import MutableMapping +from io import IOBase +from typing import Any, Callable, IO, Optional, TypeVar, Union, overload + +from azure.core import AsyncPipelineClient +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.rest import AsyncHttpResponse, HttpRequest +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict + +from ... import models as _models +from ..._utils.serialization import Deserializer, Serializer +from ...operations._digital_twin_operations import ( + build_get_digital_twin_request, + build_invoke_component_command_request, + build_invoke_root_level_command_request, + build_update_digital_twin_request, +) +from .._configuration import IotHubGatewayServiceAPIsConfiguration + +JSON = MutableMapping[str, Any] +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] + + +class DigitalTwinOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.iot.hub.protocol.aio.IotHubGatewayServiceAPIs`'s + :attr:`digital_twin` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: IotHubGatewayServiceAPIsConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace_async + async def get_digital_twin(self, id: str, **kwargs: Any) -> JSON: + """Gets a digital twin. + + Gets a digital twin. + + :param id: Digital Twin ID. Required. + :type id: str + :return: JSON or the result of cls(response) + :rtype: JSON + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[JSON] = kwargs.pop("cls", None) + + _request = build_get_digital_twin_request( + id=id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + response_headers = {} + response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) + + deserialized = self._deserialize("object", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @overload + async def update_digital_twin( + self, + id: str, + digital_twin_patch: list[JSON], + if_match: Optional[str] = None, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> None: + """Updates a digital twin. + + Updates a digital twin. + + :param id: Digital Twin ID. Required. + :type id: str + :param digital_twin_patch: json-patch contents to update. Required. + :type digital_twin_patch: list[JSON] + :param if_match: Default value is None. + :type if_match: str + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def update_digital_twin( + self, + id: str, + digital_twin_patch: IO[bytes], + if_match: Optional[str] = None, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> None: + """Updates a digital twin. + + Updates a digital twin. + + :param id: Digital Twin ID. Required. + :type id: str + :param digital_twin_patch: json-patch contents to update. Required. + :type digital_twin_patch: IO[bytes] + :param if_match: Default value is None. + :type if_match: str + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def update_digital_twin( + self, id: str, digital_twin_patch: Union[list[JSON], IO[bytes]], if_match: Optional[str] = None, **kwargs: Any + ) -> None: + """Updates a digital twin. + + Updates a digital twin. + + :param id: Digital Twin ID. Required. + :type id: str + :param digital_twin_patch: json-patch contents to update. Is either a [JSON] type or a + IO[bytes] type. Required. + :type digital_twin_patch: list[JSON] or IO[bytes] + :param if_match: Default value is None. + :type if_match: str + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[None] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(digital_twin_patch, (IOBase, bytes)): + _content = digital_twin_patch + else: + _json = self._serialize.body(digital_twin_patch, "[object]") + + _request = build_update_digital_twin_request( + id=id, + if_match=if_match, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + response_headers = {} + response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + + if cls: + return cls(pipeline_response, None, response_headers) # type: ignore + + @distributed_trace_async + async def invoke_root_level_command( + self, + id: str, + command_name: str, + payload: JSON, + connect_timeout_in_seconds: Optional[int] = None, + response_timeout_in_seconds: Optional[int] = None, + **kwargs: Any + ) -> JSON: + """Invoke a digital twin root level command. + + Invoke a digital twin root level command. + + :param id: Required. + :type id: str + :param command_name: Required. + :type command_name: str + :param payload: Required. + :type payload: JSON + :param connect_timeout_in_seconds: Maximum interval of time, in seconds, that the digital twin + command will wait for the answer. Default value is None. + :type connect_timeout_in_seconds: int + :param response_timeout_in_seconds: Maximum interval of time, in seconds, that the digital twin + command will wait for the answer. Default value is None. + :type response_timeout_in_seconds: int + :return: JSON or the result of cls(response) + :rtype: JSON + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: str = kwargs.pop("content_type", _headers.pop("Content-Type", "application/json")) + cls: ClsType[JSON] = kwargs.pop("cls", None) + + _json = self._serialize.body(payload, "object") + + _request = build_invoke_root_level_command_request( + id=id, + command_name=command_name, + connect_timeout_in_seconds=connect_timeout_in_seconds, + response_timeout_in_seconds=response_timeout_in_seconds, + api_version=api_version, + content_type=content_type, + json=_json, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + response_headers = {} + response_headers["x-ms-command-statuscode"] = self._deserialize( + "int", response.headers.get("x-ms-command-statuscode") + ) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + + deserialized = self._deserialize("object", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def invoke_component_command( + self, + id: str, + component_path: str, + command_name: str, + payload: JSON, + connect_timeout_in_seconds: Optional[int] = None, + response_timeout_in_seconds: Optional[int] = None, + **kwargs: Any + ) -> JSON: + """Invoke a digital twin command. + + Invoke a digital twin command. + + :param id: Required. + :type id: str + :param component_path: Required. + :type component_path: str + :param command_name: Required. + :type command_name: str + :param payload: Required. + :type payload: JSON + :param connect_timeout_in_seconds: Maximum interval of time, in seconds, that the digital twin + command will wait for the answer. Default value is None. + :type connect_timeout_in_seconds: int + :param response_timeout_in_seconds: Maximum interval of time, in seconds, that the digital twin + command will wait for the answer. Default value is None. + :type response_timeout_in_seconds: int + :return: JSON or the result of cls(response) + :rtype: JSON + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: str = kwargs.pop("content_type", _headers.pop("Content-Type", "application/json")) + cls: ClsType[JSON] = kwargs.pop("cls", None) + + _json = self._serialize.body(payload, "object") + + _request = build_invoke_component_command_request( + id=id, + component_path=component_path, + command_name=command_name, + connect_timeout_in_seconds=connect_timeout_in_seconds, + response_timeout_in_seconds=response_timeout_in_seconds, + api_version=api_version, + content_type=content_type, + json=_json, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + response_headers = {} + response_headers["x-ms-command-statuscode"] = self._deserialize( + "int", response.headers.get("x-ms-command-statuscode") + ) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + + deserialized = self._deserialize("object", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore diff --git a/src/azure/iot/hub/protocol/aio/operations/_jobs_operations.py b/src/azure/iot/hub/protocol/aio/operations/_jobs_operations.py new file mode 100644 index 0000000..af7574b --- /dev/null +++ b/src/azure/iot/hub/protocol/aio/operations/_jobs_operations.py @@ -0,0 +1,589 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from collections.abc import MutableMapping +from io import IOBase +from typing import Any, Callable, IO, Optional, TypeVar, Union, overload + +from azure.core import AsyncPipelineClient +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.rest import AsyncHttpResponse, HttpRequest +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict + +from ... import models as _models +from ..._utils.serialization import Deserializer, Serializer +from ...operations._jobs_operations import ( + build_cancel_import_export_job_request, + build_cancel_scheduled_job_request, + build_create_import_export_job_request, + build_create_scheduled_job_request, + build_get_import_export_job_request, + build_get_import_export_jobs_request, + build_get_scheduled_job_request, + build_query_scheduled_jobs_request, +) +from .._configuration import IotHubGatewayServiceAPIsConfiguration + +JSON = MutableMapping[str, Any] +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] + + +class JobsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.iot.hub.protocol.aio.IotHubGatewayServiceAPIs`'s + :attr:`jobs` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: IotHubGatewayServiceAPIsConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @overload + async def create_import_export_job( + self, job_properties: _models.JobProperties, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.JobProperties: + """Creates a new import or export job on the IoT Hub. See + https://docs.microsoft.com/en-us/azure/iot-hub/iot-hub-devguide-identity-registry#import-and-export-device-identities + for more information. + + :param job_properties: The job specifications. Required. + :type job_properties: ~azure.iot.hub.protocol.models.JobProperties + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: JobProperties or the result of cls(response) + :rtype: ~azure.iot.hub.protocol.models.JobProperties + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_import_export_job( + self, job_properties: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.JobProperties: + """Creates a new import or export job on the IoT Hub. See + https://docs.microsoft.com/en-us/azure/iot-hub/iot-hub-devguide-identity-registry#import-and-export-device-identities + for more information. + + :param job_properties: The job specifications. Required. + :type job_properties: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: JobProperties or the result of cls(response) + :rtype: ~azure.iot.hub.protocol.models.JobProperties + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create_import_export_job( + self, job_properties: Union[_models.JobProperties, IO[bytes]], **kwargs: Any + ) -> _models.JobProperties: + """Creates a new import or export job on the IoT Hub. See + https://docs.microsoft.com/en-us/azure/iot-hub/iot-hub-devguide-identity-registry#import-and-export-device-identities + for more information. + + :param job_properties: The job specifications. Is either a JobProperties type or a IO[bytes] + type. Required. + :type job_properties: ~azure.iot.hub.protocol.models.JobProperties or IO[bytes] + :return: JobProperties or the result of cls(response) + :rtype: ~azure.iot.hub.protocol.models.JobProperties + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.JobProperties] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(job_properties, (IOBase, bytes)): + _content = job_properties + else: + _json = self._serialize.body(job_properties, "JobProperties") + + _request = build_create_import_export_job_request( + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + deserialized = self._deserialize("JobProperties", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def get_import_export_jobs(self, **kwargs: Any) -> list[_models.JobProperties]: + """Gets the status of all import and export jobs in the IoT Hub. See + https://docs.microsoft.com/en-us/azure/iot-hub/iot-hub-devguide-identity-registry#import-and-export-device-identities + for more information. + + :return: list of JobProperties or the result of cls(response) + :rtype: list[~azure.iot.hub.protocol.models.JobProperties] + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[list[_models.JobProperties]] = kwargs.pop("cls", None) + + _request = build_get_import_export_jobs_request( + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + deserialized = self._deserialize("[JobProperties]", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def get_import_export_job(self, id: str, **kwargs: Any) -> _models.JobProperties: + """Gets the status of an import or export job in the IoT Hub. See + https://docs.microsoft.com/en-us/azure/iot-hub/iot-hub-devguide-identity-registry#import-and-export-device-identities + for more information. + + :param id: The unique identifier of the job. Required. + :type id: str + :return: JobProperties or the result of cls(response) + :rtype: ~azure.iot.hub.protocol.models.JobProperties + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.JobProperties] = kwargs.pop("cls", None) + + _request = build_get_import_export_job_request( + id=id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + deserialized = self._deserialize("JobProperties", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def cancel_import_export_job(self, id: str, **kwargs: Any) -> Optional[JSON]: + """Cancels an import or export job in the IoT Hub. + + :param id: The unique identifier of the job. Required. + :type id: str + :return: JSON or None or the result of cls(response) + :rtype: JSON or None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[Optional[JSON]] = kwargs.pop("cls", None) + + _request = build_cancel_import_export_job_request( + id=id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + deserialized = None + if response.status_code == 200: + deserialized = self._deserialize("object", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def get_scheduled_job(self, id: str, **kwargs: Any) -> _models.JobResponse: + """Gets details of a scheduled job from the IoT Hub. See + https://docs.microsoft.com/en-us/azure/iot-hub/iot-hub-devguide-jobs for more information. + + :param id: The unique identifier of the job. Required. + :type id: str + :return: JobResponse or the result of cls(response) + :rtype: ~azure.iot.hub.protocol.models.JobResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.JobResponse] = kwargs.pop("cls", None) + + _request = build_get_scheduled_job_request( + id=id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + deserialized = self._deserialize("JobResponse", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def create_scheduled_job( + self, id: str, job_request: _models.JobRequest, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.JobResponse: + """Creates a new job to schedule twin updates or direct methods on the IoT Hub at a scheduled + time. See https://docs.microsoft.com/en-us/azure/iot-hub/iot-hub-devguide-jobs for more + information. + + :param id: The unique identifier of the job. Required. + :type id: str + :param job_request: The job request info. Required. + :type job_request: ~azure.iot.hub.protocol.models.JobRequest + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: JobResponse or the result of cls(response) + :rtype: ~azure.iot.hub.protocol.models.JobResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_scheduled_job( + self, id: str, job_request: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.JobResponse: + """Creates a new job to schedule twin updates or direct methods on the IoT Hub at a scheduled + time. See https://docs.microsoft.com/en-us/azure/iot-hub/iot-hub-devguide-jobs for more + information. + + :param id: The unique identifier of the job. Required. + :type id: str + :param job_request: The job request info. Required. + :type job_request: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: JobResponse or the result of cls(response) + :rtype: ~azure.iot.hub.protocol.models.JobResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create_scheduled_job( + self, id: str, job_request: Union[_models.JobRequest, IO[bytes]], **kwargs: Any + ) -> _models.JobResponse: + """Creates a new job to schedule twin updates or direct methods on the IoT Hub at a scheduled + time. See https://docs.microsoft.com/en-us/azure/iot-hub/iot-hub-devguide-jobs for more + information. + + :param id: The unique identifier of the job. Required. + :type id: str + :param job_request: The job request info. Is either a JobRequest type or a IO[bytes] type. + Required. + :type job_request: ~azure.iot.hub.protocol.models.JobRequest or IO[bytes] + :return: JobResponse or the result of cls(response) + :rtype: ~azure.iot.hub.protocol.models.JobResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.JobResponse] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(job_request, (IOBase, bytes)): + _content = job_request + else: + _json = self._serialize.body(job_request, "JobRequest") + + _request = build_create_scheduled_job_request( + id=id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + deserialized = self._deserialize("JobResponse", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def cancel_scheduled_job(self, id: str, **kwargs: Any) -> _models.JobResponse: + """Cancels a scheduled job on the IoT Hub. See + https://docs.microsoft.com/en-us/azure/iot-hub/iot-hub-devguide-jobs for more information. + + :param id: The unique identifier of the job. Required. + :type id: str + :return: JobResponse or the result of cls(response) + :rtype: ~azure.iot.hub.protocol.models.JobResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.JobResponse] = kwargs.pop("cls", None) + + _request = build_cancel_scheduled_job_request( + id=id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + deserialized = self._deserialize("JobResponse", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def query_scheduled_jobs( + self, job_type: Optional[str] = None, job_status: Optional[str] = None, **kwargs: Any + ) -> _models.QueryResult: + """Gets the information about jobs using an IoT Hub query. See + https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-query-language for more information. + + :param job_type: The job type. See + https://docs.microsoft.com/en-us/azure/iot-hub/iot-hub-devguide-jobs#querying-for-progress-on-jobs + for a list of possible job types. Default value is None. + :type job_type: str + :param job_status: The job status. See + https://docs.microsoft.com/en-us/azure/iot-hub/iot-hub-devguide-jobs#querying-for-progress-on-jobs + for a list of possible statuses. Default value is None. + :type job_status: str + :return: QueryResult or the result of cls(response) + :rtype: ~azure.iot.hub.protocol.models.QueryResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.QueryResult] = kwargs.pop("cls", None) + + _request = build_query_scheduled_jobs_request( + job_type=job_type, + job_status=job_status, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + deserialized = self._deserialize("QueryResult", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore diff --git a/src/azure/iot/hub/protocol/aio/operations/_modules_operations.py b/src/azure/iot/hub/protocol/aio/operations/_modules_operations.py new file mode 100644 index 0000000..3786317 --- /dev/null +++ b/src/azure/iot/hub/protocol/aio/operations/_modules_operations.py @@ -0,0 +1,829 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from collections.abc import MutableMapping +from io import IOBase +from typing import Any, Callable, IO, Optional, TypeVar, Union, overload + +from azure.core import AsyncPipelineClient +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.rest import AsyncHttpResponse, HttpRequest +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict + +from ... import models as _models +from ..._utils.serialization import Deserializer, Serializer +from ...operations._modules_operations import ( + build_create_or_update_identity_request, + build_delete_identity_request, + build_get_identity_request, + build_get_modules_on_device_request, + build_get_twin_request, + build_invoke_method_request, + build_replace_twin_request, + build_update_twin_request, +) +from .._configuration import IotHubGatewayServiceAPIsConfiguration + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] + + +class ModulesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.iot.hub.protocol.aio.IotHubGatewayServiceAPIs`'s + :attr:`modules` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: IotHubGatewayServiceAPIsConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace_async + async def get_twin(self, id: str, mid: str, **kwargs: Any) -> _models.Twin: + """Gets the module twin. See + https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-device-twins for more information. + + :param id: The unique identifier of the device. Required. + :type id: str + :param mid: The unique identifier of the module. Required. + :type mid: str + :return: Twin or the result of cls(response) + :rtype: ~azure.iot.hub.protocol.models.Twin + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.Twin] = kwargs.pop("cls", None) + + _request = build_get_twin_request( + id=id, + mid=mid, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + deserialized = self._deserialize("Twin", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def replace_twin( + self, + id: str, + mid: str, + device_twin_info: _models.Twin, + if_match: Optional[str] = None, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Twin: + """Replaces the tags and desired properties of a module twin. See + https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-device-twins for more information. + + :param id: The unique identifier of the device. Required. + :type id: str + :param mid: The unique identifier of the module. Required. + :type mid: str + :param device_twin_info: The module twin info that will replace the existing info. Required. + :type device_twin_info: ~azure.iot.hub.protocol.models.Twin + :param if_match: The string representing a weak ETag for the device twin, as per RFC7232. It + determines if the replace operation should be carried out. Default value is None. + :type if_match: str + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: Twin or the result of cls(response) + :rtype: ~azure.iot.hub.protocol.models.Twin + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def replace_twin( + self, + id: str, + mid: str, + device_twin_info: IO[bytes], + if_match: Optional[str] = None, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Twin: + """Replaces the tags and desired properties of a module twin. See + https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-device-twins for more information. + + :param id: The unique identifier of the device. Required. + :type id: str + :param mid: The unique identifier of the module. Required. + :type mid: str + :param device_twin_info: The module twin info that will replace the existing info. Required. + :type device_twin_info: IO[bytes] + :param if_match: The string representing a weak ETag for the device twin, as per RFC7232. It + determines if the replace operation should be carried out. Default value is None. + :type if_match: str + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: Twin or the result of cls(response) + :rtype: ~azure.iot.hub.protocol.models.Twin + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def replace_twin( + self, + id: str, + mid: str, + device_twin_info: Union[_models.Twin, IO[bytes]], + if_match: Optional[str] = None, + **kwargs: Any + ) -> _models.Twin: + """Replaces the tags and desired properties of a module twin. See + https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-device-twins for more information. + + :param id: The unique identifier of the device. Required. + :type id: str + :param mid: The unique identifier of the module. Required. + :type mid: str + :param device_twin_info: The module twin info that will replace the existing info. Is either a + Twin type or a IO[bytes] type. Required. + :type device_twin_info: ~azure.iot.hub.protocol.models.Twin or IO[bytes] + :param if_match: The string representing a weak ETag for the device twin, as per RFC7232. It + determines if the replace operation should be carried out. Default value is None. + :type if_match: str + :return: Twin or the result of cls(response) + :rtype: ~azure.iot.hub.protocol.models.Twin + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.Twin] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(device_twin_info, (IOBase, bytes)): + _content = device_twin_info + else: + _json = self._serialize.body(device_twin_info, "Twin") + + _request = build_replace_twin_request( + id=id, + mid=mid, + if_match=if_match, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + deserialized = self._deserialize("Twin", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def update_twin( + self, + id: str, + mid: str, + device_twin_info: _models.Twin, + if_match: Optional[str] = None, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Twin: + """Updates the tags and desired properties of a module twin. See + https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-device-twins for more information. + + :param id: The unique identifier of the device. Required. + :type id: str + :param mid: The unique identifier of the module. Required. + :type mid: str + :param device_twin_info: The module twin info containing the tags and desired properties to be + updated. Required. + :type device_twin_info: ~azure.iot.hub.protocol.models.Twin + :param if_match: The string representing a weak ETag for the device twin, as per RFC7232. It + determines if the update operation should be carried out. Default value is None. + :type if_match: str + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: Twin or the result of cls(response) + :rtype: ~azure.iot.hub.protocol.models.Twin + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def update_twin( + self, + id: str, + mid: str, + device_twin_info: IO[bytes], + if_match: Optional[str] = None, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Twin: + """Updates the tags and desired properties of a module twin. See + https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-device-twins for more information. + + :param id: The unique identifier of the device. Required. + :type id: str + :param mid: The unique identifier of the module. Required. + :type mid: str + :param device_twin_info: The module twin info containing the tags and desired properties to be + updated. Required. + :type device_twin_info: IO[bytes] + :param if_match: The string representing a weak ETag for the device twin, as per RFC7232. It + determines if the update operation should be carried out. Default value is None. + :type if_match: str + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: Twin or the result of cls(response) + :rtype: ~azure.iot.hub.protocol.models.Twin + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def update_twin( + self, + id: str, + mid: str, + device_twin_info: Union[_models.Twin, IO[bytes]], + if_match: Optional[str] = None, + **kwargs: Any + ) -> _models.Twin: + """Updates the tags and desired properties of a module twin. See + https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-device-twins for more information. + + :param id: The unique identifier of the device. Required. + :type id: str + :param mid: The unique identifier of the module. Required. + :type mid: str + :param device_twin_info: The module twin info containing the tags and desired properties to be + updated. Is either a Twin type or a IO[bytes] type. Required. + :type device_twin_info: ~azure.iot.hub.protocol.models.Twin or IO[bytes] + :param if_match: The string representing a weak ETag for the device twin, as per RFC7232. It + determines if the update operation should be carried out. Default value is None. + :type if_match: str + :return: Twin or the result of cls(response) + :rtype: ~azure.iot.hub.protocol.models.Twin + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.Twin] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(device_twin_info, (IOBase, bytes)): + _content = device_twin_info + else: + _json = self._serialize.body(device_twin_info, "Twin") + + _request = build_update_twin_request( + id=id, + mid=mid, + if_match=if_match, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + deserialized = self._deserialize("Twin", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def get_modules_on_device(self, id: str, **kwargs: Any) -> list[_models.Module]: + """Gets all the module identities on the device. + + :param id: The unique identifier of the device. Required. + :type id: str + :return: list of Module or the result of cls(response) + :rtype: list[~azure.iot.hub.protocol.models.Module] + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[list[_models.Module]] = kwargs.pop("cls", None) + + _request = build_get_modules_on_device_request( + id=id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + deserialized = self._deserialize("[Module]", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def get_identity(self, id: str, mid: str, **kwargs: Any) -> _models.Module: + """Gets a module identity on the device. + + :param id: The unique identifier of the device. Required. + :type id: str + :param mid: The unique identifier of the module. Required. + :type mid: str + :return: Module or the result of cls(response) + :rtype: ~azure.iot.hub.protocol.models.Module + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.Module] = kwargs.pop("cls", None) + + _request = build_get_identity_request( + id=id, + mid=mid, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + deserialized = self._deserialize("Module", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def create_or_update_identity( + self, + id: str, + mid: str, + module: _models.Module, + if_match: Optional[str] = None, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Module: + """Creates or updates the module identity for a device in the IoT Hub. The moduleId and + generationId cannot be updated by the user. + + :param id: The unique identifier of the device. Required. + :type id: str + :param mid: The unique identifier of the module. Required. + :type mid: str + :param module: The module identity. Required. + :type module: ~azure.iot.hub.protocol.models.Module + :param if_match: The string representing a weak ETag for the module, as per RFC7232. This + should not be set when creating a module, but may be set when updating a module. Default value + is None. + :type if_match: str + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: Module or the result of cls(response) + :rtype: ~azure.iot.hub.protocol.models.Module + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_or_update_identity( + self, + id: str, + mid: str, + module: IO[bytes], + if_match: Optional[str] = None, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Module: + """Creates or updates the module identity for a device in the IoT Hub. The moduleId and + generationId cannot be updated by the user. + + :param id: The unique identifier of the device. Required. + :type id: str + :param mid: The unique identifier of the module. Required. + :type mid: str + :param module: The module identity. Required. + :type module: IO[bytes] + :param if_match: The string representing a weak ETag for the module, as per RFC7232. This + should not be set when creating a module, but may be set when updating a module. Default value + is None. + :type if_match: str + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: Module or the result of cls(response) + :rtype: ~azure.iot.hub.protocol.models.Module + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create_or_update_identity( + self, id: str, mid: str, module: Union[_models.Module, IO[bytes]], if_match: Optional[str] = None, **kwargs: Any + ) -> _models.Module: + """Creates or updates the module identity for a device in the IoT Hub. The moduleId and + generationId cannot be updated by the user. + + :param id: The unique identifier of the device. Required. + :type id: str + :param mid: The unique identifier of the module. Required. + :type mid: str + :param module: The module identity. Is either a Module type or a IO[bytes] type. Required. + :type module: ~azure.iot.hub.protocol.models.Module or IO[bytes] + :param if_match: The string representing a weak ETag for the module, as per RFC7232. This + should not be set when creating a module, but may be set when updating a module. Default value + is None. + :type if_match: str + :return: Module or the result of cls(response) + :rtype: ~azure.iot.hub.protocol.models.Module + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.Module] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(module, (IOBase, bytes)): + _content = module + else: + _json = self._serialize.body(module, "Module") + + _request = build_create_or_update_identity_request( + id=id, + mid=mid, + if_match=if_match, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + deserialized = self._deserialize("Module", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def delete_identity(self, id: str, mid: str, if_match: Optional[str] = None, **kwargs: Any) -> None: + """Deletes the module identity for a device in the IoT Hub. + + :param id: The unique identifier of the deivce. Required. + :type id: str + :param mid: The unique identifier of the module. Required. + :type mid: str + :param if_match: The string representing a weak ETag for the module, as per RFC7232. The delete + operation is performed only if this ETag matches the value maintained by the server, indicating + that the module has not been modified since it was last retrieved. To force an unconditional + delete, set If-Match to the wildcard character (*). Default value is None. + :type if_match: str + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_delete_identity_request( + id=id, + mid=mid, + if_match=if_match, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @overload + async def invoke_method( + self, + device_id: str, + module_id: str, + direct_method_request: _models.CloudToDeviceMethod, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.CloudToDeviceMethodResult: + """Invokes a direct method on a module of a device. See + https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-direct-methods for more information. + + :param device_id: The unique identifier of the device. Required. + :type device_id: str + :param module_id: The unique identifier of the module. Required. + :type module_id: str + :param direct_method_request: The parameters to execute a direct method on the module. + Required. + :type direct_method_request: ~azure.iot.hub.protocol.models.CloudToDeviceMethod + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: CloudToDeviceMethodResult or the result of cls(response) + :rtype: ~azure.iot.hub.protocol.models.CloudToDeviceMethodResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def invoke_method( + self, + device_id: str, + module_id: str, + direct_method_request: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.CloudToDeviceMethodResult: + """Invokes a direct method on a module of a device. See + https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-direct-methods for more information. + + :param device_id: The unique identifier of the device. Required. + :type device_id: str + :param module_id: The unique identifier of the module. Required. + :type module_id: str + :param direct_method_request: The parameters to execute a direct method on the module. + Required. + :type direct_method_request: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: CloudToDeviceMethodResult or the result of cls(response) + :rtype: ~azure.iot.hub.protocol.models.CloudToDeviceMethodResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def invoke_method( + self, + device_id: str, + module_id: str, + direct_method_request: Union[_models.CloudToDeviceMethod, IO[bytes]], + **kwargs: Any + ) -> _models.CloudToDeviceMethodResult: + """Invokes a direct method on a module of a device. See + https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-direct-methods for more information. + + :param device_id: The unique identifier of the device. Required. + :type device_id: str + :param module_id: The unique identifier of the module. Required. + :type module_id: str + :param direct_method_request: The parameters to execute a direct method on the module. Is + either a CloudToDeviceMethod type or a IO[bytes] type. Required. + :type direct_method_request: ~azure.iot.hub.protocol.models.CloudToDeviceMethod or IO[bytes] + :return: CloudToDeviceMethodResult or the result of cls(response) + :rtype: ~azure.iot.hub.protocol.models.CloudToDeviceMethodResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.CloudToDeviceMethodResult] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(direct_method_request, (IOBase, bytes)): + _content = direct_method_request + else: + _json = self._serialize.body(direct_method_request, "CloudToDeviceMethod") + + _request = build_invoke_method_request( + device_id=device_id, + module_id=module_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + deserialized = self._deserialize("CloudToDeviceMethodResult", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore diff --git a/src/azure/iot/hub/protocol/aio/operations/_patch.py b/src/azure/iot/hub/protocol/aio/operations/_patch.py new file mode 100644 index 0000000..87676c6 --- /dev/null +++ b/src/azure/iot/hub/protocol/aio/operations/_patch.py @@ -0,0 +1,21 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------- +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" + + +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/src/azure/iot/hub/protocol/aio/operations/_query_operations.py b/src/azure/iot/hub/protocol/aio/operations/_query_operations.py new file mode 100644 index 0000000..4f1923d --- /dev/null +++ b/src/azure/iot/hub/protocol/aio/operations/_query_operations.py @@ -0,0 +1,199 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from collections.abc import MutableMapping +from io import IOBase +from typing import Any, Callable, IO, Optional, TypeVar, Union, overload + +from azure.core import AsyncPipelineClient +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.rest import AsyncHttpResponse, HttpRequest +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict + +from ... import models as _models +from ..._utils.serialization import Deserializer, Serializer +from ...operations._query_operations import build_get_twins_request +from .._configuration import IotHubGatewayServiceAPIsConfiguration + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] + + +class QueryOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.iot.hub.protocol.aio.IotHubGatewayServiceAPIs`'s + :attr:`query` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: IotHubGatewayServiceAPIsConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @overload + async def get_twins( + self, + query_specification: _models.QuerySpecification, + x_ms_continuation: Optional[str] = None, + x_ms_max_item_count: Optional[str] = None, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> list[_models.Twin]: + """Query an IoT Hub to retrieve information regarding device twins using a SQL-like language. See + https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-query-language for more information. + Pagination is supported. This returns information about device twins only. + + :param query_specification: The query string. See + https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-query-language for more information. + Required. + :type query_specification: ~azure.iot.hub.protocol.models.QuerySpecification + :param x_ms_continuation: The continuation token used to get the next page of results. Default + value is None. + :type x_ms_continuation: str + :param x_ms_max_item_count: The maximum number of items returned per page. The service may use + a different value if the value specified is not acceptable. Default value is None. + :type x_ms_max_item_count: str + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: list of Twin or the result of cls(response) + :rtype: list[~azure.iot.hub.protocol.models.Twin] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def get_twins( + self, + query_specification: IO[bytes], + x_ms_continuation: Optional[str] = None, + x_ms_max_item_count: Optional[str] = None, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> list[_models.Twin]: + """Query an IoT Hub to retrieve information regarding device twins using a SQL-like language. See + https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-query-language for more information. + Pagination is supported. This returns information about device twins only. + + :param query_specification: The query string. See + https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-query-language for more information. + Required. + :type query_specification: IO[bytes] + :param x_ms_continuation: The continuation token used to get the next page of results. Default + value is None. + :type x_ms_continuation: str + :param x_ms_max_item_count: The maximum number of items returned per page. The service may use + a different value if the value specified is not acceptable. Default value is None. + :type x_ms_max_item_count: str + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: list of Twin or the result of cls(response) + :rtype: list[~azure.iot.hub.protocol.models.Twin] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def get_twins( + self, + query_specification: Union[_models.QuerySpecification, IO[bytes]], + x_ms_continuation: Optional[str] = None, + x_ms_max_item_count: Optional[str] = None, + **kwargs: Any + ) -> list[_models.Twin]: + """Query an IoT Hub to retrieve information regarding device twins using a SQL-like language. See + https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-query-language for more information. + Pagination is supported. This returns information about device twins only. + + :param query_specification: The query string. See + https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-query-language for more information. + Is either a QuerySpecification type or a IO[bytes] type. Required. + :type query_specification: ~azure.iot.hub.protocol.models.QuerySpecification or IO[bytes] + :param x_ms_continuation: The continuation token used to get the next page of results. Default + value is None. + :type x_ms_continuation: str + :param x_ms_max_item_count: The maximum number of items returned per page. The service may use + a different value if the value specified is not acceptable. Default value is None. + :type x_ms_max_item_count: str + :return: list of Twin or the result of cls(response) + :rtype: list[~azure.iot.hub.protocol.models.Twin] + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[list[_models.Twin]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(query_specification, (IOBase, bytes)): + _content = query_specification + else: + _json = self._serialize.body(query_specification, "QuerySpecification") + + _request = build_get_twins_request( + x_ms_continuation=x_ms_continuation, + x_ms_max_item_count=x_ms_max_item_count, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + response_headers = {} + response_headers["x-ms-item-type"] = self._deserialize("str", response.headers.get("x-ms-item-type")) + response_headers["x-ms-continuation"] = self._deserialize("str", response.headers.get("x-ms-continuation")) + + deserialized = self._deserialize("[Twin]", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore diff --git a/src/azure/iot/hub/protocol/aio/operations/_statistics_operations.py b/src/azure/iot/hub/protocol/aio/operations/_statistics_operations.py new file mode 100644 index 0000000..a489d05 --- /dev/null +++ b/src/azure/iot/hub/protocol/aio/operations/_statistics_operations.py @@ -0,0 +1,148 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from collections.abc import MutableMapping +from typing import Any, Callable, Optional, TypeVar + +from azure.core import AsyncPipelineClient +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.rest import AsyncHttpResponse, HttpRequest +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict + +from ... import models as _models +from ..._utils.serialization import Deserializer, Serializer +from ...operations._statistics_operations import ( + build_get_device_statistics_request, + build_get_service_statistics_request, +) +from .._configuration import IotHubGatewayServiceAPIsConfiguration + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] + + +class StatisticsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.iot.hub.protocol.aio.IotHubGatewayServiceAPIs`'s + :attr:`statistics` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: IotHubGatewayServiceAPIsConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace_async + async def get_device_statistics(self, **kwargs: Any) -> _models.RegistryStatistics: + """Gets device statistics of the IoT Hub identity registry, such as total device count. + + :return: RegistryStatistics or the result of cls(response) + :rtype: ~azure.iot.hub.protocol.models.RegistryStatistics + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.RegistryStatistics] = kwargs.pop("cls", None) + + _request = build_get_device_statistics_request( + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + deserialized = self._deserialize("RegistryStatistics", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def get_service_statistics(self, **kwargs: Any) -> _models.ServiceStatistics: + """Gets service statistics of the IoT Hub identity registry, such as connected device count. + + :return: ServiceStatistics or the result of cls(response) + :rtype: ~azure.iot.hub.protocol.models.ServiceStatistics + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ServiceStatistics] = kwargs.pop("cls", None) + + _request = build_get_service_statistics_request( + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + deserialized = self._deserialize("ServiceStatistics", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore diff --git a/src/azure/iot/hub/protocol/iot_hub_gateway_service_ap_is.py b/src/azure/iot/hub/protocol/iot_hub_gateway_service_ap_is.py deleted file mode 100644 index bdd35f2..0000000 --- a/src/azure/iot/hub/protocol/iot_hub_gateway_service_ap_is.py +++ /dev/null @@ -1,112 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is -# regenerated. -# -------------------------------------------------------------------------- - -from msrest.service_client import SDKClient -from msrest import Configuration, Serializer, Deserializer -from .version import VERSION -from msrest.exceptions import HttpOperationError -from .operations.configuration_operations import ConfigurationOperations -from .operations.statistics_operations import StatisticsOperations -from .operations.devices_operations import DevicesOperations -from .operations.bulk_registry_operations import BulkRegistryOperations -from .operations.query_operations import QueryOperations -from .operations.jobs_operations import JobsOperations -from .operations.cloud_to_device_messages_operations import CloudToDeviceMessagesOperations -from .operations.modules_operations import ModulesOperations -from .operations.digital_twin_operations import DigitalTwinOperations -from . import models - - -class IotHubGatewayServiceAPIsConfiguration(Configuration): - """Configuration for IotHubGatewayServiceAPIs - Note that all parameters used to create this instance are saved as instance - attributes. - - :param credentials: Subscription credentials which uniquely identify - client subscription. - :type credentials: None - :param str base_url: Service URL - """ - - def __init__(self, credentials, base_url=None): - - if credentials is None: - raise ValueError("Parameter 'credentials' must not be None.") - if not base_url: - base_url = "https://fully-qualified-iothubname.azure-devices.net" - - super(IotHubGatewayServiceAPIsConfiguration, self).__init__(base_url) - - self.add_user_agent("iothubgatewayserviceapis/{}".format(VERSION)) - - self.credentials = credentials - - -class IotHubGatewayServiceAPIs(SDKClient): - """IotHubGatewayServiceAPIs - - :ivar config: Configuration for client. - :vartype config: IotHubGatewayServiceAPIsConfiguration - - :ivar configuration: Configuration operations - :vartype configuration: protocol.operations.ConfigurationOperations - :ivar statistics: Statistics operations - :vartype statistics: protocol.operations.StatisticsOperations - :ivar devices: Devices operations - :vartype devices: protocol.operations.DevicesOperations - :ivar bulk_registry: BulkRegistry operations - :vartype bulk_registry: protocol.operations.BulkRegistryOperations - :ivar query: Query operations - :vartype query: protocol.operations.QueryOperations - :ivar jobs: Jobs operations - :vartype jobs: protocol.operations.JobsOperations - :ivar cloud_to_device_messages: CloudToDeviceMessages operations - :vartype cloud_to_device_messages: protocol.operations.CloudToDeviceMessagesOperations - :ivar modules: Modules operations - :vartype modules: protocol.operations.ModulesOperations - :ivar digital_twin: DigitalTwin operations - :vartype digital_twin: protocol.operations.DigitalTwinOperations - - :param credentials: Subscription credentials which uniquely identify - client subscription. - :type credentials: None - :param str base_url: Service URL - """ - - def __init__(self, credentials, base_url=None): - - self.config = IotHubGatewayServiceAPIsConfiguration(credentials, base_url) - super(IotHubGatewayServiceAPIs, self).__init__(self.config.credentials, self.config) - - client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} - self.api_version = "2021-04-12" - self._serialize = Serializer(client_models) - self._deserialize = Deserializer(client_models) - - self.configuration = ConfigurationOperations( - self._client, self.config, self._serialize, self._deserialize - ) - self.statistics = StatisticsOperations( - self._client, self.config, self._serialize, self._deserialize - ) - self.devices = DevicesOperations( - self._client, self.config, self._serialize, self._deserialize - ) - self.bulk_registry = BulkRegistryOperations( - self._client, self.config, self._serialize, self._deserialize - ) - self.query = QueryOperations(self._client, self.config, self._serialize, self._deserialize) - self.jobs = JobsOperations(self._client, self.config, self._serialize, self._deserialize) - self.cloud_to_device_messages = CloudToDeviceMessagesOperations( - self._client, self.config, self._serialize, self._deserialize - ) - self.modules = ModulesOperations( - self._client, self.config, self._serialize, self._deserialize - ) - self.digital_twin = DigitalTwinOperations( - self._client, self.config, self._serialize, self._deserialize - ) diff --git a/src/azure/iot/hub/protocol/models/__init__.py b/src/azure/iot/hub/protocol/models/__init__.py index 8e47a2f..f4a9a81 100644 --- a/src/azure/iot/hub/protocol/models/__init__.py +++ b/src/azure/iot/hub/protocol/models/__init__.py @@ -1,102 +1,124 @@ # coding=utf-8 # -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is -# regenerated. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position -try: - from .configuration_metrics_py3 import ConfigurationMetrics - from .configuration_content_py3 import ConfigurationContent - from .configuration_py3 import Configuration - from .configuration_queries_test_input_py3 import ConfigurationQueriesTestInput - from .configuration_queries_test_response_py3 import ConfigurationQueriesTestResponse - from .registry_statistics_py3 import RegistryStatistics - from .service_statistics_py3 import ServiceStatistics - from .symmetric_key_py3 import SymmetricKey - from .x509_thumbprint_py3 import X509Thumbprint - from .authentication_mechanism_py3 import AuthenticationMechanism - from .device_capabilities_py3 import DeviceCapabilities - from .device_py3 import Device - from .property_container_py3 import PropertyContainer - from .export_import_device_py3 import ExportImportDevice - from .device_registry_operation_error_py3 import DeviceRegistryOperationError - from .device_registry_operation_warning_py3 import DeviceRegistryOperationWarning - from .bulk_registry_operation_result_py3 import BulkRegistryOperationResult - from .query_specification_py3 import QuerySpecification - from .twin_properties_py3 import TwinProperties - from .twin_py3 import Twin - from .managed_identity_py3 import ManagedIdentity - from .job_properties_py3 import JobProperties - from .purge_message_queue_result_py3 import PurgeMessageQueueResult - from .cloud_to_device_method_py3 import CloudToDeviceMethod - from .job_request_py3 import JobRequest - from .device_job_statistics_py3 import DeviceJobStatistics - from .job_response_py3 import JobResponse - from .query_result_py3 import QueryResult - from .module_py3 import Module - from .cloud_to_device_method_result_py3 import CloudToDeviceMethodResult -except (SyntaxError, ImportError): - from .configuration_metrics import ConfigurationMetrics - from .configuration_content import ConfigurationContent - from .configuration import Configuration - from .configuration_queries_test_input import ConfigurationQueriesTestInput - from .configuration_queries_test_response import ConfigurationQueriesTestResponse - from .registry_statistics import RegistryStatistics - from .service_statistics import ServiceStatistics - from .symmetric_key import SymmetricKey - from .x509_thumbprint import X509Thumbprint - from .authentication_mechanism import AuthenticationMechanism - from .device_capabilities import DeviceCapabilities - from .device import Device - from .property_container import PropertyContainer - from .export_import_device import ExportImportDevice - from .device_registry_operation_error import DeviceRegistryOperationError - from .device_registry_operation_warning import DeviceRegistryOperationWarning - from .bulk_registry_operation_result import BulkRegistryOperationResult - from .query_specification import QuerySpecification - from .twin_properties import TwinProperties - from .twin import Twin - from .managed_identity import ManagedIdentity - from .job_properties import JobProperties - from .purge_message_queue_result import PurgeMessageQueueResult - from .cloud_to_device_method import CloudToDeviceMethod - from .job_request import JobRequest - from .device_job_statistics import DeviceJobStatistics - from .job_response import JobResponse - from .query_result import QueryResult - from .module import Module - from .cloud_to_device_method_result import CloudToDeviceMethodResult +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + + +from ._models_py3 import ( # type: ignore + AuthenticationMechanism, + BulkRegistryOperationResult, + CloudToDeviceMethod, + CloudToDeviceMethodResult, + Configuration, + ConfigurationContent, + ConfigurationMetrics, + ConfigurationQueriesTestInput, + ConfigurationQueriesTestResponse, + Device, + DeviceCapabilities, + DeviceJobStatistics, + DeviceRegistryOperationError, + DeviceRegistryOperationWarning, + ExportImportDevice, + JobProperties, + JobRequest, + JobResponse, + ManagedIdentity, + Module, + PropertyContainer, + PurgeMessageQueueResult, + QueryResult, + QuerySpecification, + RegistryStatistics, + ServiceStatistics, + SymmetricKey, + Twin, + TwinProperties, + X509Thumbprint, +) + +from ._iot_hub_gateway_service_apis_enums import ( # type: ignore + AuthenticationMechanismType, + DeviceConnectionState, + DeviceRegistryOperationErrorCode, + DeviceRegistryOperationWarningCode, + DeviceStatus, + ExportImportDeviceImportMode, + ExportImportDeviceStatus, + JobPropertiesStatus, + JobPropertiesStorageAuthenticationType, + JobPropertiesType, + JobRequestType, + JobResponseStatus, + JobResponseType, + ModuleConnectionState, + QueryResultType, + TwinAuthenticationType, + TwinConnectionState, + TwinStatus, +) +from ._patch import __all__ as _patch_all +from ._patch import * +from ._patch import patch_sdk as _patch_sdk __all__ = [ - "ConfigurationMetrics", - "ConfigurationContent", + "AuthenticationMechanism", + "BulkRegistryOperationResult", + "CloudToDeviceMethod", + "CloudToDeviceMethodResult", "Configuration", + "ConfigurationContent", + "ConfigurationMetrics", "ConfigurationQueriesTestInput", "ConfigurationQueriesTestResponse", - "RegistryStatistics", - "ServiceStatistics", - "SymmetricKey", - "X509Thumbprint", - "AuthenticationMechanism", - "DeviceCapabilities", "Device", - "PropertyContainer", - "ExportImportDevice", + "DeviceCapabilities", + "DeviceJobStatistics", "DeviceRegistryOperationError", "DeviceRegistryOperationWarning", - "BulkRegistryOperationResult", - "QuerySpecification", - "TwinProperties", - "Twin", - "ManagedIdentity", + "ExportImportDevice", "JobProperties", - "PurgeMessageQueueResult", - "CloudToDeviceMethod", "JobRequest", - "DeviceJobStatistics", "JobResponse", - "QueryResult", + "ManagedIdentity", "Module", - "CloudToDeviceMethodResult", + "PropertyContainer", + "PurgeMessageQueueResult", + "QueryResult", + "QuerySpecification", + "RegistryStatistics", + "ServiceStatistics", + "SymmetricKey", + "Twin", + "TwinProperties", + "X509Thumbprint", + "AuthenticationMechanismType", + "DeviceConnectionState", + "DeviceRegistryOperationErrorCode", + "DeviceRegistryOperationWarningCode", + "DeviceStatus", + "ExportImportDeviceImportMode", + "ExportImportDeviceStatus", + "JobPropertiesStatus", + "JobPropertiesStorageAuthenticationType", + "JobPropertiesType", + "JobRequestType", + "JobResponseStatus", + "JobResponseType", + "ModuleConnectionState", + "QueryResultType", + "TwinAuthenticationType", + "TwinConnectionState", + "TwinStatus", ] +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore +_patch_sdk() diff --git a/src/azure/iot/hub/protocol/models/_iot_hub_gateway_service_apis_enums.py b/src/azure/iot/hub/protocol/models/_iot_hub_gateway_service_apis_enums.py new file mode 100644 index 0000000..84aa916 --- /dev/null +++ b/src/azure/iot/hub/protocol/models/_iot_hub_gateway_service_apis_enums.py @@ -0,0 +1,412 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from enum import Enum +from azure.core import CaseInsensitiveEnumMeta + + +class AuthenticationMechanismType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The type of authentication used to connect to the service.""" + + SAS = "sas" + SELF_SIGNED = "selfSigned" + CERTIFICATE_AUTHORITY = "certificateAuthority" + NONE = "none" + + +class DeviceConnectionState(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The state of the device.""" + + DISCONNECTED = "Disconnected" + CONNECTED = "Connected" + + +class DeviceRegistryOperationErrorCode(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The error code.""" + + INVALID_ERROR_CODE = "InvalidErrorCode" + GENERIC_BAD_REQUEST = "GenericBadRequest" + INVALID_PROTOCOL_VERSION = "InvalidProtocolVersion" + DEVICE_INVALID_RESULT_COUNT = "DeviceInvalidResultCount" + INVALID_OPERATION = "InvalidOperation" + ARGUMENT_INVALID = "ArgumentInvalid" + ARGUMENT_NULL = "ArgumentNull" + IOT_HUB_FORMAT_ERROR = "IotHubFormatError" + DEVICE_STORAGE_ENTITY_SERIALIZATION_ERROR = "DeviceStorageEntitySerializationError" + BLOB_CONTAINER_VALIDATION_ERROR = "BlobContainerValidationError" + IMPORT_WARNING_EXISTS_ERROR = "ImportWarningExistsError" + INVALID_SCHEMA_VERSION = "InvalidSchemaVersion" + DEVICE_DEFINED_MULTIPLE_TIMES = "DeviceDefinedMultipleTimes" + DESERIALIZATION_ERROR = "DeserializationError" + BULK_REGISTRY_OPERATION_FAILURE = "BulkRegistryOperationFailure" + DEFAULT_STORAGE_ENDPOINT_NOT_CONFIGURED = "DefaultStorageEndpointNotConfigured" + INVALID_FILE_UPLOAD_CORRELATION_ID = "InvalidFileUploadCorrelationId" + EXPIRED_FILE_UPLOAD_CORRELATION_ID = "ExpiredFileUploadCorrelationId" + INVALID_STORAGE_ENDPOINT = "InvalidStorageEndpoint" + INVALID_MESSAGING_ENDPOINT = "InvalidMessagingEndpoint" + INVALID_FILE_UPLOAD_COMPLETION_STATUS = "InvalidFileUploadCompletionStatus" + INVALID_STORAGE_ENDPOINT_OR_BLOB = "InvalidStorageEndpointOrBlob" + REQUEST_CANCELED = "RequestCanceled" + INVALID_STORAGE_ENDPOINT_PROPERTY = "InvalidStorageEndpointProperty" + ETAG_DOES_NOT_MATCH = "EtagDoesNotMatch" + REQUEST_TIMED_OUT = "RequestTimedOut" + UNSUPPORTED_OPERATION_ON_REPLICA = "UnsupportedOperationOnReplica" + NULL_MESSAGE = "NullMessage" + CONNECTION_FORCEFULLY_CLOSED_ON_NEW_CONNECTION = "ConnectionForcefullyClosedOnNewConnection" + INVALID_DEVICE_SCOPE = "InvalidDeviceScope" + CONNECTION_FORCEFULLY_CLOSED_ON_FAULT_INJECTION = "ConnectionForcefullyClosedOnFaultInjection" + CONNECTION_REJECTED_ON_FAULT_INJECTION = "ConnectionRejectedOnFaultInjection" + INVALID_ENDPOINT_AUTHENTICATION_TYPE = "InvalidEndpointAuthenticationType" + MANAGED_IDENTITY_NOT_ENABLED = "ManagedIdentityNotEnabled" + INVALID_ROUTE_TEST_INPUT = "InvalidRouteTestInput" + INVALID_SOURCE_ON_ROUTE = "InvalidSourceOnRoute" + ROUTING_NOT_ENABLED = "RoutingNotEnabled" + INVALID_CONTENT_ENCODING_OR_TYPE = "InvalidContentEncodingOrType" + INVALID_ENDORSEMENT_KEY = "InvalidEndorsementKey" + INVALID_REGISTRATION_ID = "InvalidRegistrationId" + INVALID_STORAGE_ROOT_KEY = "InvalidStorageRootKey" + INVALID_ENROLLMENT_GROUP_ID = "InvalidEnrollmentGroupId" + TOO_MANY_ENROLLMENTS = "TooManyEnrollments" + REGISTRATION_ID_DEFINED_MULTIPLE_TIMES = "RegistrationIdDefinedMultipleTimes" + CUSTOM_ALLOCATION_FAILED = "CustomAllocationFailed" + CUSTOM_ALLOCATION_IOT_HUB_NOT_SPECIFIED = "CustomAllocationIotHubNotSpecified" + CUSTOM_ALLOCATION_UNAUTHORIZED_ACCESS = "CustomAllocationUnauthorizedAccess" + CANNOT_REGISTER_MODULE_TO_MODULE = "CannotRegisterModuleToModule" + TENANT_HUB_ROUTING_NOT_ENABLED = "TenantHubRoutingNotEnabled" + INVALID_CONFIGURATION_TARGET_CONDITION = "InvalidConfigurationTargetCondition" + INVALID_CONFIGURATION_CONTENT = "InvalidConfigurationContent" + CANNOT_MODIFY_IMMUTABLE_CONFIGURATION_CONTENT = "CannotModifyImmutableConfigurationContent" + INVALID_CONFIGURATION_CUSTOM_METRICS_QUERY = "InvalidConfigurationCustomMetricsQuery" + INVALID_PN_P_INTERFACE_DEFINITION = "InvalidPnPInterfaceDefinition" + INVALID_PN_P_DESIRED_PROPERTIES = "InvalidPnPDesiredProperties" + INVALID_PN_P_REPORTED_PROPERTIES = "InvalidPnPReportedProperties" + INVALID_PN_P_WRITABLE_REPORTED_PROPERTIES = "InvalidPnPWritableReportedProperties" + INVALID_DIGITAL_TWIN_JSON_PATCH = "InvalidDigitalTwinJsonPatch" + INVALID_DIGITAL_TWIN_PAYLOAD = "InvalidDigitalTwinPayload" + INVALID_DIGITAL_TWIN_PATCH = "InvalidDigitalTwinPatch" + INVALID_DIGITAL_TWIN_PATCH_PATH = "InvalidDigitalTwinPatchPath" + GENERIC_UNAUTHORIZED = "GenericUnauthorized" + IOT_HUB_NOT_FOUND = "IotHubNotFound" + IOT_HUB_UNAUTHORIZED_ACCESS = "IotHubUnauthorizedAccess" + IOT_HUB_UNAUTHORIZED = "IotHubUnauthorized" + ELASTIC_POOL_NOT_FOUND = "ElasticPoolNotFound" + SYSTEM_MODULE_MODIFY_UNAUTHORIZED_ACCESS = "SystemModuleModifyUnauthorizedAccess" + GENERIC_FORBIDDEN = "GenericForbidden" + IOT_HUB_SUSPENDED = "IotHubSuspended" + IOT_HUB_QUOTA_EXCEEDED = "IotHubQuotaExceeded" + JOB_QUOTA_EXCEEDED = "JobQuotaExceeded" + DEVICE_MAXIMUM_QUEUE_DEPTH_EXCEEDED = "DeviceMaximumQueueDepthExceeded" + IOT_HUB_MAX_CBS_TOKEN_EXCEEDED = "IotHubMaxCbsTokenExceeded" + DEVICE_MAXIMUM_ACTIVE_FILE_UPLOAD_LIMIT_EXCEEDED = "DeviceMaximumActiveFileUploadLimitExceeded" + DEVICE_MAXIMUM_QUEUE_SIZE_EXCEEDED = "DeviceMaximumQueueSizeExceeded" + ROUTING_ENDPOINT_RESPONSE_FORBIDDEN = "RoutingEndpointResponseForbidden" + INVALID_MESSAGE_EXPIRY_TIME = "InvalidMessageExpiryTime" + OPERATION_NOT_AVAILABLE_IN_CURRENT_TIER = "OperationNotAvailableInCurrentTier" + KEY_ENCRYPTION_KEY_REVOKED = "KeyEncryptionKeyRevoked" + DEVICE_MODEL_MAX_PROPERTIES_EXCEEDED = "DeviceModelMaxPropertiesExceeded" + DEVICE_MODEL_MAX_INDEXABLE_PROPERTIES_EXCEEDED = "DeviceModelMaxIndexablePropertiesExceeded" + IOT_DPS_SUSPENDED = "IotDpsSuspended" + IOT_DPS_SUSPENDING = "IotDpsSuspending" + GENERIC_NOT_FOUND = "GenericNotFound" + DEVICE_NOT_FOUND = "DeviceNotFound" + JOB_NOT_FOUND = "JobNotFound" + QUOTA_METRIC_NOT_FOUND = "QuotaMetricNotFound" + SYSTEM_PROPERTY_NOT_FOUND = "SystemPropertyNotFound" + AMQP_ADDRESS_NOT_FOUND = "AmqpAddressNotFound" + ROUTING_ENDPOINT_RESPONSE_NOT_FOUND = "RoutingEndpointResponseNotFound" + CERTIFICATE_NOT_FOUND = "CertificateNotFound" + ELASTIC_POOL_TENANT_HUB_NOT_FOUND = "ElasticPoolTenantHubNotFound" + MODULE_NOT_FOUND = "ModuleNotFound" + AZURE_TABLE_STORE_NOT_FOUND = "AzureTableStoreNotFound" + IOT_HUB_FAILING_OVER = "IotHubFailingOver" + FEATURE_NOT_SUPPORTED = "FeatureNotSupported" + DIGITAL_TWIN_INTERFACE_NOT_FOUND = "DigitalTwinInterfaceNotFound" + QUERY_STORE_CLUSTER_NOT_FOUND = "QueryStoreClusterNotFound" + DEVICE_NOT_ONLINE = "DeviceNotOnline" + DEVICE_CONNECTION_CLOSED_REMOTELY = "DeviceConnectionClosedRemotely" + ENROLLMENT_NOT_FOUND = "EnrollmentNotFound" + DEVICE_REGISTRATION_NOT_FOUND = "DeviceRegistrationNotFound" + ASYNC_OPERATION_NOT_FOUND = "AsyncOperationNotFound" + ENROLLMENT_GROUP_NOT_FOUND = "EnrollmentGroupNotFound" + DEVICE_RECORD_NOT_FOUND = "DeviceRecordNotFound" + GROUP_RECORD_NOT_FOUND = "GroupRecordNotFound" + DEVICE_GROUP_NOT_FOUND = "DeviceGroupNotFound" + PROVISIONING_SETTINGS_NOT_FOUND = "ProvisioningSettingsNotFound" + PROVISIONING_RECORD_NOT_FOUND = "ProvisioningRecordNotFound" + LINKED_HUB_NOT_FOUND = "LinkedHubNotFound" + CERTIFICATE_AUTHORITY_NOT_FOUND = "CertificateAuthorityNotFound" + CONFIGURATION_NOT_FOUND = "ConfigurationNotFound" + GROUP_NOT_FOUND = "GroupNotFound" + DIGITAL_TWIN_MODEL_NOT_FOUND = "DigitalTwinModelNotFound" + INTERFACE_NAME_MODEL_NOT_FOUND = "InterfaceNameModelNotFound" + GENERIC_METHOD_NOT_ALLOWED = "GenericMethodNotAllowed" + OPERATION_NOT_ALLOWED_IN_CURRENT_STATE = "OperationNotAllowedInCurrentState" + IMPORT_DEVICES_NOT_SUPPORTED = "ImportDevicesNotSupported" + BULK_ADD_DEVICES_NOT_SUPPORTED = "BulkAddDevicesNotSupported" + GENERIC_CONFLICT = "GenericConflict" + DEVICE_ALREADY_EXISTS = "DeviceAlreadyExists" + LINK_CREATION_CONFLICT = "LinkCreationConflict" + CALLBACK_SUBSCRIPTION_CONFLICT = "CallbackSubscriptionConflict" + MODEL_ALREADY_EXISTS = "ModelAlreadyExists" + DEVICE_LOCKED = "DeviceLocked" + DEVICE_JOB_ALREADY_EXISTS = "DeviceJobAlreadyExists" + JOB_ALREADY_EXISTS = "JobAlreadyExists" + ENROLLMENT_CONFLICT = "EnrollmentConflict" + ENROLLMENT_GROUP_CONFLICT = "EnrollmentGroupConflict" + REGISTRATION_STATUS_CONFLICT = "RegistrationStatusConflict" + DEVICE_RECORD_CONFLICT = "DeviceRecordConflict" + GROUP_RECORD_CONFLICT = "GroupRecordConflict" + DEVICE_GROUP_CONFLICT = "DeviceGroupConflict" + PROVISIONING_SETTINGS_CONFLICT = "ProvisioningSettingsConflict" + PROVISIONING_RECORD_CONFLICT = "ProvisioningRecordConflict" + LINKED_HUB_CONFLICT = "LinkedHubConflict" + CERTIFICATE_AUTHORITY_CONFLICT = "CertificateAuthorityConflict" + MODULE_ALREADY_EXISTS_ON_DEVICE = "ModuleAlreadyExistsOnDevice" + CONFIGURATION_ALREADY_EXISTS = "ConfigurationAlreadyExists" + APPLY_CONFIGURATION_ALREADY_IN_PROGRESS_ON_DEVICE = "ApplyConfigurationAlreadyInProgressOnDevice" + DIGITAL_TWIN_MODEL_ALREADY_EXISTS = "DigitalTwinModelAlreadyExists" + DIGITAL_TWIN_MODEL_EXISTS_WITH_OTHER_MODEL_TYPE = "DigitalTwinModelExistsWithOtherModelType" + INTERFACE_NAME_MODEL_ALREADY_EXISTS = "InterfaceNameModelAlreadyExists" + GENERIC_PRECONDITION_FAILED = "GenericPreconditionFailed" + PRECONDITION_FAILED = "PreconditionFailed" + DEVICE_MESSAGE_LOCK_LOST = "DeviceMessageLockLost" + JOB_RUN_PRECONDITION_FAILED = "JobRunPreconditionFailed" + INFLIGHT_MESSAGES_IN_LINK = "InflightMessagesInLink" + GENERIC_REQUEST_ENTITY_TOO_LARGE = "GenericRequestEntityTooLarge" + MESSAGE_TOO_LARGE = "MessageTooLarge" + TOO_MANY_DEVICES = "TooManyDevices" + TOO_MANY_MODULES_ON_DEVICE = "TooManyModulesOnDevice" + CONFIGURATION_COUNT_LIMIT_EXCEEDED = "ConfigurationCountLimitExceeded" + DIGITAL_TWIN_MODEL_COUNT_LIMIT_EXCEEDED = "DigitalTwinModelCountLimitExceeded" + INTERFACE_NAME_COMPRESSION_MODEL_COUNT_LIMIT_EXCEEDED = "InterfaceNameCompressionModelCountLimitExceeded" + GENERIC_UNSUPPORTED_MEDIA_TYPE = "GenericUnsupportedMediaType" + INCOMPATIBLE_DATA_TYPE = "IncompatibleDataType" + GENERIC_TOO_MANY_REQUESTS = "GenericTooManyRequests" + THROTTLING_EXCEPTION = "ThrottlingException" + THROTTLE_BACKLOG_LIMIT_EXCEEDED = "ThrottleBacklogLimitExceeded" + THROTTLING_BACKLOG_TIMEOUT = "ThrottlingBacklogTimeout" + THROTTLING_MAX_ACTIVE_JOB_COUNT_EXCEEDED = "ThrottlingMaxActiveJobCountExceeded" + DEVICE_THROTTLING_LIMIT_EXCEEDED = "DeviceThrottlingLimitExceeded" + CLIENT_CLOSED_REQUEST = "ClientClosedRequest" + GENERIC_SERVER_ERROR = "GenericServerError" + SERVER_ERROR = "ServerError" + JOB_CANCELLED = "JobCancelled" + STATISTICS_RETRIEVAL_ERROR = "StatisticsRetrievalError" + CONNECTION_FORCEFULLY_CLOSED = "ConnectionForcefullyClosed" + INVALID_BLOB_STATE = "InvalidBlobState" + BACKUP_TIMED_OUT = "BackupTimedOut" + AZURE_STORAGE_TIMEOUT = "AzureStorageTimeout" + GENERIC_TIMEOUT = "GenericTimeout" + INVALID_THROTTLE_PARAMETER = "InvalidThrottleParameter" + EVENT_HUB_LINK_ALREADY_CLOSED = "EventHubLinkAlreadyClosed" + RELIABLE_BLOB_STORE_ERROR = "ReliableBlobStoreError" + RETRY_ATTEMPTS_EXHAUSTED = "RetryAttemptsExhausted" + AZURE_TABLE_STORE_ERROR = "AzureTableStoreError" + CHECKPOINT_STORE_NOT_FOUND = "CheckpointStoreNotFound" + DOCUMENT_DB_INVALID_RETURN_VALUE = "DocumentDbInvalidReturnValue" + RELIABLE_DOC_DB_STORE_STORE_ERROR = "ReliableDocDbStoreStoreError" + RELIABLE_BLOB_STORE_TIMEOUT_ERROR = "ReliableBlobStoreTimeoutError" + CONFIG_READ_FAILED = "ConfigReadFailed" + INVALID_CONTAINER_RECEIVE_LINK = "InvalidContainerReceiveLink" + INVALID_PARTITION_EPOCH = "InvalidPartitionEpoch" + RESTORE_TIMED_OUT = "RestoreTimedOut" + STREAM_RESERVATION_FAILURE = "StreamReservationFailure" + SERIALIZATION_ERROR = "SerializationError" + UNEXPECTED_PROPERTY_VALUE = "UnexpectedPropertyValue" + ORCHESTRATION_OPERATION_FAILED = "OrchestrationOperationFailed" + MODEL_REPO_ENDPOINT_ERROR = "ModelRepoEndpointError" + RESOLUTION_ERROR = "ResolutionError" + UNABLE_TO_FETCH_CREDENTIALS = "UnableToFetchCredentials" + UNABLE_TO_FETCH_TENANT_INFO = "UnableToFetchTenantInfo" + UNABLE_TO_SHARE_IDENTITY = "UnableToShareIdentity" + UNABLE_TO_EXPAND_DISCOVERY_INFO = "UnableToExpandDiscoveryInfo" + UNABLE_TO_EXPAND_COMPONENT_INFO = "UnableToExpandComponentInfo" + UNABLE_TO_COMPRESS_COMPONENT_INFO = "UnableToCompressComponentInfo" + UNABLE_TO_COMPRESS_DISCOVERY_INFO = "UnableToCompressDiscoveryInfo" + ORPHAN_DISCOVERY_DOCUMENT = "OrphanDiscoveryDocument" + GENERIC_BAD_GATEWAY = "GenericBadGateway" + INVALID_RESPONSE_WHILE_PROXYING = "InvalidResponseWhileProxying" + GENERIC_SERVICE_UNAVAILABLE = "GenericServiceUnavailable" + SERVICE_UNAVAILABLE = "ServiceUnavailable" + PARTITION_NOT_FOUND = "PartitionNotFound" + IOT_HUB_ACTIVATION_FAILED = "IotHubActivationFailed" + SERVER_BUSY = "ServerBusy" + IOT_HUB_RESTORING = "IotHubRestoring" + RECEIVE_LINK_OPENS_THROTTLED = "ReceiveLinkOpensThrottled" + CONNECTION_UNAVAILABLE = "ConnectionUnavailable" + DEVICE_UNAVAILABLE = "DeviceUnavailable" + CONFIGURATION_NOT_AVAILABLE = "ConfigurationNotAvailable" + GROUP_NOT_AVAILABLE = "GroupNotAvailable" + HOSTING_SERVICE_NOT_AVAILABLE = "HostingServiceNotAvailable" + GENERIC_GATEWAY_TIMEOUT = "GenericGatewayTimeout" + GATEWAY_TIMEOUT = "GatewayTimeout" + + +class DeviceRegistryOperationWarningCode(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The warning code.""" + + DEVICE_REGISTERED_WITHOUT_TWIN = "DeviceRegisteredWithoutTwin" + + +class DeviceStatus(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The status of the device. If the status disabled, a device cannot connect to the service.""" + + ENABLED = "enabled" + DISABLED = "disabled" + + +class ExportImportDeviceImportMode(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The type of registry operation and ETag preferences.""" + + CREATE = "create" + UPDATE = "update" + UPDATE_IF_MATCH_E_TAG = "updateIfMatchETag" + DELETE = "delete" + DELETE_IF_MATCH_E_TAG = "deleteIfMatchETag" + UPDATE_TWIN = "updateTwin" + UPDATE_TWIN_IF_MATCH_E_TAG = "updateTwinIfMatchETag" + + +class ExportImportDeviceStatus(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The status of the module. If disabled, the module cannot connect to the service.""" + + ENABLED = "enabled" + DISABLED = "disabled" + + +class JobPropertiesStatus(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """System generated. Ignored at creation. The status of the job.""" + + UNKNOWN = "unknown" + ENQUEUED = "enqueued" + RUNNING = "running" + COMPLETED = "completed" + FAILED = "failed" + CANCELLED = "cancelled" + SCHEDULED = "scheduled" + QUEUED = "queued" + + +class JobPropertiesStorageAuthenticationType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The authentication type used for connecting to the storage account.""" + + KEY_BASED = "keyBased" + IDENTITY_BASED = "identityBased" + + +class JobPropertiesType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The job type.""" + + UNKNOWN = "unknown" + EXPORT = "export" + IMPORT = "import" + BACKUP = "backup" + READ_DEVICE_PROPERTIES = "readDeviceProperties" + WRITE_DEVICE_PROPERTIES = "writeDeviceProperties" + UPDATE_DEVICE_CONFIGURATION = "updateDeviceConfiguration" + REBOOT_DEVICE = "rebootDevice" + FACTORY_RESET_DEVICE = "factoryResetDevice" + FIRMWARE_UPDATE = "firmwareUpdate" + SCHEDULE_DEVICE_METHOD = "scheduleDeviceMethod" + SCHEDULE_UPDATE_TWIN = "scheduleUpdateTwin" + RESTORE_FROM_BACKUP = "restoreFromBackup" + FAILOVER_DATA_COPY = "failoverDataCopy" + + +class JobRequestType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The job type.""" + + UNKNOWN = "unknown" + EXPORT = "export" + IMPORT = "import" + BACKUP = "backup" + READ_DEVICE_PROPERTIES = "readDeviceProperties" + WRITE_DEVICE_PROPERTIES = "writeDeviceProperties" + UPDATE_DEVICE_CONFIGURATION = "updateDeviceConfiguration" + REBOOT_DEVICE = "rebootDevice" + FACTORY_RESET_DEVICE = "factoryResetDevice" + FIRMWARE_UPDATE = "firmwareUpdate" + SCHEDULE_DEVICE_METHOD = "scheduleDeviceMethod" + SCHEDULE_UPDATE_TWIN = "scheduleUpdateTwin" + RESTORE_FROM_BACKUP = "restoreFromBackup" + FAILOVER_DATA_COPY = "failoverDataCopy" + + +class JobResponseStatus(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """System generated. Ignored at creation. The status of the job.""" + + UNKNOWN = "unknown" + ENQUEUED = "enqueued" + RUNNING = "running" + COMPLETED = "completed" + FAILED = "failed" + CANCELLED = "cancelled" + SCHEDULED = "scheduled" + QUEUED = "queued" + + +class JobResponseType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The job type.""" + + UNKNOWN = "unknown" + EXPORT = "export" + IMPORT = "import" + BACKUP = "backup" + READ_DEVICE_PROPERTIES = "readDeviceProperties" + WRITE_DEVICE_PROPERTIES = "writeDeviceProperties" + UPDATE_DEVICE_CONFIGURATION = "updateDeviceConfiguration" + REBOOT_DEVICE = "rebootDevice" + FACTORY_RESET_DEVICE = "factoryResetDevice" + FIRMWARE_UPDATE = "firmwareUpdate" + SCHEDULE_DEVICE_METHOD = "scheduleDeviceMethod" + SCHEDULE_UPDATE_TWIN = "scheduleUpdateTwin" + RESTORE_FROM_BACKUP = "restoreFromBackup" + FAILOVER_DATA_COPY = "failoverDataCopy" + + +class ModuleConnectionState(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The connection state of the device.""" + + DISCONNECTED = "Disconnected" + CONNECTED = "Connected" + + +class QueryResultType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The query result type.""" + + UNKNOWN = "unknown" + TWIN = "twin" + DEVICE_JOB = "deviceJob" + JOB_RESPONSE = "jobResponse" + RAW = "raw" + ENROLLMENT = "enrollment" + ENROLLMENT_GROUP = "enrollmentGroup" + DEVICE_REGISTRATION = "deviceRegistration" + + +class TwinAuthenticationType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The authentication type used by the device.""" + + SAS = "sas" + SELF_SIGNED = "selfSigned" + CERTIFICATE_AUTHORITY = "certificateAuthority" + NONE = "none" + + +class TwinConnectionState(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The connection state of the device.""" + + DISCONNECTED = "Disconnected" + CONNECTED = "Connected" + + +class TwinStatus(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The enabled status of the device. If disabled, the device cannot connect to the service.""" + + ENABLED = "enabled" + DISABLED = "disabled" diff --git a/src/azure/iot/hub/protocol/models/_models_py3.py b/src/azure/iot/hub/protocol/models/_models_py3.py new file mode 100644 index 0000000..0016182 --- /dev/null +++ b/src/azure/iot/hub/protocol/models/_models_py3.py @@ -0,0 +1,1955 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from collections.abc import MutableMapping +import datetime +from typing import Any, Optional, TYPE_CHECKING, Union + +from .._utils import serialization as _serialization + +if TYPE_CHECKING: + from .. import models as _models +JSON = MutableMapping[str, Any] + + +class AuthenticationMechanism(_serialization.Model): + """AuthenticationMechanism. + + :ivar symmetric_key: The primary and secondary keys used for SAS based authentication. + :vartype symmetric_key: ~azure.iot.hub.protocol.models.SymmetricKey + :ivar x509_thumbprint: The primary and secondary x509 thumbprints used for x509 based + authentication. + :vartype x509_thumbprint: ~azure.iot.hub.protocol.models.X509Thumbprint + :ivar type: The type of authentication used to connect to the service. Known values are: "sas", + "selfSigned", "certificateAuthority", and "none". + :vartype type: str or ~azure.iot.hub.protocol.models.AuthenticationMechanismType + """ + + _attribute_map = { + "symmetric_key": {"key": "symmetricKey", "type": "SymmetricKey"}, + "x509_thumbprint": {"key": "x509Thumbprint", "type": "X509Thumbprint"}, + "type": {"key": "type", "type": "str"}, + } + + def __init__( + self, + *, + symmetric_key: Optional["_models.SymmetricKey"] = None, + x509_thumbprint: Optional["_models.X509Thumbprint"] = None, + type: Optional[Union[str, "_models.AuthenticationMechanismType"]] = None, + **kwargs: Any + ) -> None: + """ + :keyword symmetric_key: The primary and secondary keys used for SAS based authentication. + :paramtype symmetric_key: ~azure.iot.hub.protocol.models.SymmetricKey + :keyword x509_thumbprint: The primary and secondary x509 thumbprints used for x509 based + authentication. + :paramtype x509_thumbprint: ~azure.iot.hub.protocol.models.X509Thumbprint + :keyword type: The type of authentication used to connect to the service. Known values are: + "sas", "selfSigned", "certificateAuthority", and "none". + :paramtype type: str or ~azure.iot.hub.protocol.models.AuthenticationMechanismType + """ + super().__init__(**kwargs) + self.symmetric_key = symmetric_key + self.x509_thumbprint = x509_thumbprint + self.type = type + + +class BulkRegistryOperationResult(_serialization.Model): + """The result of the bulk registry operation. + + :ivar is_successful: The operation result. + :vartype is_successful: bool + :ivar errors: The device registry operation errors. + :vartype errors: list[~azure.iot.hub.protocol.models.DeviceRegistryOperationError] + :ivar warnings: The device registry operation warnings. + :vartype warnings: list[~azure.iot.hub.protocol.models.DeviceRegistryOperationWarning] + """ + + _attribute_map = { + "is_successful": {"key": "isSuccessful", "type": "bool"}, + "errors": {"key": "errors", "type": "[DeviceRegistryOperationError]"}, + "warnings": {"key": "warnings", "type": "[DeviceRegistryOperationWarning]"}, + } + + def __init__( + self, + *, + is_successful: Optional[bool] = None, + errors: Optional[list["_models.DeviceRegistryOperationError"]] = None, + warnings: Optional[list["_models.DeviceRegistryOperationWarning"]] = None, + **kwargs: Any + ) -> None: + """ + :keyword is_successful: The operation result. + :paramtype is_successful: bool + :keyword errors: The device registry operation errors. + :paramtype errors: list[~azure.iot.hub.protocol.models.DeviceRegistryOperationError] + :keyword warnings: The device registry operation warnings. + :paramtype warnings: list[~azure.iot.hub.protocol.models.DeviceRegistryOperationWarning] + """ + super().__init__(**kwargs) + self.is_successful = is_successful + self.errors = errors + self.warnings = warnings + + +class CloudToDeviceMethod(_serialization.Model): + """The parameters to execute a direct method on the device. + + :ivar method_name: The name of the method to execute. + :vartype method_name: str + :ivar payload: The JSON-formatted direct method payload, up to 128kb in size. + :vartype payload: JSON + :ivar response_timeout_in_seconds: + :vartype response_timeout_in_seconds: int + :ivar connect_timeout_in_seconds: + :vartype connect_timeout_in_seconds: int + """ + + _attribute_map = { + "method_name": {"key": "methodName", "type": "str"}, + "payload": {"key": "payload", "type": "object"}, + "response_timeout_in_seconds": {"key": "responseTimeoutInSeconds", "type": "int"}, + "connect_timeout_in_seconds": {"key": "connectTimeoutInSeconds", "type": "int"}, + } + + def __init__( + self, + *, + method_name: Optional[str] = None, + payload: Optional[JSON] = None, + response_timeout_in_seconds: Optional[int] = None, + connect_timeout_in_seconds: Optional[int] = None, + **kwargs: Any + ) -> None: + """ + :keyword method_name: The name of the method to execute. + :paramtype method_name: str + :keyword payload: The JSON-formatted direct method payload, up to 128kb in size. + :paramtype payload: JSON + :keyword response_timeout_in_seconds: + :paramtype response_timeout_in_seconds: int + :keyword connect_timeout_in_seconds: + :paramtype connect_timeout_in_seconds: int + """ + super().__init__(**kwargs) + self.method_name = method_name + self.payload = payload + self.response_timeout_in_seconds = response_timeout_in_seconds + self.connect_timeout_in_seconds = connect_timeout_in_seconds + + +class CloudToDeviceMethodResult(_serialization.Model): + """Represents the Device Method Invocation Results. + + :ivar status: Method invocation result status. + :vartype status: int + :ivar payload: Method invocation result payload. + :vartype payload: JSON + """ + + _attribute_map = { + "status": {"key": "status", "type": "int"}, + "payload": {"key": "payload", "type": "object"}, + } + + def __init__(self, *, status: Optional[int] = None, payload: Optional[JSON] = None, **kwargs: Any) -> None: + """ + :keyword status: Method invocation result status. + :paramtype status: int + :keyword payload: Method invocation result payload. + :paramtype payload: JSON + """ + super().__init__(**kwargs) + self.status = status + self.payload = payload + + +class Configuration(_serialization.Model): + """The configuration for Iot Hub device and module twins. + + :ivar id: The unique identifier of the configuration. + :vartype id: str + :ivar schema_version: The schema version of the configuration. + :vartype schema_version: str + :ivar labels: The key-value pairs used to describe the configuration. + :vartype labels: dict[str, str] + :ivar content: The content of the configuration. + :vartype content: ~azure.iot.hub.protocol.models.ConfigurationContent + :ivar target_condition: The query used to define the targeted devices or modules. The query is + based on twin tags and/or reported properties. + :vartype target_condition: str + :ivar created_time_utc: The creation date and time of the configuration. + :vartype created_time_utc: ~datetime.datetime + :ivar last_updated_time_utc: The update date and time of the configuration. + :vartype last_updated_time_utc: ~datetime.datetime + :ivar priority: The priority number assigned to the configuration. + :vartype priority: int + :ivar system_metrics: The system metrics computed by the IoT Hub that cannot be customized. + :vartype system_metrics: ~azure.iot.hub.protocol.models.ConfigurationMetrics + :ivar metrics: The custom metrics specified by the developer as queries against twin reported + properties. + :vartype metrics: ~azure.iot.hub.protocol.models.ConfigurationMetrics + :ivar etag: The ETag of the configuration. + :vartype etag: str + """ + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "schema_version": {"key": "schemaVersion", "type": "str"}, + "labels": {"key": "labels", "type": "{str}"}, + "content": {"key": "content", "type": "ConfigurationContent"}, + "target_condition": {"key": "targetCondition", "type": "str"}, + "created_time_utc": {"key": "createdTimeUtc", "type": "iso-8601"}, + "last_updated_time_utc": {"key": "lastUpdatedTimeUtc", "type": "iso-8601"}, + "priority": {"key": "priority", "type": "int"}, + "system_metrics": {"key": "systemMetrics", "type": "ConfigurationMetrics"}, + "metrics": {"key": "metrics", "type": "ConfigurationMetrics"}, + "etag": {"key": "etag", "type": "str"}, + } + + def __init__( + self, + *, + id: Optional[str] = None, # pylint: disable=redefined-builtin + schema_version: Optional[str] = None, + labels: Optional[dict[str, str]] = None, + content: Optional["_models.ConfigurationContent"] = None, + target_condition: Optional[str] = None, + created_time_utc: Optional[datetime.datetime] = None, + last_updated_time_utc: Optional[datetime.datetime] = None, + priority: Optional[int] = None, + system_metrics: Optional["_models.ConfigurationMetrics"] = None, + metrics: Optional["_models.ConfigurationMetrics"] = None, + etag: Optional[str] = None, + **kwargs: Any + ) -> None: + """ + :keyword id: The unique identifier of the configuration. + :paramtype id: str + :keyword schema_version: The schema version of the configuration. + :paramtype schema_version: str + :keyword labels: The key-value pairs used to describe the configuration. + :paramtype labels: dict[str, str] + :keyword content: The content of the configuration. + :paramtype content: ~azure.iot.hub.protocol.models.ConfigurationContent + :keyword target_condition: The query used to define the targeted devices or modules. The query + is based on twin tags and/or reported properties. + :paramtype target_condition: str + :keyword created_time_utc: The creation date and time of the configuration. + :paramtype created_time_utc: ~datetime.datetime + :keyword last_updated_time_utc: The update date and time of the configuration. + :paramtype last_updated_time_utc: ~datetime.datetime + :keyword priority: The priority number assigned to the configuration. + :paramtype priority: int + :keyword system_metrics: The system metrics computed by the IoT Hub that cannot be customized. + :paramtype system_metrics: ~azure.iot.hub.protocol.models.ConfigurationMetrics + :keyword metrics: The custom metrics specified by the developer as queries against twin + reported properties. + :paramtype metrics: ~azure.iot.hub.protocol.models.ConfigurationMetrics + :keyword etag: The ETag of the configuration. + :paramtype etag: str + """ + super().__init__(**kwargs) + self.id = id + self.schema_version = schema_version + self.labels = labels + self.content = content + self.target_condition = target_condition + self.created_time_utc = created_time_utc + self.last_updated_time_utc = last_updated_time_utc + self.priority = priority + self.system_metrics = system_metrics + self.metrics = metrics + self.etag = etag + + +class ConfigurationContent(_serialization.Model): + """The configuration content for devices or modules on edge devices. + + :ivar device_content: The device configuration content. + :vartype device_content: dict[str, JSON] + :ivar modules_content: The modules configuration content. + :vartype modules_content: dict[str, dict[str, JSON]] + :ivar module_content: The module configuration content. + :vartype module_content: dict[str, JSON] + """ + + _attribute_map = { + "device_content": {"key": "deviceContent", "type": "{object}"}, + "modules_content": {"key": "modulesContent", "type": "{{object}}"}, + "module_content": {"key": "moduleContent", "type": "{object}"}, + } + + def __init__( + self, + *, + device_content: Optional[dict[str, JSON]] = None, + modules_content: Optional[dict[str, dict[str, JSON]]] = None, + module_content: Optional[dict[str, JSON]] = None, + **kwargs: Any + ) -> None: + """ + :keyword device_content: The device configuration content. + :paramtype device_content: dict[str, JSON] + :keyword modules_content: The modules configuration content. + :paramtype modules_content: dict[str, dict[str, JSON]] + :keyword module_content: The module configuration content. + :paramtype module_content: dict[str, JSON] + """ + super().__init__(**kwargs) + self.device_content = device_content + self.modules_content = modules_content + self.module_content = module_content + + +class ConfigurationMetrics(_serialization.Model): + """The configuration metrics for Iot Hub devices and modules. + + :ivar results: The results of the metrics collection queries. + :vartype results: dict[str, int] + :ivar queries: The key-value pairs with queries and their identifier. + :vartype queries: dict[str, str] + """ + + _attribute_map = { + "results": {"key": "results", "type": "{int}"}, + "queries": {"key": "queries", "type": "{str}"}, + } + + def __init__( + self, *, results: Optional[dict[str, int]] = None, queries: Optional[dict[str, str]] = None, **kwargs: Any + ) -> None: + """ + :keyword results: The results of the metrics collection queries. + :paramtype results: dict[str, int] + :keyword queries: The key-value pairs with queries and their identifier. + :paramtype queries: dict[str, str] + """ + super().__init__(**kwargs) + self.results = results + self.queries = queries + + +class ConfigurationQueriesTestInput(_serialization.Model): + """ConfigurationQueriesTestInput. + + :ivar target_condition: The query used to define targeted devices or modules. The query is + based on twin tags and/or reported properties. + :vartype target_condition: str + :ivar custom_metric_queries: The key-value pairs with queries and their identifier. + :vartype custom_metric_queries: dict[str, str] + """ + + _attribute_map = { + "target_condition": {"key": "targetCondition", "type": "str"}, + "custom_metric_queries": {"key": "customMetricQueries", "type": "{str}"}, + } + + def __init__( + self, + *, + target_condition: Optional[str] = None, + custom_metric_queries: Optional[dict[str, str]] = None, + **kwargs: Any + ) -> None: + """ + :keyword target_condition: The query used to define targeted devices or modules. The query is + based on twin tags and/or reported properties. + :paramtype target_condition: str + :keyword custom_metric_queries: The key-value pairs with queries and their identifier. + :paramtype custom_metric_queries: dict[str, str] + """ + super().__init__(**kwargs) + self.target_condition = target_condition + self.custom_metric_queries = custom_metric_queries + + +class ConfigurationQueriesTestResponse(_serialization.Model): + """ConfigurationQueriesTestResponse. + + :ivar target_condition_error: The errors from running the target condition query. + :vartype target_condition_error: str + :ivar custom_metric_query_errors: The errors from running the custom metric query. + :vartype custom_metric_query_errors: dict[str, str] + """ + + _attribute_map = { + "target_condition_error": {"key": "targetConditionError", "type": "str"}, + "custom_metric_query_errors": {"key": "customMetricQueryErrors", "type": "{str}"}, + } + + def __init__( + self, + *, + target_condition_error: Optional[str] = None, + custom_metric_query_errors: Optional[dict[str, str]] = None, + **kwargs: Any + ) -> None: + """ + :keyword target_condition_error: The errors from running the target condition query. + :paramtype target_condition_error: str + :keyword custom_metric_query_errors: The errors from running the custom metric query. + :paramtype custom_metric_query_errors: dict[str, str] + """ + super().__init__(**kwargs) + self.target_condition_error = target_condition_error + self.custom_metric_query_errors = custom_metric_query_errors + + +class Device(_serialization.Model): + """Device. + + :ivar device_id: The unique identifier of the device. + :vartype device_id: str + :ivar generation_id: The IoT Hub-generated, case-sensitive string up to 128 characters long. + This value is used to distinguish devices with the same deviceId, when they have been deleted + and re-created. + :vartype generation_id: str + :ivar etag: The string representing a weak ETag for the device identity, as per RFC7232. + :vartype etag: str + :ivar connection_state: The state of the device. Known values are: "Disconnected" and + "Connected". + :vartype connection_state: str or ~azure.iot.hub.protocol.models.DeviceConnectionState + :ivar status: The status of the device. If the status disabled, a device cannot connect to the + service. Known values are: "enabled" and "disabled". + :vartype status: str or ~azure.iot.hub.protocol.models.DeviceStatus + :ivar status_reason: The 128 character-long string that stores the reason for the device + identity status. All UTF-8 characters are allowed. + :vartype status_reason: str + :ivar connection_state_updated_time: The date and time the connection state was last updated. + :vartype connection_state_updated_time: ~datetime.datetime + :ivar status_updated_time: The date and time when the status field was last updated. + :vartype status_updated_time: ~datetime.datetime + :ivar last_activity_time: The date and last time the device last connected, received, or sent a + message. + :vartype last_activity_time: ~datetime.datetime + :ivar cloud_to_device_message_count: The number of cloud-to-device messages currently queued to + be sent to the device. + :vartype cloud_to_device_message_count: int + :ivar authentication: The authentication mechanism used by the device. + :vartype authentication: ~azure.iot.hub.protocol.models.AuthenticationMechanism + :ivar capabilities: The set of capabilities of the device. For example, if this device is an + edge device or not. + :vartype capabilities: ~azure.iot.hub.protocol.models.DeviceCapabilities + :ivar device_scope: The scope of the device. Auto generated and immutable for edge devices and + modifiable in leaf devices to create child/parent relationship. + :vartype device_scope: str + :ivar parent_scopes: The scopes of the upper level edge devices if applicable. Only available + for edge devices. + :vartype parent_scopes: list[str] + """ + + _attribute_map = { + "device_id": {"key": "deviceId", "type": "str"}, + "generation_id": {"key": "generationId", "type": "str"}, + "etag": {"key": "etag", "type": "str"}, + "connection_state": {"key": "connectionState", "type": "str"}, + "status": {"key": "status", "type": "str"}, + "status_reason": {"key": "statusReason", "type": "str"}, + "connection_state_updated_time": {"key": "connectionStateUpdatedTime", "type": "iso-8601"}, + "status_updated_time": {"key": "statusUpdatedTime", "type": "iso-8601"}, + "last_activity_time": {"key": "lastActivityTime", "type": "iso-8601"}, + "cloud_to_device_message_count": {"key": "cloudToDeviceMessageCount", "type": "int"}, + "authentication": {"key": "authentication", "type": "AuthenticationMechanism"}, + "capabilities": {"key": "capabilities", "type": "DeviceCapabilities"}, + "device_scope": {"key": "deviceScope", "type": "str"}, + "parent_scopes": {"key": "parentScopes", "type": "[str]"}, + } + + def __init__( + self, + *, + device_id: Optional[str] = None, + generation_id: Optional[str] = None, + etag: Optional[str] = None, + connection_state: Optional[Union[str, "_models.DeviceConnectionState"]] = None, + status: Optional[Union[str, "_models.DeviceStatus"]] = None, + status_reason: Optional[str] = None, + connection_state_updated_time: Optional[datetime.datetime] = None, + status_updated_time: Optional[datetime.datetime] = None, + last_activity_time: Optional[datetime.datetime] = None, + cloud_to_device_message_count: Optional[int] = None, + authentication: Optional["_models.AuthenticationMechanism"] = None, + capabilities: Optional["_models.DeviceCapabilities"] = None, + device_scope: Optional[str] = None, + parent_scopes: Optional[list[str]] = None, + **kwargs: Any + ) -> None: + """ + :keyword device_id: The unique identifier of the device. + :paramtype device_id: str + :keyword generation_id: The IoT Hub-generated, case-sensitive string up to 128 characters long. + This value is used to distinguish devices with the same deviceId, when they have been deleted + and re-created. + :paramtype generation_id: str + :keyword etag: The string representing a weak ETag for the device identity, as per RFC7232. + :paramtype etag: str + :keyword connection_state: The state of the device. Known values are: "Disconnected" and + "Connected". + :paramtype connection_state: str or ~azure.iot.hub.protocol.models.DeviceConnectionState + :keyword status: The status of the device. If the status disabled, a device cannot connect to + the service. Known values are: "enabled" and "disabled". + :paramtype status: str or ~azure.iot.hub.protocol.models.DeviceStatus + :keyword status_reason: The 128 character-long string that stores the reason for the device + identity status. All UTF-8 characters are allowed. + :paramtype status_reason: str + :keyword connection_state_updated_time: The date and time the connection state was last + updated. + :paramtype connection_state_updated_time: ~datetime.datetime + :keyword status_updated_time: The date and time when the status field was last updated. + :paramtype status_updated_time: ~datetime.datetime + :keyword last_activity_time: The date and last time the device last connected, received, or + sent a message. + :paramtype last_activity_time: ~datetime.datetime + :keyword cloud_to_device_message_count: The number of cloud-to-device messages currently queued + to be sent to the device. + :paramtype cloud_to_device_message_count: int + :keyword authentication: The authentication mechanism used by the device. + :paramtype authentication: ~azure.iot.hub.protocol.models.AuthenticationMechanism + :keyword capabilities: The set of capabilities of the device. For example, if this device is an + edge device or not. + :paramtype capabilities: ~azure.iot.hub.protocol.models.DeviceCapabilities + :keyword device_scope: The scope of the device. Auto generated and immutable for edge devices + and modifiable in leaf devices to create child/parent relationship. + :paramtype device_scope: str + :keyword parent_scopes: The scopes of the upper level edge devices if applicable. Only + available for edge devices. + :paramtype parent_scopes: list[str] + """ + super().__init__(**kwargs) + self.device_id = device_id + self.generation_id = generation_id + self.etag = etag + self.connection_state = connection_state + self.status = status + self.status_reason = status_reason + self.connection_state_updated_time = connection_state_updated_time + self.status_updated_time = status_updated_time + self.last_activity_time = last_activity_time + self.cloud_to_device_message_count = cloud_to_device_message_count + self.authentication = authentication + self.capabilities = capabilities + self.device_scope = device_scope + self.parent_scopes = parent_scopes + + +class DeviceCapabilities(_serialization.Model): + """The status of capabilities enabled on the device. + + :ivar iot_edge: The property that determines if the device is an edge device or not. + :vartype iot_edge: bool + """ + + _attribute_map = { + "iot_edge": {"key": "iotEdge", "type": "bool"}, + } + + def __init__(self, *, iot_edge: Optional[bool] = None, **kwargs: Any) -> None: + """ + :keyword iot_edge: The property that determines if the device is an edge device or not. + :paramtype iot_edge: bool + """ + super().__init__(**kwargs) + self.iot_edge = iot_edge + + +class DeviceJobStatistics(_serialization.Model): + """The job statistics regarding execution status. + + :ivar device_count: The number of devices targeted by the job. + :vartype device_count: int + :ivar failed_count: The number of failed jobs. + :vartype failed_count: int + :ivar succeeded_count: The number of succeeded jobs. + :vartype succeeded_count: int + :ivar running_count: The number of running jobs. + :vartype running_count: int + :ivar pending_count: The number of pending (scheduled) jobs. + :vartype pending_count: int + """ + + _attribute_map = { + "device_count": {"key": "deviceCount", "type": "int"}, + "failed_count": {"key": "failedCount", "type": "int"}, + "succeeded_count": {"key": "succeededCount", "type": "int"}, + "running_count": {"key": "runningCount", "type": "int"}, + "pending_count": {"key": "pendingCount", "type": "int"}, + } + + def __init__( + self, + *, + device_count: Optional[int] = None, + failed_count: Optional[int] = None, + succeeded_count: Optional[int] = None, + running_count: Optional[int] = None, + pending_count: Optional[int] = None, + **kwargs: Any + ) -> None: + """ + :keyword device_count: The number of devices targeted by the job. + :paramtype device_count: int + :keyword failed_count: The number of failed jobs. + :paramtype failed_count: int + :keyword succeeded_count: The number of succeeded jobs. + :paramtype succeeded_count: int + :keyword running_count: The number of running jobs. + :paramtype running_count: int + :keyword pending_count: The number of pending (scheduled) jobs. + :paramtype pending_count: int + """ + super().__init__(**kwargs) + self.device_count = device_count + self.failed_count = failed_count + self.succeeded_count = succeeded_count + self.running_count = running_count + self.pending_count = pending_count + + +class DeviceRegistryOperationError(_serialization.Model): + """The device registry operation error details. + + :ivar device_id: The unique identifier of the device. + :vartype device_id: str + :ivar error_code: The error code. Known values are: "InvalidErrorCode", "GenericBadRequest", + "InvalidProtocolVersion", "DeviceInvalidResultCount", "InvalidOperation", "ArgumentInvalid", + "ArgumentNull", "IotHubFormatError", "DeviceStorageEntitySerializationError", + "BlobContainerValidationError", "ImportWarningExistsError", "InvalidSchemaVersion", + "DeviceDefinedMultipleTimes", "DeserializationError", "BulkRegistryOperationFailure", + "DefaultStorageEndpointNotConfigured", "InvalidFileUploadCorrelationId", + "ExpiredFileUploadCorrelationId", "InvalidStorageEndpoint", "InvalidMessagingEndpoint", + "InvalidFileUploadCompletionStatus", "InvalidStorageEndpointOrBlob", "RequestCanceled", + "InvalidStorageEndpointProperty", "EtagDoesNotMatch", "RequestTimedOut", + "UnsupportedOperationOnReplica", "NullMessage", "ConnectionForcefullyClosedOnNewConnection", + "InvalidDeviceScope", "ConnectionForcefullyClosedOnFaultInjection", + "ConnectionRejectedOnFaultInjection", "InvalidEndpointAuthenticationType", + "ManagedIdentityNotEnabled", "InvalidRouteTestInput", "InvalidSourceOnRoute", + "RoutingNotEnabled", "InvalidContentEncodingOrType", "InvalidEndorsementKey", + "InvalidRegistrationId", "InvalidStorageRootKey", "InvalidEnrollmentGroupId", + "TooManyEnrollments", "RegistrationIdDefinedMultipleTimes", "CustomAllocationFailed", + "CustomAllocationIotHubNotSpecified", "CustomAllocationUnauthorizedAccess", + "CannotRegisterModuleToModule", "TenantHubRoutingNotEnabled", + "InvalidConfigurationTargetCondition", "InvalidConfigurationContent", + "CannotModifyImmutableConfigurationContent", "InvalidConfigurationCustomMetricsQuery", + "InvalidPnPInterfaceDefinition", "InvalidPnPDesiredProperties", "InvalidPnPReportedProperties", + "InvalidPnPWritableReportedProperties", "InvalidDigitalTwinJsonPatch", + "InvalidDigitalTwinPayload", "InvalidDigitalTwinPatch", "InvalidDigitalTwinPatchPath", + "GenericUnauthorized", "IotHubNotFound", "IotHubUnauthorizedAccess", "IotHubUnauthorized", + "ElasticPoolNotFound", "SystemModuleModifyUnauthorizedAccess", "GenericForbidden", + "IotHubSuspended", "IotHubQuotaExceeded", "JobQuotaExceeded", + "DeviceMaximumQueueDepthExceeded", "IotHubMaxCbsTokenExceeded", + "DeviceMaximumActiveFileUploadLimitExceeded", "DeviceMaximumQueueSizeExceeded", + "RoutingEndpointResponseForbidden", "InvalidMessageExpiryTime", + "OperationNotAvailableInCurrentTier", "KeyEncryptionKeyRevoked", + "DeviceModelMaxPropertiesExceeded", "DeviceModelMaxIndexablePropertiesExceeded", + "IotDpsSuspended", "IotDpsSuspending", "GenericNotFound", "DeviceNotFound", "JobNotFound", + "QuotaMetricNotFound", "SystemPropertyNotFound", "AmqpAddressNotFound", + "RoutingEndpointResponseNotFound", "CertificateNotFound", "ElasticPoolTenantHubNotFound", + "ModuleNotFound", "AzureTableStoreNotFound", "IotHubFailingOver", "FeatureNotSupported", + "DigitalTwinInterfaceNotFound", "QueryStoreClusterNotFound", "DeviceNotOnline", + "DeviceConnectionClosedRemotely", "EnrollmentNotFound", "DeviceRegistrationNotFound", + "AsyncOperationNotFound", "EnrollmentGroupNotFound", "DeviceRecordNotFound", + "GroupRecordNotFound", "DeviceGroupNotFound", "ProvisioningSettingsNotFound", + "ProvisioningRecordNotFound", "LinkedHubNotFound", "CertificateAuthorityNotFound", + "ConfigurationNotFound", "GroupNotFound", "DigitalTwinModelNotFound", + "InterfaceNameModelNotFound", "GenericMethodNotAllowed", "OperationNotAllowedInCurrentState", + "ImportDevicesNotSupported", "BulkAddDevicesNotSupported", "GenericConflict", + "DeviceAlreadyExists", "LinkCreationConflict", "CallbackSubscriptionConflict", + "ModelAlreadyExists", "DeviceLocked", "DeviceJobAlreadyExists", "JobAlreadyExists", + "EnrollmentConflict", "EnrollmentGroupConflict", "RegistrationStatusConflict", + "DeviceRecordConflict", "GroupRecordConflict", "DeviceGroupConflict", + "ProvisioningSettingsConflict", "ProvisioningRecordConflict", "LinkedHubConflict", + "CertificateAuthorityConflict", "ModuleAlreadyExistsOnDevice", "ConfigurationAlreadyExists", + "ApplyConfigurationAlreadyInProgressOnDevice", "DigitalTwinModelAlreadyExists", + "DigitalTwinModelExistsWithOtherModelType", "InterfaceNameModelAlreadyExists", + "GenericPreconditionFailed", "PreconditionFailed", "DeviceMessageLockLost", + "JobRunPreconditionFailed", "InflightMessagesInLink", "GenericRequestEntityTooLarge", + "MessageTooLarge", "TooManyDevices", "TooManyModulesOnDevice", + "ConfigurationCountLimitExceeded", "DigitalTwinModelCountLimitExceeded", + "InterfaceNameCompressionModelCountLimitExceeded", "GenericUnsupportedMediaType", + "IncompatibleDataType", "GenericTooManyRequests", "ThrottlingException", + "ThrottleBacklogLimitExceeded", "ThrottlingBacklogTimeout", + "ThrottlingMaxActiveJobCountExceeded", "DeviceThrottlingLimitExceeded", "ClientClosedRequest", + "GenericServerError", "ServerError", "JobCancelled", "StatisticsRetrievalError", + "ConnectionForcefullyClosed", "InvalidBlobState", "BackupTimedOut", "AzureStorageTimeout", + "GenericTimeout", "InvalidThrottleParameter", "EventHubLinkAlreadyClosed", + "ReliableBlobStoreError", "RetryAttemptsExhausted", "AzureTableStoreError", + "CheckpointStoreNotFound", "DocumentDbInvalidReturnValue", "ReliableDocDbStoreStoreError", + "ReliableBlobStoreTimeoutError", "ConfigReadFailed", "InvalidContainerReceiveLink", + "InvalidPartitionEpoch", "RestoreTimedOut", "StreamReservationFailure", "SerializationError", + "UnexpectedPropertyValue", "OrchestrationOperationFailed", "ModelRepoEndpointError", + "ResolutionError", "UnableToFetchCredentials", "UnableToFetchTenantInfo", + "UnableToShareIdentity", "UnableToExpandDiscoveryInfo", "UnableToExpandComponentInfo", + "UnableToCompressComponentInfo", "UnableToCompressDiscoveryInfo", "OrphanDiscoveryDocument", + "GenericBadGateway", "InvalidResponseWhileProxying", "GenericServiceUnavailable", + "ServiceUnavailable", "PartitionNotFound", "IotHubActivationFailed", "ServerBusy", + "IotHubRestoring", "ReceiveLinkOpensThrottled", "ConnectionUnavailable", "DeviceUnavailable", + "ConfigurationNotAvailable", "GroupNotAvailable", "HostingServiceNotAvailable", + "GenericGatewayTimeout", and "GatewayTimeout". + :vartype error_code: str or ~azure.iot.hub.protocol.models.DeviceRegistryOperationErrorCode + :ivar error_status: The details of the error. + :vartype error_status: str + :ivar module_id: The unique identifier of the module, if applicable. + :vartype module_id: str + :ivar operation: The type of the operation that failed. + :vartype operation: str + """ + + _attribute_map = { + "device_id": {"key": "deviceId", "type": "str"}, + "error_code": {"key": "errorCode", "type": "str"}, + "error_status": {"key": "errorStatus", "type": "str"}, + "module_id": {"key": "moduleId", "type": "str"}, + "operation": {"key": "operation", "type": "str"}, + } + + def __init__( + self, + *, + device_id: Optional[str] = None, + error_code: Optional[Union[str, "_models.DeviceRegistryOperationErrorCode"]] = None, + error_status: Optional[str] = None, + module_id: Optional[str] = None, + operation: Optional[str] = None, + **kwargs: Any + ) -> None: + """ + :keyword device_id: The unique identifier of the device. + :paramtype device_id: str + :keyword error_code: The error code. Known values are: "InvalidErrorCode", "GenericBadRequest", + "InvalidProtocolVersion", "DeviceInvalidResultCount", "InvalidOperation", "ArgumentInvalid", + "ArgumentNull", "IotHubFormatError", "DeviceStorageEntitySerializationError", + "BlobContainerValidationError", "ImportWarningExistsError", "InvalidSchemaVersion", + "DeviceDefinedMultipleTimes", "DeserializationError", "BulkRegistryOperationFailure", + "DefaultStorageEndpointNotConfigured", "InvalidFileUploadCorrelationId", + "ExpiredFileUploadCorrelationId", "InvalidStorageEndpoint", "InvalidMessagingEndpoint", + "InvalidFileUploadCompletionStatus", "InvalidStorageEndpointOrBlob", "RequestCanceled", + "InvalidStorageEndpointProperty", "EtagDoesNotMatch", "RequestTimedOut", + "UnsupportedOperationOnReplica", "NullMessage", "ConnectionForcefullyClosedOnNewConnection", + "InvalidDeviceScope", "ConnectionForcefullyClosedOnFaultInjection", + "ConnectionRejectedOnFaultInjection", "InvalidEndpointAuthenticationType", + "ManagedIdentityNotEnabled", "InvalidRouteTestInput", "InvalidSourceOnRoute", + "RoutingNotEnabled", "InvalidContentEncodingOrType", "InvalidEndorsementKey", + "InvalidRegistrationId", "InvalidStorageRootKey", "InvalidEnrollmentGroupId", + "TooManyEnrollments", "RegistrationIdDefinedMultipleTimes", "CustomAllocationFailed", + "CustomAllocationIotHubNotSpecified", "CustomAllocationUnauthorizedAccess", + "CannotRegisterModuleToModule", "TenantHubRoutingNotEnabled", + "InvalidConfigurationTargetCondition", "InvalidConfigurationContent", + "CannotModifyImmutableConfigurationContent", "InvalidConfigurationCustomMetricsQuery", + "InvalidPnPInterfaceDefinition", "InvalidPnPDesiredProperties", "InvalidPnPReportedProperties", + "InvalidPnPWritableReportedProperties", "InvalidDigitalTwinJsonPatch", + "InvalidDigitalTwinPayload", "InvalidDigitalTwinPatch", "InvalidDigitalTwinPatchPath", + "GenericUnauthorized", "IotHubNotFound", "IotHubUnauthorizedAccess", "IotHubUnauthorized", + "ElasticPoolNotFound", "SystemModuleModifyUnauthorizedAccess", "GenericForbidden", + "IotHubSuspended", "IotHubQuotaExceeded", "JobQuotaExceeded", + "DeviceMaximumQueueDepthExceeded", "IotHubMaxCbsTokenExceeded", + "DeviceMaximumActiveFileUploadLimitExceeded", "DeviceMaximumQueueSizeExceeded", + "RoutingEndpointResponseForbidden", "InvalidMessageExpiryTime", + "OperationNotAvailableInCurrentTier", "KeyEncryptionKeyRevoked", + "DeviceModelMaxPropertiesExceeded", "DeviceModelMaxIndexablePropertiesExceeded", + "IotDpsSuspended", "IotDpsSuspending", "GenericNotFound", "DeviceNotFound", "JobNotFound", + "QuotaMetricNotFound", "SystemPropertyNotFound", "AmqpAddressNotFound", + "RoutingEndpointResponseNotFound", "CertificateNotFound", "ElasticPoolTenantHubNotFound", + "ModuleNotFound", "AzureTableStoreNotFound", "IotHubFailingOver", "FeatureNotSupported", + "DigitalTwinInterfaceNotFound", "QueryStoreClusterNotFound", "DeviceNotOnline", + "DeviceConnectionClosedRemotely", "EnrollmentNotFound", "DeviceRegistrationNotFound", + "AsyncOperationNotFound", "EnrollmentGroupNotFound", "DeviceRecordNotFound", + "GroupRecordNotFound", "DeviceGroupNotFound", "ProvisioningSettingsNotFound", + "ProvisioningRecordNotFound", "LinkedHubNotFound", "CertificateAuthorityNotFound", + "ConfigurationNotFound", "GroupNotFound", "DigitalTwinModelNotFound", + "InterfaceNameModelNotFound", "GenericMethodNotAllowed", "OperationNotAllowedInCurrentState", + "ImportDevicesNotSupported", "BulkAddDevicesNotSupported", "GenericConflict", + "DeviceAlreadyExists", "LinkCreationConflict", "CallbackSubscriptionConflict", + "ModelAlreadyExists", "DeviceLocked", "DeviceJobAlreadyExists", "JobAlreadyExists", + "EnrollmentConflict", "EnrollmentGroupConflict", "RegistrationStatusConflict", + "DeviceRecordConflict", "GroupRecordConflict", "DeviceGroupConflict", + "ProvisioningSettingsConflict", "ProvisioningRecordConflict", "LinkedHubConflict", + "CertificateAuthorityConflict", "ModuleAlreadyExistsOnDevice", "ConfigurationAlreadyExists", + "ApplyConfigurationAlreadyInProgressOnDevice", "DigitalTwinModelAlreadyExists", + "DigitalTwinModelExistsWithOtherModelType", "InterfaceNameModelAlreadyExists", + "GenericPreconditionFailed", "PreconditionFailed", "DeviceMessageLockLost", + "JobRunPreconditionFailed", "InflightMessagesInLink", "GenericRequestEntityTooLarge", + "MessageTooLarge", "TooManyDevices", "TooManyModulesOnDevice", + "ConfigurationCountLimitExceeded", "DigitalTwinModelCountLimitExceeded", + "InterfaceNameCompressionModelCountLimitExceeded", "GenericUnsupportedMediaType", + "IncompatibleDataType", "GenericTooManyRequests", "ThrottlingException", + "ThrottleBacklogLimitExceeded", "ThrottlingBacklogTimeout", + "ThrottlingMaxActiveJobCountExceeded", "DeviceThrottlingLimitExceeded", "ClientClosedRequest", + "GenericServerError", "ServerError", "JobCancelled", "StatisticsRetrievalError", + "ConnectionForcefullyClosed", "InvalidBlobState", "BackupTimedOut", "AzureStorageTimeout", + "GenericTimeout", "InvalidThrottleParameter", "EventHubLinkAlreadyClosed", + "ReliableBlobStoreError", "RetryAttemptsExhausted", "AzureTableStoreError", + "CheckpointStoreNotFound", "DocumentDbInvalidReturnValue", "ReliableDocDbStoreStoreError", + "ReliableBlobStoreTimeoutError", "ConfigReadFailed", "InvalidContainerReceiveLink", + "InvalidPartitionEpoch", "RestoreTimedOut", "StreamReservationFailure", "SerializationError", + "UnexpectedPropertyValue", "OrchestrationOperationFailed", "ModelRepoEndpointError", + "ResolutionError", "UnableToFetchCredentials", "UnableToFetchTenantInfo", + "UnableToShareIdentity", "UnableToExpandDiscoveryInfo", "UnableToExpandComponentInfo", + "UnableToCompressComponentInfo", "UnableToCompressDiscoveryInfo", "OrphanDiscoveryDocument", + "GenericBadGateway", "InvalidResponseWhileProxying", "GenericServiceUnavailable", + "ServiceUnavailable", "PartitionNotFound", "IotHubActivationFailed", "ServerBusy", + "IotHubRestoring", "ReceiveLinkOpensThrottled", "ConnectionUnavailable", "DeviceUnavailable", + "ConfigurationNotAvailable", "GroupNotAvailable", "HostingServiceNotAvailable", + "GenericGatewayTimeout", and "GatewayTimeout". + :paramtype error_code: str or ~azure.iot.hub.protocol.models.DeviceRegistryOperationErrorCode + :keyword error_status: The details of the error. + :paramtype error_status: str + :keyword module_id: The unique identifier of the module, if applicable. + :paramtype module_id: str + :keyword operation: The type of the operation that failed. + :paramtype operation: str + """ + super().__init__(**kwargs) + self.device_id = device_id + self.error_code = error_code + self.error_status = error_status + self.module_id = module_id + self.operation = operation + + +class DeviceRegistryOperationWarning(_serialization.Model): + """The device registry operation warning details. + + :ivar device_id: The unique identifier of the device. + :vartype device_id: str + :ivar warning_code: The warning code. "DeviceRegisteredWithoutTwin" + :vartype warning_code: str or ~azure.iot.hub.protocol.models.DeviceRegistryOperationWarningCode + :ivar warning_status: The details of the warning. + :vartype warning_status: str + """ + + _attribute_map = { + "device_id": {"key": "deviceId", "type": "str"}, + "warning_code": {"key": "warningCode", "type": "str"}, + "warning_status": {"key": "warningStatus", "type": "str"}, + } + + def __init__( + self, + *, + device_id: Optional[str] = None, + warning_code: Optional[Union[str, "_models.DeviceRegistryOperationWarningCode"]] = None, + warning_status: Optional[str] = None, + **kwargs: Any + ) -> None: + """ + :keyword device_id: The unique identifier of the device. + :paramtype device_id: str + :keyword warning_code: The warning code. "DeviceRegisteredWithoutTwin" + :paramtype warning_code: str or + ~azure.iot.hub.protocol.models.DeviceRegistryOperationWarningCode + :keyword warning_status: The details of the warning. + :paramtype warning_status: str + """ + super().__init__(**kwargs) + self.device_id = device_id + self.warning_code = warning_code + self.warning_status = warning_status + + +class ExportImportDevice(_serialization.Model): + """ExportImportDevice. + + :ivar id: The unique identifier of the device. + :vartype id: str + :ivar module_id: The unique identifier of the module, if applicable. + :vartype module_id: str + :ivar e_tag: The string representing a weak ETag for the device RFC7232. The value is only used + if import mode is updateIfMatchETag, in that case the import operation is performed only if + this ETag matches the value maintained by the server. + :vartype e_tag: str + :ivar import_mode: The type of registry operation and ETag preferences. Known values are: + "create", "update", "updateIfMatchETag", "delete", "deleteIfMatchETag", "updateTwin", and + "updateTwinIfMatchETag". + :vartype import_mode: str or ~azure.iot.hub.protocol.models.ExportImportDeviceImportMode + :ivar status: The status of the module. If disabled, the module cannot connect to the service. + Known values are: "enabled" and "disabled". + :vartype status: str or ~azure.iot.hub.protocol.models.ExportImportDeviceStatus + :ivar status_reason: The 128 character-long string that stores the reason for the device + identity status. All UTF-8 characters are allowed. + :vartype status_reason: str + :ivar authentication: The authentication mechanism used by the module. This parameter is + optional and defaults to SAS if not provided. In that case, primary/secondary access keys are + auto-generated. + :vartype authentication: ~azure.iot.hub.protocol.models.AuthenticationMechanism + :ivar twin_e_tag: The string representing a weak ETag for the device twin RFC7232. The value is + only used if import mode is updateIfMatchETag, in that case the import operation is performed + only if this ETag matches the value maintained by the server. + :vartype twin_e_tag: str + :ivar tags: The JSON document read and written by the solution back end. The tags are not + visible to device apps. + :vartype tags: dict[str, JSON] + :ivar properties: The desired and reported properties for the device. + :vartype properties: ~azure.iot.hub.protocol.models.PropertyContainer + :ivar capabilities: The status of capabilities enabled on the device. + :vartype capabilities: ~azure.iot.hub.protocol.models.DeviceCapabilities + :ivar device_scope: The scope of the device. + :vartype device_scope: str + :ivar parent_scopes: The scopes of the upper level edge devices if applicable. Only available + for edge devices. + :vartype parent_scopes: list[str] + """ + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "module_id": {"key": "moduleId", "type": "str"}, + "e_tag": {"key": "eTag", "type": "str"}, + "import_mode": {"key": "importMode", "type": "str"}, + "status": {"key": "status", "type": "str"}, + "status_reason": {"key": "statusReason", "type": "str"}, + "authentication": {"key": "authentication", "type": "AuthenticationMechanism"}, + "twin_e_tag": {"key": "twinETag", "type": "str"}, + "tags": {"key": "tags", "type": "{object}"}, + "properties": {"key": "properties", "type": "PropertyContainer"}, + "capabilities": {"key": "capabilities", "type": "DeviceCapabilities"}, + "device_scope": {"key": "deviceScope", "type": "str"}, + "parent_scopes": {"key": "parentScopes", "type": "[str]"}, + } + + def __init__( + self, + *, + id: Optional[str] = None, # pylint: disable=redefined-builtin + module_id: Optional[str] = None, + e_tag: Optional[str] = None, + import_mode: Optional[Union[str, "_models.ExportImportDeviceImportMode"]] = None, + status: Optional[Union[str, "_models.ExportImportDeviceStatus"]] = None, + status_reason: Optional[str] = None, + authentication: Optional["_models.AuthenticationMechanism"] = None, + twin_e_tag: Optional[str] = None, + tags: Optional[dict[str, JSON]] = None, + properties: Optional["_models.PropertyContainer"] = None, + capabilities: Optional["_models.DeviceCapabilities"] = None, + device_scope: Optional[str] = None, + parent_scopes: Optional[list[str]] = None, + **kwargs: Any + ) -> None: + """ + :keyword id: The unique identifier of the device. + :paramtype id: str + :keyword module_id: The unique identifier of the module, if applicable. + :paramtype module_id: str + :keyword e_tag: The string representing a weak ETag for the device RFC7232. The value is only + used if import mode is updateIfMatchETag, in that case the import operation is performed only + if this ETag matches the value maintained by the server. + :paramtype e_tag: str + :keyword import_mode: The type of registry operation and ETag preferences. Known values are: + "create", "update", "updateIfMatchETag", "delete", "deleteIfMatchETag", "updateTwin", and + "updateTwinIfMatchETag". + :paramtype import_mode: str or ~azure.iot.hub.protocol.models.ExportImportDeviceImportMode + :keyword status: The status of the module. If disabled, the module cannot connect to the + service. Known values are: "enabled" and "disabled". + :paramtype status: str or ~azure.iot.hub.protocol.models.ExportImportDeviceStatus + :keyword status_reason: The 128 character-long string that stores the reason for the device + identity status. All UTF-8 characters are allowed. + :paramtype status_reason: str + :keyword authentication: The authentication mechanism used by the module. This parameter is + optional and defaults to SAS if not provided. In that case, primary/secondary access keys are + auto-generated. + :paramtype authentication: ~azure.iot.hub.protocol.models.AuthenticationMechanism + :keyword twin_e_tag: The string representing a weak ETag for the device twin RFC7232. The value + is only used if import mode is updateIfMatchETag, in that case the import operation is + performed only if this ETag matches the value maintained by the server. + :paramtype twin_e_tag: str + :keyword tags: The JSON document read and written by the solution back end. The tags are not + visible to device apps. + :paramtype tags: dict[str, JSON] + :keyword properties: The desired and reported properties for the device. + :paramtype properties: ~azure.iot.hub.protocol.models.PropertyContainer + :keyword capabilities: The status of capabilities enabled on the device. + :paramtype capabilities: ~azure.iot.hub.protocol.models.DeviceCapabilities + :keyword device_scope: The scope of the device. + :paramtype device_scope: str + :keyword parent_scopes: The scopes of the upper level edge devices if applicable. Only + available for edge devices. + :paramtype parent_scopes: list[str] + """ + super().__init__(**kwargs) + self.id = id + self.module_id = module_id + self.e_tag = e_tag + self.import_mode = import_mode + self.status = status + self.status_reason = status_reason + self.authentication = authentication + self.twin_e_tag = twin_e_tag + self.tags = tags + self.properties = properties + self.capabilities = capabilities + self.device_scope = device_scope + self.parent_scopes = parent_scopes + + +class JobProperties(_serialization.Model): + """JobProperties. + + :ivar job_id: The unique identifier of the job. + :vartype job_id: str + :ivar start_time_utc: System generated. Ignored at creation. The start date and time of the job + in UTC. + :vartype start_time_utc: ~datetime.datetime + :ivar end_time_utc: System generated. Ignored at creation. The end date and time of the job in + UTC. + :vartype end_time_utc: ~datetime.datetime + :ivar type: The job type. Known values are: "unknown", "export", "import", "backup", + "readDeviceProperties", "writeDeviceProperties", "updateDeviceConfiguration", "rebootDevice", + "factoryResetDevice", "firmwareUpdate", "scheduleDeviceMethod", "scheduleUpdateTwin", + "restoreFromBackup", and "failoverDataCopy". + :vartype type: str or ~azure.iot.hub.protocol.models.JobPropertiesType + :ivar status: System generated. Ignored at creation. The status of the job. Known values are: + "unknown", "enqueued", "running", "completed", "failed", "cancelled", "scheduled", and + "queued". + :vartype status: str or ~azure.iot.hub.protocol.models.JobPropertiesStatus + :ivar progress: System generated. Ignored at creation. The percentage of job completion. + :vartype progress: int + :ivar input_blob_container_uri: The URI containing SAS token to a blob container that contains + registry data to sync. + :vartype input_blob_container_uri: str + :ivar input_blob_name: The blob name to use when importing from the input blob container. + :vartype input_blob_name: str + :ivar output_blob_container_uri: The SAS token to access the blob container. This is used to + output the status and results of the job. + :vartype output_blob_container_uri: str + :ivar output_blob_name: The blob name that will be created in the output blob container. This + blob will contain the exported device registry information for the IoT Hub. + :vartype output_blob_name: str + :ivar exclude_keys_in_export: Optional for export jobs; ignored for other jobs. If not + specified, the service defaults to false. If false, authorization keys are included in export + output. Keys are exported as null otherwise. + :vartype exclude_keys_in_export: bool + :ivar storage_authentication_type: The authentication type used for connecting to the storage + account. Known values are: "keyBased" and "identityBased". + :vartype storage_authentication_type: str or + ~azure.iot.hub.protocol.models.JobPropertiesStorageAuthenticationType + :ivar identity: + :vartype identity: ~azure.iot.hub.protocol.models.ManagedIdentity + :ivar failure_reason: System genereated. Ignored at creation. The reason for failure, if a + failure occurred. + :vartype failure_reason: str + :ivar include_configurations: Defaults to false. If true, then configurations are included in + the data export/import. + :vartype include_configurations: bool + :ivar configurations_blob_name: Defaults to configurations.txt. Specifies the name of the blob + to use when exporting/importing configurations. + :vartype configurations_blob_name: str + """ + + _attribute_map = { + "job_id": {"key": "jobId", "type": "str"}, + "start_time_utc": {"key": "startTimeUtc", "type": "iso-8601"}, + "end_time_utc": {"key": "endTimeUtc", "type": "iso-8601"}, + "type": {"key": "type", "type": "str"}, + "status": {"key": "status", "type": "str"}, + "progress": {"key": "progress", "type": "int"}, + "input_blob_container_uri": {"key": "inputBlobContainerUri", "type": "str"}, + "input_blob_name": {"key": "inputBlobName", "type": "str"}, + "output_blob_container_uri": {"key": "outputBlobContainerUri", "type": "str"}, + "output_blob_name": {"key": "outputBlobName", "type": "str"}, + "exclude_keys_in_export": {"key": "excludeKeysInExport", "type": "bool"}, + "storage_authentication_type": {"key": "storageAuthenticationType", "type": "str"}, + "identity": {"key": "identity", "type": "ManagedIdentity"}, + "failure_reason": {"key": "failureReason", "type": "str"}, + "include_configurations": {"key": "includeConfigurations", "type": "bool"}, + "configurations_blob_name": {"key": "configurationsBlobName", "type": "str"}, + } + + def __init__( + self, + *, + job_id: Optional[str] = None, + start_time_utc: Optional[datetime.datetime] = None, + end_time_utc: Optional[datetime.datetime] = None, + type: Optional[Union[str, "_models.JobPropertiesType"]] = None, + status: Optional[Union[str, "_models.JobPropertiesStatus"]] = None, + progress: Optional[int] = None, + input_blob_container_uri: Optional[str] = None, + input_blob_name: Optional[str] = None, + output_blob_container_uri: Optional[str] = None, + output_blob_name: Optional[str] = None, + exclude_keys_in_export: Optional[bool] = None, + storage_authentication_type: Optional[Union[str, "_models.JobPropertiesStorageAuthenticationType"]] = None, + identity: Optional["_models.ManagedIdentity"] = None, + failure_reason: Optional[str] = None, + include_configurations: Optional[bool] = None, + configurations_blob_name: Optional[str] = None, + **kwargs: Any + ) -> None: + """ + :keyword job_id: The unique identifier of the job. + :paramtype job_id: str + :keyword start_time_utc: System generated. Ignored at creation. The start date and time of the + job in UTC. + :paramtype start_time_utc: ~datetime.datetime + :keyword end_time_utc: System generated. Ignored at creation. The end date and time of the job + in UTC. + :paramtype end_time_utc: ~datetime.datetime + :keyword type: The job type. Known values are: "unknown", "export", "import", "backup", + "readDeviceProperties", "writeDeviceProperties", "updateDeviceConfiguration", "rebootDevice", + "factoryResetDevice", "firmwareUpdate", "scheduleDeviceMethod", "scheduleUpdateTwin", + "restoreFromBackup", and "failoverDataCopy". + :paramtype type: str or ~azure.iot.hub.protocol.models.JobPropertiesType + :keyword status: System generated. Ignored at creation. The status of the job. Known values + are: "unknown", "enqueued", "running", "completed", "failed", "cancelled", "scheduled", and + "queued". + :paramtype status: str or ~azure.iot.hub.protocol.models.JobPropertiesStatus + :keyword progress: System generated. Ignored at creation. The percentage of job completion. + :paramtype progress: int + :keyword input_blob_container_uri: The URI containing SAS token to a blob container that + contains registry data to sync. + :paramtype input_blob_container_uri: str + :keyword input_blob_name: The blob name to use when importing from the input blob container. + :paramtype input_blob_name: str + :keyword output_blob_container_uri: The SAS token to access the blob container. This is used to + output the status and results of the job. + :paramtype output_blob_container_uri: str + :keyword output_blob_name: The blob name that will be created in the output blob container. + This blob will contain the exported device registry information for the IoT Hub. + :paramtype output_blob_name: str + :keyword exclude_keys_in_export: Optional for export jobs; ignored for other jobs. If not + specified, the service defaults to false. If false, authorization keys are included in export + output. Keys are exported as null otherwise. + :paramtype exclude_keys_in_export: bool + :keyword storage_authentication_type: The authentication type used for connecting to the + storage account. Known values are: "keyBased" and "identityBased". + :paramtype storage_authentication_type: str or + ~azure.iot.hub.protocol.models.JobPropertiesStorageAuthenticationType + :keyword identity: + :paramtype identity: ~azure.iot.hub.protocol.models.ManagedIdentity + :keyword failure_reason: System genereated. Ignored at creation. The reason for failure, if a + failure occurred. + :paramtype failure_reason: str + :keyword include_configurations: Defaults to false. If true, then configurations are included + in the data export/import. + :paramtype include_configurations: bool + :keyword configurations_blob_name: Defaults to configurations.txt. Specifies the name of the + blob to use when exporting/importing configurations. + :paramtype configurations_blob_name: str + """ + super().__init__(**kwargs) + self.job_id = job_id + self.start_time_utc = start_time_utc + self.end_time_utc = end_time_utc + self.type = type + self.status = status + self.progress = progress + self.input_blob_container_uri = input_blob_container_uri + self.input_blob_name = input_blob_name + self.output_blob_container_uri = output_blob_container_uri + self.output_blob_name = output_blob_name + self.exclude_keys_in_export = exclude_keys_in_export + self.storage_authentication_type = storage_authentication_type + self.identity = identity + self.failure_reason = failure_reason + self.include_configurations = include_configurations + self.configurations_blob_name = configurations_blob_name + + +class JobRequest(_serialization.Model): + """JobRequest. + + :ivar job_id: The unique identifier of the job. + :vartype job_id: str + :ivar type: The job type. Known values are: "unknown", "export", "import", "backup", + "readDeviceProperties", "writeDeviceProperties", "updateDeviceConfiguration", "rebootDevice", + "factoryResetDevice", "firmwareUpdate", "scheduleDeviceMethod", "scheduleUpdateTwin", + "restoreFromBackup", and "failoverDataCopy". + :vartype type: str or ~azure.iot.hub.protocol.models.JobRequestType + :ivar cloud_to_device_method: The method type and parameters. This is required if the job type + is cloudToDeviceMethod. + :vartype cloud_to_device_method: ~azure.iot.hub.protocol.models.CloudToDeviceMethod + :ivar update_twin: The state information for a device or module. This is implicitly created and + deleted when the corresponding device/ module identity is created or deleted in the IoT Hub. + :vartype update_twin: ~azure.iot.hub.protocol.models.Twin + :ivar query_condition: The condition for devices to execute the job. This is required if the + job type is updateTwin or cloudToDeviceMethod. + :vartype query_condition: str + :ivar start_time: The start date and time of the job in ISO 8601 standard. + :vartype start_time: ~datetime.datetime + :ivar max_execution_time_in_seconds: The maximum execution time in secounds. + :vartype max_execution_time_in_seconds: int + """ + + _attribute_map = { + "job_id": {"key": "jobId", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "cloud_to_device_method": {"key": "cloudToDeviceMethod", "type": "CloudToDeviceMethod"}, + "update_twin": {"key": "updateTwin", "type": "Twin"}, + "query_condition": {"key": "queryCondition", "type": "str"}, + "start_time": {"key": "startTime", "type": "iso-8601"}, + "max_execution_time_in_seconds": {"key": "maxExecutionTimeInSeconds", "type": "int"}, + } + + def __init__( + self, + *, + job_id: Optional[str] = None, + type: Optional[Union[str, "_models.JobRequestType"]] = None, + cloud_to_device_method: Optional["_models.CloudToDeviceMethod"] = None, + update_twin: Optional["_models.Twin"] = None, + query_condition: Optional[str] = None, + start_time: Optional[datetime.datetime] = None, + max_execution_time_in_seconds: Optional[int] = None, + **kwargs: Any + ) -> None: + """ + :keyword job_id: The unique identifier of the job. + :paramtype job_id: str + :keyword type: The job type. Known values are: "unknown", "export", "import", "backup", + "readDeviceProperties", "writeDeviceProperties", "updateDeviceConfiguration", "rebootDevice", + "factoryResetDevice", "firmwareUpdate", "scheduleDeviceMethod", "scheduleUpdateTwin", + "restoreFromBackup", and "failoverDataCopy". + :paramtype type: str or ~azure.iot.hub.protocol.models.JobRequestType + :keyword cloud_to_device_method: The method type and parameters. This is required if the job + type is cloudToDeviceMethod. + :paramtype cloud_to_device_method: ~azure.iot.hub.protocol.models.CloudToDeviceMethod + :keyword update_twin: The state information for a device or module. This is implicitly created + and deleted when the corresponding device/ module identity is created or deleted in the IoT + Hub. + :paramtype update_twin: ~azure.iot.hub.protocol.models.Twin + :keyword query_condition: The condition for devices to execute the job. This is required if the + job type is updateTwin or cloudToDeviceMethod. + :paramtype query_condition: str + :keyword start_time: The start date and time of the job in ISO 8601 standard. + :paramtype start_time: ~datetime.datetime + :keyword max_execution_time_in_seconds: The maximum execution time in secounds. + :paramtype max_execution_time_in_seconds: int + """ + super().__init__(**kwargs) + self.job_id = job_id + self.type = type + self.cloud_to_device_method = cloud_to_device_method + self.update_twin = update_twin + self.query_condition = query_condition + self.start_time = start_time + self.max_execution_time_in_seconds = max_execution_time_in_seconds + + +class JobResponse(_serialization.Model): + """JobResponse. + + :ivar job_id: System generated. Ignored at creation. The unique identifier of the job. + :vartype job_id: str + :ivar query_condition: The device query condition. + :vartype query_condition: str + :ivar created_time: System generated. Ignored at creation. The creation date and time of the + job. + :vartype created_time: ~datetime.datetime + :ivar start_time: The start date and time of the scheduled job in UTC. + :vartype start_time: ~datetime.datetime + :ivar end_time: System generated. Ignored at creation. The end date and time of the job in + UTC. + :vartype end_time: ~datetime.datetime + :ivar max_execution_time_in_seconds: The maximum execution time in secounds. + :vartype max_execution_time_in_seconds: int + :ivar type: The job type. Known values are: "unknown", "export", "import", "backup", + "readDeviceProperties", "writeDeviceProperties", "updateDeviceConfiguration", "rebootDevice", + "factoryResetDevice", "firmwareUpdate", "scheduleDeviceMethod", "scheduleUpdateTwin", + "restoreFromBackup", and "failoverDataCopy". + :vartype type: str or ~azure.iot.hub.protocol.models.JobResponseType + :ivar cloud_to_device_method: The method type and parameters. This is required if job type is + cloudToDeviceMethod. + :vartype cloud_to_device_method: ~azure.iot.hub.protocol.models.CloudToDeviceMethod + :ivar update_twin: The state information for a device or module. This is implicitly created and + deleted when the corresponding device/ module identity is created or deleted in the IoT Hub. + :vartype update_twin: ~azure.iot.hub.protocol.models.Twin + :ivar status: System generated. Ignored at creation. The status of the job. Known values are: + "unknown", "enqueued", "running", "completed", "failed", "cancelled", "scheduled", and + "queued". + :vartype status: str or ~azure.iot.hub.protocol.models.JobResponseStatus + :ivar failure_reason: The reason for the failure, if a failure occurred. + :vartype failure_reason: str + :ivar status_message: The status message of the job. + :vartype status_message: str + :ivar device_job_statistics: The details regarding job execution status. + :vartype device_job_statistics: ~azure.iot.hub.protocol.models.DeviceJobStatistics + """ + + _attribute_map = { + "job_id": {"key": "jobId", "type": "str"}, + "query_condition": {"key": "queryCondition", "type": "str"}, + "created_time": {"key": "createdTime", "type": "iso-8601"}, + "start_time": {"key": "startTime", "type": "iso-8601"}, + "end_time": {"key": "endTime", "type": "iso-8601"}, + "max_execution_time_in_seconds": {"key": "maxExecutionTimeInSeconds", "type": "int"}, + "type": {"key": "type", "type": "str"}, + "cloud_to_device_method": {"key": "cloudToDeviceMethod", "type": "CloudToDeviceMethod"}, + "update_twin": {"key": "updateTwin", "type": "Twin"}, + "status": {"key": "status", "type": "str"}, + "failure_reason": {"key": "failureReason", "type": "str"}, + "status_message": {"key": "statusMessage", "type": "str"}, + "device_job_statistics": {"key": "deviceJobStatistics", "type": "DeviceJobStatistics"}, + } + + def __init__( + self, + *, + job_id: Optional[str] = None, + query_condition: Optional[str] = None, + created_time: Optional[datetime.datetime] = None, + start_time: Optional[datetime.datetime] = None, + end_time: Optional[datetime.datetime] = None, + max_execution_time_in_seconds: Optional[int] = None, + type: Optional[Union[str, "_models.JobResponseType"]] = None, + cloud_to_device_method: Optional["_models.CloudToDeviceMethod"] = None, + update_twin: Optional["_models.Twin"] = None, + status: Optional[Union[str, "_models.JobResponseStatus"]] = None, + failure_reason: Optional[str] = None, + status_message: Optional[str] = None, + device_job_statistics: Optional["_models.DeviceJobStatistics"] = None, + **kwargs: Any + ) -> None: + """ + :keyword job_id: System generated. Ignored at creation. The unique identifier of the job. + :paramtype job_id: str + :keyword query_condition: The device query condition. + :paramtype query_condition: str + :keyword created_time: System generated. Ignored at creation. The creation date and time of + the job. + :paramtype created_time: ~datetime.datetime + :keyword start_time: The start date and time of the scheduled job in UTC. + :paramtype start_time: ~datetime.datetime + :keyword end_time: System generated. Ignored at creation. The end date and time of the job in + UTC. + :paramtype end_time: ~datetime.datetime + :keyword max_execution_time_in_seconds: The maximum execution time in secounds. + :paramtype max_execution_time_in_seconds: int + :keyword type: The job type. Known values are: "unknown", "export", "import", "backup", + "readDeviceProperties", "writeDeviceProperties", "updateDeviceConfiguration", "rebootDevice", + "factoryResetDevice", "firmwareUpdate", "scheduleDeviceMethod", "scheduleUpdateTwin", + "restoreFromBackup", and "failoverDataCopy". + :paramtype type: str or ~azure.iot.hub.protocol.models.JobResponseType + :keyword cloud_to_device_method: The method type and parameters. This is required if job type + is cloudToDeviceMethod. + :paramtype cloud_to_device_method: ~azure.iot.hub.protocol.models.CloudToDeviceMethod + :keyword update_twin: The state information for a device or module. This is implicitly created + and deleted when the corresponding device/ module identity is created or deleted in the IoT + Hub. + :paramtype update_twin: ~azure.iot.hub.protocol.models.Twin + :keyword status: System generated. Ignored at creation. The status of the job. Known values + are: "unknown", "enqueued", "running", "completed", "failed", "cancelled", "scheduled", and + "queued". + :paramtype status: str or ~azure.iot.hub.protocol.models.JobResponseStatus + :keyword failure_reason: The reason for the failure, if a failure occurred. + :paramtype failure_reason: str + :keyword status_message: The status message of the job. + :paramtype status_message: str + :keyword device_job_statistics: The details regarding job execution status. + :paramtype device_job_statistics: ~azure.iot.hub.protocol.models.DeviceJobStatistics + """ + super().__init__(**kwargs) + self.job_id = job_id + self.query_condition = query_condition + self.created_time = created_time + self.start_time = start_time + self.end_time = end_time + self.max_execution_time_in_seconds = max_execution_time_in_seconds + self.type = type + self.cloud_to_device_method = cloud_to_device_method + self.update_twin = update_twin + self.status = status + self.failure_reason = failure_reason + self.status_message = status_message + self.device_job_statistics = device_job_statistics + + +class ManagedIdentity(_serialization.Model): + """ManagedIdentity. + + :ivar user_assigned_identity: + :vartype user_assigned_identity: str + """ + + _attribute_map = { + "user_assigned_identity": {"key": "userAssignedIdentity", "type": "str"}, + } + + def __init__(self, *, user_assigned_identity: Optional[str] = None, **kwargs: Any) -> None: + """ + :keyword user_assigned_identity: + :paramtype user_assigned_identity: str + """ + super().__init__(**kwargs) + self.user_assigned_identity = user_assigned_identity + + +class Module(_serialization.Model): + """The module identity on a device. + + :ivar module_id: The unique identifier of the module. + :vartype module_id: str + :ivar managed_by: Identifies who manages this module. For instance, this value is \\"IotEdge\\" + if the edge runtime owns this module. + :vartype managed_by: str + :ivar device_id: The unique identifier of the device. + :vartype device_id: str + :ivar generation_id: The IoT Hub generated, case-sensitive string up to 128 characters long. + This value is used to distinguish modules with the same moduleId, when they have been deleted + and re-created. + :vartype generation_id: str + :ivar etag: The string representing a weak ETag for the module identity, as per RFC7232. + :vartype etag: str + :ivar connection_state: The connection state of the device. Known values are: "Disconnected" + and "Connected". + :vartype connection_state: str or ~azure.iot.hub.protocol.models.ModuleConnectionState + :ivar connection_state_updated_time: The date and time the connection state was last updated. + :vartype connection_state_updated_time: ~datetime.datetime + :ivar last_activity_time: The date and time the device last connected, received, or sent a + message. + :vartype last_activity_time: ~datetime.datetime + :ivar cloud_to_device_message_count: The number of cloud-to-module messages currently queued to + be sent to the module. + :vartype cloud_to_device_message_count: int + :ivar authentication: The authentication mechanism used by the module when connecting to the + service and edge hub. + :vartype authentication: ~azure.iot.hub.protocol.models.AuthenticationMechanism + """ + + _attribute_map = { + "module_id": {"key": "moduleId", "type": "str"}, + "managed_by": {"key": "managedBy", "type": "str"}, + "device_id": {"key": "deviceId", "type": "str"}, + "generation_id": {"key": "generationId", "type": "str"}, + "etag": {"key": "etag", "type": "str"}, + "connection_state": {"key": "connectionState", "type": "str"}, + "connection_state_updated_time": {"key": "connectionStateUpdatedTime", "type": "iso-8601"}, + "last_activity_time": {"key": "lastActivityTime", "type": "iso-8601"}, + "cloud_to_device_message_count": {"key": "cloudToDeviceMessageCount", "type": "int"}, + "authentication": {"key": "authentication", "type": "AuthenticationMechanism"}, + } + + def __init__( + self, + *, + module_id: Optional[str] = None, + managed_by: Optional[str] = None, + device_id: Optional[str] = None, + generation_id: Optional[str] = None, + etag: Optional[str] = None, + connection_state: Optional[Union[str, "_models.ModuleConnectionState"]] = None, + connection_state_updated_time: Optional[datetime.datetime] = None, + last_activity_time: Optional[datetime.datetime] = None, + cloud_to_device_message_count: Optional[int] = None, + authentication: Optional["_models.AuthenticationMechanism"] = None, + **kwargs: Any + ) -> None: + """ + :keyword module_id: The unique identifier of the module. + :paramtype module_id: str + :keyword managed_by: Identifies who manages this module. For instance, this value is + \\"IotEdge\\" if the edge runtime owns this module. + :paramtype managed_by: str + :keyword device_id: The unique identifier of the device. + :paramtype device_id: str + :keyword generation_id: The IoT Hub generated, case-sensitive string up to 128 characters long. + This value is used to distinguish modules with the same moduleId, when they have been deleted + and re-created. + :paramtype generation_id: str + :keyword etag: The string representing a weak ETag for the module identity, as per RFC7232. + :paramtype etag: str + :keyword connection_state: The connection state of the device. Known values are: "Disconnected" + and "Connected". + :paramtype connection_state: str or ~azure.iot.hub.protocol.models.ModuleConnectionState + :keyword connection_state_updated_time: The date and time the connection state was last + updated. + :paramtype connection_state_updated_time: ~datetime.datetime + :keyword last_activity_time: The date and time the device last connected, received, or sent a + message. + :paramtype last_activity_time: ~datetime.datetime + :keyword cloud_to_device_message_count: The number of cloud-to-module messages currently queued + to be sent to the module. + :paramtype cloud_to_device_message_count: int + :keyword authentication: The authentication mechanism used by the module when connecting to the + service and edge hub. + :paramtype authentication: ~azure.iot.hub.protocol.models.AuthenticationMechanism + """ + super().__init__(**kwargs) + self.module_id = module_id + self.managed_by = managed_by + self.device_id = device_id + self.generation_id = generation_id + self.etag = etag + self.connection_state = connection_state + self.connection_state_updated_time = connection_state_updated_time + self.last_activity_time = last_activity_time + self.cloud_to_device_message_count = cloud_to_device_message_count + self.authentication = authentication + + +class PropertyContainer(_serialization.Model): + """The desired and reported properties of the twin. The maximum depth of the object is 10. + + :ivar desired: The collection of desired property key-value pairs. The keys are UTF-8 encoded, + case-sensitive and up-to 1KB in length. Allowed characters exclude UNICODE control characters + (segments C0 and C1), '.', '$' and space. The desired porperty values are JSON objects, up-to + 4KB in length. + :vartype desired: dict[str, JSON] + :ivar reported: The collection of reported property key-value pairs. The keys are UTF-8 + encoded, case-sensitive and up-to 1KB in length. Allowed characters exclude UNICODE control + characters (segments C0 and C1), '.', '$' and space. The reported property values are JSON + objects, up-to 4KB in length. + :vartype reported: dict[str, JSON] + """ + + _attribute_map = { + "desired": {"key": "desired", "type": "{object}"}, + "reported": {"key": "reported", "type": "{object}"}, + } + + def __init__( + self, *, desired: Optional[dict[str, JSON]] = None, reported: Optional[dict[str, JSON]] = None, **kwargs: Any + ) -> None: + """ + :keyword desired: The collection of desired property key-value pairs. The keys are UTF-8 + encoded, case-sensitive and up-to 1KB in length. Allowed characters exclude UNICODE control + characters (segments C0 and C1), '.', '$' and space. The desired porperty values are JSON + objects, up-to 4KB in length. + :paramtype desired: dict[str, JSON] + :keyword reported: The collection of reported property key-value pairs. The keys are UTF-8 + encoded, case-sensitive and up-to 1KB in length. Allowed characters exclude UNICODE control + characters (segments C0 and C1), '.', '$' and space. The reported property values are JSON + objects, up-to 4KB in length. + :paramtype reported: dict[str, JSON] + """ + super().__init__(**kwargs) + self.desired = desired + self.reported = reported + + +class PurgeMessageQueueResult(_serialization.Model): + """The result of a device message queue purge operation. + + :ivar total_messages_purged: + :vartype total_messages_purged: int + :ivar device_id: The unique identifier of the device. + :vartype device_id: str + :ivar module_id: The unique identifier of the module. + :vartype module_id: str + """ + + _attribute_map = { + "total_messages_purged": {"key": "totalMessagesPurged", "type": "int"}, + "device_id": {"key": "deviceId", "type": "str"}, + "module_id": {"key": "moduleId", "type": "str"}, + } + + def __init__( + self, + *, + total_messages_purged: Optional[int] = None, + device_id: Optional[str] = None, + module_id: Optional[str] = None, + **kwargs: Any + ) -> None: + """ + :keyword total_messages_purged: + :paramtype total_messages_purged: int + :keyword device_id: The unique identifier of the device. + :paramtype device_id: str + :keyword module_id: The unique identifier of the module. + :paramtype module_id: str + """ + super().__init__(**kwargs) + self.total_messages_purged = total_messages_purged + self.device_id = device_id + self.module_id = module_id + + +class QueryResult(_serialization.Model): + """The query result. + + :ivar type: The query result type. Known values are: "unknown", "twin", "deviceJob", + "jobResponse", "raw", "enrollment", "enrollmentGroup", and "deviceRegistration". + :vartype type: str or ~azure.iot.hub.protocol.models.QueryResultType + :ivar items: The query result items, as a collection. + :vartype items: list[JSON] + :ivar continuation_token: The continuation token. + :vartype continuation_token: str + """ + + _attribute_map = { + "type": {"key": "type", "type": "str"}, + "items": {"key": "items", "type": "[object]"}, + "continuation_token": {"key": "continuationToken", "type": "str"}, + } + + def __init__( + self, + *, + type: Optional[Union[str, "_models.QueryResultType"]] = None, + items: Optional[list[JSON]] = None, + continuation_token: Optional[str] = None, + **kwargs: Any + ) -> None: + """ + :keyword type: The query result type. Known values are: "unknown", "twin", "deviceJob", + "jobResponse", "raw", "enrollment", "enrollmentGroup", and "deviceRegistration". + :paramtype type: str or ~azure.iot.hub.protocol.models.QueryResultType + :keyword items: The query result items, as a collection. + :paramtype items: list[JSON] + :keyword continuation_token: The continuation token. + :paramtype continuation_token: str + """ + super().__init__(**kwargs) + self.type = type + self.items = items + self.continuation_token = continuation_token + + +class QuerySpecification(_serialization.Model): + """The Json query request. + + :ivar query: The query string. + :vartype query: str + """ + + _attribute_map = { + "query": {"key": "query", "type": "str"}, + } + + def __init__(self, *, query: Optional[str] = None, **kwargs: Any) -> None: + """ + :keyword query: The query string. + :paramtype query: str + """ + super().__init__(**kwargs) + self.query = query + + +class RegistryStatistics(_serialization.Model): + """RegistryStatistics. + + :ivar total_device_count: The total number of devices registered for the IoT Hub. + :vartype total_device_count: int + :ivar enabled_device_count: The number of currently enabled devices. + :vartype enabled_device_count: int + :ivar disabled_device_count: The number of currently disabled devices. + :vartype disabled_device_count: int + """ + + _attribute_map = { + "total_device_count": {"key": "totalDeviceCount", "type": "int"}, + "enabled_device_count": {"key": "enabledDeviceCount", "type": "int"}, + "disabled_device_count": {"key": "disabledDeviceCount", "type": "int"}, + } + + def __init__( + self, + *, + total_device_count: Optional[int] = None, + enabled_device_count: Optional[int] = None, + disabled_device_count: Optional[int] = None, + **kwargs: Any + ) -> None: + """ + :keyword total_device_count: The total number of devices registered for the IoT Hub. + :paramtype total_device_count: int + :keyword enabled_device_count: The number of currently enabled devices. + :paramtype enabled_device_count: int + :keyword disabled_device_count: The number of currently disabled devices. + :paramtype disabled_device_count: int + """ + super().__init__(**kwargs) + self.total_device_count = total_device_count + self.enabled_device_count = enabled_device_count + self.disabled_device_count = disabled_device_count + + +class ServiceStatistics(_serialization.Model): + """ServiceStatistics. + + :ivar connected_device_count: The number of currently connected devices. + :vartype connected_device_count: int + """ + + _attribute_map = { + "connected_device_count": {"key": "connectedDeviceCount", "type": "int"}, + } + + def __init__(self, *, connected_device_count: Optional[int] = None, **kwargs: Any) -> None: + """ + :keyword connected_device_count: The number of currently connected devices. + :paramtype connected_device_count: int + """ + super().__init__(**kwargs) + self.connected_device_count = connected_device_count + + +class SymmetricKey(_serialization.Model): + """SymmetricKey. + + :ivar primary_key: The base64 encoded primary key of the device. + :vartype primary_key: str + :ivar secondary_key: The base64 encoded secondary key of the device. + :vartype secondary_key: str + """ + + _attribute_map = { + "primary_key": {"key": "primaryKey", "type": "str"}, + "secondary_key": {"key": "secondaryKey", "type": "str"}, + } + + def __init__( + self, *, primary_key: Optional[str] = None, secondary_key: Optional[str] = None, **kwargs: Any + ) -> None: + """ + :keyword primary_key: The base64 encoded primary key of the device. + :paramtype primary_key: str + :keyword secondary_key: The base64 encoded secondary key of the device. + :paramtype secondary_key: str + """ + super().__init__(**kwargs) + self.primary_key = primary_key + self.secondary_key = secondary_key + + +class Twin(_serialization.Model): + """The state information for a device or module. This is implicitly created and deleted when the + corresponding device/ module identity is created or deleted in the IoT Hub. + + :ivar device_id: The unique identifier of the device in the identity registry of the IoT Hub. + It is a case-sensitive string (up to 128 char long) of ASCII 7-bit alphanumeric chars, and the + following special characters {'-', ':', '.', '+', '%', '_', '#', '*', '?', '!', '(', ')', ',', + '=', '@', ';', '$', '''}. + :vartype device_id: str + :ivar module_id: The unique identifier of the module in the identity registry of the IoT Hub. + It is a case-sensitive string (up to 128 char long) of ASCII 7-bit alphanumeric chars, and the + following special characters {'-', ':', '.', '+', '%', '_', '#', '*', '?', '!', '(', ')', ',', + '=', '@', ';', '$', '''}. + :vartype module_id: str + :ivar tags: The collection of key-value pairs read and written by the solution back end. They + are not visible to device apps. They keys are UTF-8 encoded, case-sensitive and up-to 1KB in + length. Allowed characters exclude UNICODE control characters (segments C0 and C1), '.', '$' + and space. The values are JSON objects, up-to 4KB in length. + :vartype tags: dict[str, JSON] + :ivar properties: The desired and reported properties of the twin. + :vartype properties: ~azure.iot.hub.protocol.models.TwinProperties + :ivar etag: The string representing a ETag for the device twin, as per RFC7232. + :vartype etag: str + :ivar version: The version for the device twin including tags and desired properties. + :vartype version: int + :ivar device_etag: The string representing a ETag for the device, as per RFC7232. + :vartype device_etag: str + :ivar status: The enabled status of the device. If disabled, the device cannot connect to the + service. Known values are: "enabled" and "disabled". + :vartype status: str or ~azure.iot.hub.protocol.models.TwinStatus + :ivar status_reason: The reason for the current status of the device, if any. + :vartype status_reason: str + :ivar status_update_time: The date and time when the status of the device was last updated. + :vartype status_update_time: ~datetime.datetime + :ivar connection_state: The connection state of the device. Known values are: "Disconnected" + and "Connected". + :vartype connection_state: str or ~azure.iot.hub.protocol.models.TwinConnectionState + :ivar last_activity_time: The date and time when the device last connected or received or sent + a message. The date and time is sepecified in ISO8601 datetime format in UTC, for example, + 2015-01-28T16:24:48.789Z. This value is not updated if the device uses the HTTP/1 protocol to + perform messaging operations. + :vartype last_activity_time: ~datetime.datetime + :ivar cloud_to_device_message_count: The number of cloud-to-device messages sent. + :vartype cloud_to_device_message_count: int + :ivar authentication_type: The authentication type used by the device. Known values are: "sas", + "selfSigned", "certificateAuthority", and "none". + :vartype authentication_type: str or ~azure.iot.hub.protocol.models.TwinAuthenticationType + :ivar x509_thumbprint: The X509 thumbprint of the device. + :vartype x509_thumbprint: ~azure.iot.hub.protocol.models.X509Thumbprint + :ivar capabilities: The status of capabilities enabled on the device. + :vartype capabilities: ~azure.iot.hub.protocol.models.DeviceCapabilities + :ivar device_scope: The scope of the device. + :vartype device_scope: str + :ivar parent_scopes: The scopes of the upper level edge devices if applicable. Only available + for edge devices. + :vartype parent_scopes: list[str] + """ + + _attribute_map = { + "device_id": {"key": "deviceId", "type": "str"}, + "module_id": {"key": "moduleId", "type": "str"}, + "tags": {"key": "tags", "type": "{object}"}, + "properties": {"key": "properties", "type": "TwinProperties"}, + "etag": {"key": "etag", "type": "str"}, + "version": {"key": "version", "type": "int"}, + "device_etag": {"key": "deviceEtag", "type": "str"}, + "status": {"key": "status", "type": "str"}, + "status_reason": {"key": "statusReason", "type": "str"}, + "status_update_time": {"key": "statusUpdateTime", "type": "iso-8601"}, + "connection_state": {"key": "connectionState", "type": "str"}, + "last_activity_time": {"key": "lastActivityTime", "type": "iso-8601"}, + "cloud_to_device_message_count": {"key": "cloudToDeviceMessageCount", "type": "int"}, + "authentication_type": {"key": "authenticationType", "type": "str"}, + "x509_thumbprint": {"key": "x509Thumbprint", "type": "X509Thumbprint"}, + "capabilities": {"key": "capabilities", "type": "DeviceCapabilities"}, + "device_scope": {"key": "deviceScope", "type": "str"}, + "parent_scopes": {"key": "parentScopes", "type": "[str]"}, + } + + def __init__( + self, + *, + device_id: Optional[str] = None, + module_id: Optional[str] = None, + tags: Optional[dict[str, JSON]] = None, + properties: Optional["_models.TwinProperties"] = None, + etag: Optional[str] = None, + version: Optional[int] = None, + device_etag: Optional[str] = None, + status: Optional[Union[str, "_models.TwinStatus"]] = None, + status_reason: Optional[str] = None, + status_update_time: Optional[datetime.datetime] = None, + connection_state: Optional[Union[str, "_models.TwinConnectionState"]] = None, + last_activity_time: Optional[datetime.datetime] = None, + cloud_to_device_message_count: Optional[int] = None, + authentication_type: Optional[Union[str, "_models.TwinAuthenticationType"]] = None, + x509_thumbprint: Optional["_models.X509Thumbprint"] = None, + capabilities: Optional["_models.DeviceCapabilities"] = None, + device_scope: Optional[str] = None, + parent_scopes: Optional[list[str]] = None, + **kwargs: Any + ) -> None: + """ + :keyword device_id: The unique identifier of the device in the identity registry of the IoT + Hub. It is a case-sensitive string (up to 128 char long) of ASCII 7-bit alphanumeric chars, and + the following special characters {'-', ':', '.', '+', '%', '_', '#', '*', '?', '!', '(', ')', + ',', '=', '@', ';', '$', '''}. + :paramtype device_id: str + :keyword module_id: The unique identifier of the module in the identity registry of the IoT + Hub. It is a case-sensitive string (up to 128 char long) of ASCII 7-bit alphanumeric chars, and + the following special characters {'-', ':', '.', '+', '%', '_', '#', '*', '?', '!', '(', ')', + ',', '=', '@', ';', '$', '''}. + :paramtype module_id: str + :keyword tags: The collection of key-value pairs read and written by the solution back end. + They are not visible to device apps. They keys are UTF-8 encoded, case-sensitive and up-to 1KB + in length. Allowed characters exclude UNICODE control characters (segments C0 and C1), '.', '$' + and space. The values are JSON objects, up-to 4KB in length. + :paramtype tags: dict[str, JSON] + :keyword properties: The desired and reported properties of the twin. + :paramtype properties: ~azure.iot.hub.protocol.models.TwinProperties + :keyword etag: The string representing a ETag for the device twin, as per RFC7232. + :paramtype etag: str + :keyword version: The version for the device twin including tags and desired properties. + :paramtype version: int + :keyword device_etag: The string representing a ETag for the device, as per RFC7232. + :paramtype device_etag: str + :keyword status: The enabled status of the device. If disabled, the device cannot connect to + the service. Known values are: "enabled" and "disabled". + :paramtype status: str or ~azure.iot.hub.protocol.models.TwinStatus + :keyword status_reason: The reason for the current status of the device, if any. + :paramtype status_reason: str + :keyword status_update_time: The date and time when the status of the device was last updated. + :paramtype status_update_time: ~datetime.datetime + :keyword connection_state: The connection state of the device. Known values are: "Disconnected" + and "Connected". + :paramtype connection_state: str or ~azure.iot.hub.protocol.models.TwinConnectionState + :keyword last_activity_time: The date and time when the device last connected or received or + sent a message. The date and time is sepecified in ISO8601 datetime format in UTC, for example, + 2015-01-28T16:24:48.789Z. This value is not updated if the device uses the HTTP/1 protocol to + perform messaging operations. + :paramtype last_activity_time: ~datetime.datetime + :keyword cloud_to_device_message_count: The number of cloud-to-device messages sent. + :paramtype cloud_to_device_message_count: int + :keyword authentication_type: The authentication type used by the device. Known values are: + "sas", "selfSigned", "certificateAuthority", and "none". + :paramtype authentication_type: str or ~azure.iot.hub.protocol.models.TwinAuthenticationType + :keyword x509_thumbprint: The X509 thumbprint of the device. + :paramtype x509_thumbprint: ~azure.iot.hub.protocol.models.X509Thumbprint + :keyword capabilities: The status of capabilities enabled on the device. + :paramtype capabilities: ~azure.iot.hub.protocol.models.DeviceCapabilities + :keyword device_scope: The scope of the device. + :paramtype device_scope: str + :keyword parent_scopes: The scopes of the upper level edge devices if applicable. Only + available for edge devices. + :paramtype parent_scopes: list[str] + """ + super().__init__(**kwargs) + self.device_id = device_id + self.module_id = module_id + self.tags = tags + self.properties = properties + self.etag = etag + self.version = version + self.device_etag = device_etag + self.status = status + self.status_reason = status_reason + self.status_update_time = status_update_time + self.connection_state = connection_state + self.last_activity_time = last_activity_time + self.cloud_to_device_message_count = cloud_to_device_message_count + self.authentication_type = authentication_type + self.x509_thumbprint = x509_thumbprint + self.capabilities = capabilities + self.device_scope = device_scope + self.parent_scopes = parent_scopes + + +class TwinProperties(_serialization.Model): + """The desired and reported properties of the twin. The maximum depth of the object is 10. + + :ivar desired: The collection of desired property key-value pairs. The keys are UTF-8 encoded, + case-sensitive and up-to 1KB in length. Allowed characters exclude UNICODE control characters + (segments C0 and C1), '.', '$' and space. The desired porperty values are JSON objects, up-to + 4KB in length. + :vartype desired: dict[str, JSON] + :ivar reported: The collection of reported property key-value pairs. The keys are UTF-8 + encoded, case-sensitive and up-to 1KB in length. Allowed characters exclude UNICODE control + characters (segments C0 and C1), '.', '$' and space. The reported property values are JSON + objects, up-to 4KB in length. + :vartype reported: dict[str, JSON] + """ + + _attribute_map = { + "desired": {"key": "desired", "type": "{object}"}, + "reported": {"key": "reported", "type": "{object}"}, + } + + def __init__( + self, *, desired: Optional[dict[str, JSON]] = None, reported: Optional[dict[str, JSON]] = None, **kwargs: Any + ) -> None: + """ + :keyword desired: The collection of desired property key-value pairs. The keys are UTF-8 + encoded, case-sensitive and up-to 1KB in length. Allowed characters exclude UNICODE control + characters (segments C0 and C1), '.', '$' and space. The desired porperty values are JSON + objects, up-to 4KB in length. + :paramtype desired: dict[str, JSON] + :keyword reported: The collection of reported property key-value pairs. The keys are UTF-8 + encoded, case-sensitive and up-to 1KB in length. Allowed characters exclude UNICODE control + characters (segments C0 and C1), '.', '$' and space. The reported property values are JSON + objects, up-to 4KB in length. + :paramtype reported: dict[str, JSON] + """ + super().__init__(**kwargs) + self.desired = desired + self.reported = reported + + +class X509Thumbprint(_serialization.Model): + """X509Thumbprint. + + :ivar primary_thumbprint: The X509 client certificate primary thumbprint. + :vartype primary_thumbprint: str + :ivar secondary_thumbprint: The X509 client certificate secondary thumbprint. + :vartype secondary_thumbprint: str + """ + + _attribute_map = { + "primary_thumbprint": {"key": "primaryThumbprint", "type": "str"}, + "secondary_thumbprint": {"key": "secondaryThumbprint", "type": "str"}, + } + + def __init__( + self, *, primary_thumbprint: Optional[str] = None, secondary_thumbprint: Optional[str] = None, **kwargs: Any + ) -> None: + """ + :keyword primary_thumbprint: The X509 client certificate primary thumbprint. + :paramtype primary_thumbprint: str + :keyword secondary_thumbprint: The X509 client certificate secondary thumbprint. + :paramtype secondary_thumbprint: str + """ + super().__init__(**kwargs) + self.primary_thumbprint = primary_thumbprint + self.secondary_thumbprint = secondary_thumbprint diff --git a/src/azure/iot/hub/protocol/models/_patch.py b/src/azure/iot/hub/protocol/models/_patch.py new file mode 100644 index 0000000..87676c6 --- /dev/null +++ b/src/azure/iot/hub/protocol/models/_patch.py @@ -0,0 +1,21 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------- +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" + + +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/src/azure/iot/hub/protocol/models/authentication_mechanism.py b/src/azure/iot/hub/protocol/models/authentication_mechanism.py deleted file mode 100644 index 814282c..0000000 --- a/src/azure/iot/hub/protocol/models/authentication_mechanism.py +++ /dev/null @@ -1,36 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is -# regenerated. -# -------------------------------------------------------------------------- - -from msrest.serialization import Model - - -class AuthenticationMechanism(Model): - """AuthenticationMechanism. - - :param symmetric_key: The primary and secondary keys used for SAS based - authentication. - :type symmetric_key: ~protocol.models.SymmetricKey - :param x509_thumbprint: The primary and secondary x509 thumbprints used - for x509 based authentication. - :type x509_thumbprint: ~protocol.models.X509Thumbprint - :param type: The type of authentication used to connect to the service. - Possible values include: 'sas', 'selfSigned', 'certificateAuthority', - 'none' - :type type: str or ~protocol.models.enum - """ - - _attribute_map = { - "symmetric_key": {"key": "symmetricKey", "type": "SymmetricKey"}, - "x509_thumbprint": {"key": "x509Thumbprint", "type": "X509Thumbprint"}, - "type": {"key": "type", "type": "str"}, - } - - def __init__(self, **kwargs): - super(AuthenticationMechanism, self).__init__(**kwargs) - self.symmetric_key = kwargs.get("symmetric_key", None) - self.x509_thumbprint = kwargs.get("x509_thumbprint", None) - self.type = kwargs.get("type", None) diff --git a/src/azure/iot/hub/protocol/models/authentication_mechanism_py3.py b/src/azure/iot/hub/protocol/models/authentication_mechanism_py3.py deleted file mode 100644 index e94694c..0000000 --- a/src/azure/iot/hub/protocol/models/authentication_mechanism_py3.py +++ /dev/null @@ -1,36 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is -# regenerated. -# -------------------------------------------------------------------------- - -from msrest.serialization import Model - - -class AuthenticationMechanism(Model): - """AuthenticationMechanism. - - :param symmetric_key: The primary and secondary keys used for SAS based - authentication. - :type symmetric_key: ~protocol.models.SymmetricKey - :param x509_thumbprint: The primary and secondary x509 thumbprints used - for x509 based authentication. - :type x509_thumbprint: ~protocol.models.X509Thumbprint - :param type: The type of authentication used to connect to the service. - Possible values include: 'sas', 'selfSigned', 'certificateAuthority', - 'none' - :type type: str or ~protocol.models.enum - """ - - _attribute_map = { - "symmetric_key": {"key": "symmetricKey", "type": "SymmetricKey"}, - "x509_thumbprint": {"key": "x509Thumbprint", "type": "X509Thumbprint"}, - "type": {"key": "type", "type": "str"}, - } - - def __init__(self, *, symmetric_key=None, x509_thumbprint=None, type=None, **kwargs) -> None: - super(AuthenticationMechanism, self).__init__(**kwargs) - self.symmetric_key = symmetric_key - self.x509_thumbprint = x509_thumbprint - self.type = type diff --git a/src/azure/iot/hub/protocol/models/bulk_registry_operation_result.py b/src/azure/iot/hub/protocol/models/bulk_registry_operation_result.py deleted file mode 100644 index 53886ef..0000000 --- a/src/azure/iot/hub/protocol/models/bulk_registry_operation_result.py +++ /dev/null @@ -1,32 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is -# regenerated. -# -------------------------------------------------------------------------- - -from msrest.serialization import Model - - -class BulkRegistryOperationResult(Model): - """The result of the bulk registry operation. - - :param is_successful: The operation result. - :type is_successful: bool - :param errors: The device registry operation errors. - :type errors: list[~protocol.models.DeviceRegistryOperationError] - :param warnings: The device registry operation warnings. - :type warnings: list[~protocol.models.DeviceRegistryOperationWarning] - """ - - _attribute_map = { - "is_successful": {"key": "isSuccessful", "type": "bool"}, - "errors": {"key": "errors", "type": "[DeviceRegistryOperationError]"}, - "warnings": {"key": "warnings", "type": "[DeviceRegistryOperationWarning]"}, - } - - def __init__(self, **kwargs): - super(BulkRegistryOperationResult, self).__init__(**kwargs) - self.is_successful = kwargs.get("is_successful", None) - self.errors = kwargs.get("errors", None) - self.warnings = kwargs.get("warnings", None) diff --git a/src/azure/iot/hub/protocol/models/bulk_registry_operation_result_py3.py b/src/azure/iot/hub/protocol/models/bulk_registry_operation_result_py3.py deleted file mode 100644 index 484653f..0000000 --- a/src/azure/iot/hub/protocol/models/bulk_registry_operation_result_py3.py +++ /dev/null @@ -1,32 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is -# regenerated. -# -------------------------------------------------------------------------- - -from msrest.serialization import Model - - -class BulkRegistryOperationResult(Model): - """The result of the bulk registry operation. - - :param is_successful: The operation result. - :type is_successful: bool - :param errors: The device registry operation errors. - :type errors: list[~protocol.models.DeviceRegistryOperationError] - :param warnings: The device registry operation warnings. - :type warnings: list[~protocol.models.DeviceRegistryOperationWarning] - """ - - _attribute_map = { - "is_successful": {"key": "isSuccessful", "type": "bool"}, - "errors": {"key": "errors", "type": "[DeviceRegistryOperationError]"}, - "warnings": {"key": "warnings", "type": "[DeviceRegistryOperationWarning]"}, - } - - def __init__(self, *, is_successful: bool = None, errors=None, warnings=None, **kwargs) -> None: - super(BulkRegistryOperationResult, self).__init__(**kwargs) - self.is_successful = is_successful - self.errors = errors - self.warnings = warnings diff --git a/src/azure/iot/hub/protocol/models/cloud_to_device_method.py b/src/azure/iot/hub/protocol/models/cloud_to_device_method.py deleted file mode 100644 index 07d492d..0000000 --- a/src/azure/iot/hub/protocol/models/cloud_to_device_method.py +++ /dev/null @@ -1,37 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is -# regenerated. -# -------------------------------------------------------------------------- - -from msrest.serialization import Model - - -class CloudToDeviceMethod(Model): - """The parameters to execute a direct method on the device. - - :param method_name: The name of the method to execute. - :type method_name: str - :param payload: The JSON-formatted direct method payload, up to 128kb in - size. - :type payload: object - :param response_timeout_in_seconds: - :type response_timeout_in_seconds: int - :param connect_timeout_in_seconds: - :type connect_timeout_in_seconds: int - """ - - _attribute_map = { - "method_name": {"key": "methodName", "type": "str"}, - "payload": {"key": "payload", "type": "object"}, - "response_timeout_in_seconds": {"key": "responseTimeoutInSeconds", "type": "int"}, - "connect_timeout_in_seconds": {"key": "connectTimeoutInSeconds", "type": "int"}, - } - - def __init__(self, **kwargs): - super(CloudToDeviceMethod, self).__init__(**kwargs) - self.method_name = kwargs.get("method_name", None) - self.payload = kwargs.get("payload", None) - self.response_timeout_in_seconds = kwargs.get("response_timeout_in_seconds", None) - self.connect_timeout_in_seconds = kwargs.get("connect_timeout_in_seconds", None) diff --git a/src/azure/iot/hub/protocol/models/cloud_to_device_method_py3.py b/src/azure/iot/hub/protocol/models/cloud_to_device_method_py3.py deleted file mode 100644 index 4726619..0000000 --- a/src/azure/iot/hub/protocol/models/cloud_to_device_method_py3.py +++ /dev/null @@ -1,45 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is -# regenerated. -# -------------------------------------------------------------------------- - -from msrest.serialization import Model - - -class CloudToDeviceMethod(Model): - """The parameters to execute a direct method on the device. - - :param method_name: The name of the method to execute. - :type method_name: str - :param payload: The JSON-formatted direct method payload, up to 128kb in - size. - :type payload: object - :param response_timeout_in_seconds: - :type response_timeout_in_seconds: int - :param connect_timeout_in_seconds: - :type connect_timeout_in_seconds: int - """ - - _attribute_map = { - "method_name": {"key": "methodName", "type": "str"}, - "payload": {"key": "payload", "type": "object"}, - "response_timeout_in_seconds": {"key": "responseTimeoutInSeconds", "type": "int"}, - "connect_timeout_in_seconds": {"key": "connectTimeoutInSeconds", "type": "int"}, - } - - def __init__( - self, - *, - method_name: str = None, - payload=None, - response_timeout_in_seconds: int = None, - connect_timeout_in_seconds: int = None, - **kwargs - ) -> None: - super(CloudToDeviceMethod, self).__init__(**kwargs) - self.method_name = method_name - self.payload = payload - self.response_timeout_in_seconds = response_timeout_in_seconds - self.connect_timeout_in_seconds = connect_timeout_in_seconds diff --git a/src/azure/iot/hub/protocol/models/cloud_to_device_method_result.py b/src/azure/iot/hub/protocol/models/cloud_to_device_method_result.py deleted file mode 100644 index b1ba2eb..0000000 --- a/src/azure/iot/hub/protocol/models/cloud_to_device_method_result.py +++ /dev/null @@ -1,28 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is -# regenerated. -# -------------------------------------------------------------------------- - -from msrest.serialization import Model - - -class CloudToDeviceMethodResult(Model): - """Represents the Device Method Invocation Results. - - :param status: Method invocation result status. - :type status: int - :param payload: Method invocation result payload. - :type payload: object - """ - - _attribute_map = { - "status": {"key": "status", "type": "int"}, - "payload": {"key": "payload", "type": "object"}, - } - - def __init__(self, **kwargs): - super(CloudToDeviceMethodResult, self).__init__(**kwargs) - self.status = kwargs.get("status", None) - self.payload = kwargs.get("payload", None) diff --git a/src/azure/iot/hub/protocol/models/cloud_to_device_method_result_py3.py b/src/azure/iot/hub/protocol/models/cloud_to_device_method_result_py3.py deleted file mode 100644 index 63a86e1..0000000 --- a/src/azure/iot/hub/protocol/models/cloud_to_device_method_result_py3.py +++ /dev/null @@ -1,28 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is -# regenerated. -# -------------------------------------------------------------------------- - -from msrest.serialization import Model - - -class CloudToDeviceMethodResult(Model): - """Represents the Device Method Invocation Results. - - :param status: Method invocation result status. - :type status: int - :param payload: Method invocation result payload. - :type payload: object - """ - - _attribute_map = { - "status": {"key": "status", "type": "int"}, - "payload": {"key": "payload", "type": "object"}, - } - - def __init__(self, *, status: int = None, payload=None, **kwargs) -> None: - super(CloudToDeviceMethodResult, self).__init__(**kwargs) - self.status = status - self.payload = payload diff --git a/src/azure/iot/hub/protocol/models/configuration.py b/src/azure/iot/hub/protocol/models/configuration.py deleted file mode 100644 index 328cab0..0000000 --- a/src/azure/iot/hub/protocol/models/configuration.py +++ /dev/null @@ -1,68 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is -# regenerated. -# -------------------------------------------------------------------------- - -from msrest.serialization import Model - - -class Configuration(Model): - """The configuration for Iot Hub device and module twins. - - :param id: The unique identifier of the configuration. - :type id: str - :param schema_version: The schema version of the configuration. - :type schema_version: str - :param labels: The key-value pairs used to describe the configuration. - :type labels: dict[str, str] - :param content: The content of the configuration. - :type content: ~protocol.models.ConfigurationContent - :param target_condition: The query used to define the targeted devices or - modules. The query is based on twin tags and/or reported properties. - :type target_condition: str - :param created_time_utc: The creation date and time of the configuration. - :type created_time_utc: datetime - :param last_updated_time_utc: The update date and time of the - configuration. - :type last_updated_time_utc: datetime - :param priority: The priority number assigned to the configuration. - :type priority: int - :param system_metrics: The system metrics computed by the IoT Hub that - cannot be customized. - :type system_metrics: ~protocol.models.ConfigurationMetrics - :param metrics: The custom metrics specified by the developer as queries - against twin reported properties. - :type metrics: ~protocol.models.ConfigurationMetrics - :param etag: The ETag of the configuration. - :type etag: str - """ - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "schema_version": {"key": "schemaVersion", "type": "str"}, - "labels": {"key": "labels", "type": "{str}"}, - "content": {"key": "content", "type": "ConfigurationContent"}, - "target_condition": {"key": "targetCondition", "type": "str"}, - "created_time_utc": {"key": "createdTimeUtc", "type": "iso-8601"}, - "last_updated_time_utc": {"key": "lastUpdatedTimeUtc", "type": "iso-8601"}, - "priority": {"key": "priority", "type": "int"}, - "system_metrics": {"key": "systemMetrics", "type": "ConfigurationMetrics"}, - "metrics": {"key": "metrics", "type": "ConfigurationMetrics"}, - "etag": {"key": "etag", "type": "str"}, - } - - def __init__(self, **kwargs): - super(Configuration, self).__init__(**kwargs) - self.id = kwargs.get("id", None) - self.schema_version = kwargs.get("schema_version", None) - self.labels = kwargs.get("labels", None) - self.content = kwargs.get("content", None) - self.target_condition = kwargs.get("target_condition", None) - self.created_time_utc = kwargs.get("created_time_utc", None) - self.last_updated_time_utc = kwargs.get("last_updated_time_utc", None) - self.priority = kwargs.get("priority", None) - self.system_metrics = kwargs.get("system_metrics", None) - self.metrics = kwargs.get("metrics", None) - self.etag = kwargs.get("etag", None) diff --git a/src/azure/iot/hub/protocol/models/configuration_content.py b/src/azure/iot/hub/protocol/models/configuration_content.py deleted file mode 100644 index 37b1430..0000000 --- a/src/azure/iot/hub/protocol/models/configuration_content.py +++ /dev/null @@ -1,32 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is -# regenerated. -# -------------------------------------------------------------------------- - -from msrest.serialization import Model - - -class ConfigurationContent(Model): - """The configuration content for devices or modules on edge devices. - - :param device_content: The device configuration content. - :type device_content: dict[str, object] - :param modules_content: The modules configuration content. - :type modules_content: dict[str, dict[str, object]] - :param module_content: The module configuration content. - :type module_content: dict[str, object] - """ - - _attribute_map = { - "device_content": {"key": "deviceContent", "type": "{object}"}, - "modules_content": {"key": "modulesContent", "type": "{{object}}"}, - "module_content": {"key": "moduleContent", "type": "{object}"}, - } - - def __init__(self, **kwargs): - super(ConfigurationContent, self).__init__(**kwargs) - self.device_content = kwargs.get("device_content", None) - self.modules_content = kwargs.get("modules_content", None) - self.module_content = kwargs.get("module_content", None) diff --git a/src/azure/iot/hub/protocol/models/configuration_content_py3.py b/src/azure/iot/hub/protocol/models/configuration_content_py3.py deleted file mode 100644 index 11eba35..0000000 --- a/src/azure/iot/hub/protocol/models/configuration_content_py3.py +++ /dev/null @@ -1,34 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is -# regenerated. -# -------------------------------------------------------------------------- - -from msrest.serialization import Model - - -class ConfigurationContent(Model): - """The configuration content for devices or modules on edge devices. - - :param device_content: The device configuration content. - :type device_content: dict[str, object] - :param modules_content: The modules configuration content. - :type modules_content: dict[str, dict[str, object]] - :param module_content: The module configuration content. - :type module_content: dict[str, object] - """ - - _attribute_map = { - "device_content": {"key": "deviceContent", "type": "{object}"}, - "modules_content": {"key": "modulesContent", "type": "{{object}}"}, - "module_content": {"key": "moduleContent", "type": "{object}"}, - } - - def __init__( - self, *, device_content=None, modules_content=None, module_content=None, **kwargs - ) -> None: - super(ConfigurationContent, self).__init__(**kwargs) - self.device_content = device_content - self.modules_content = modules_content - self.module_content = module_content diff --git a/src/azure/iot/hub/protocol/models/configuration_metrics.py b/src/azure/iot/hub/protocol/models/configuration_metrics.py deleted file mode 100644 index afeeb40..0000000 --- a/src/azure/iot/hub/protocol/models/configuration_metrics.py +++ /dev/null @@ -1,28 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is -# regenerated. -# -------------------------------------------------------------------------- - -from msrest.serialization import Model - - -class ConfigurationMetrics(Model): - """The configuration metrics for Iot Hub devices and modules. - - :param results: The results of the metrics collection queries. - :type results: dict[str, long] - :param queries: The key-value pairs with queries and their identifier. - :type queries: dict[str, str] - """ - - _attribute_map = { - "results": {"key": "results", "type": "{long}"}, - "queries": {"key": "queries", "type": "{str}"}, - } - - def __init__(self, **kwargs): - super(ConfigurationMetrics, self).__init__(**kwargs) - self.results = kwargs.get("results", None) - self.queries = kwargs.get("queries", None) diff --git a/src/azure/iot/hub/protocol/models/configuration_metrics_py3.py b/src/azure/iot/hub/protocol/models/configuration_metrics_py3.py deleted file mode 100644 index aa656e2..0000000 --- a/src/azure/iot/hub/protocol/models/configuration_metrics_py3.py +++ /dev/null @@ -1,28 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is -# regenerated. -# -------------------------------------------------------------------------- - -from msrest.serialization import Model - - -class ConfigurationMetrics(Model): - """The configuration metrics for Iot Hub devices and modules. - - :param results: The results of the metrics collection queries. - :type results: dict[str, long] - :param queries: The key-value pairs with queries and their identifier. - :type queries: dict[str, str] - """ - - _attribute_map = { - "results": {"key": "results", "type": "{long}"}, - "queries": {"key": "queries", "type": "{str}"}, - } - - def __init__(self, *, results=None, queries=None, **kwargs) -> None: - super(ConfigurationMetrics, self).__init__(**kwargs) - self.results = results - self.queries = queries diff --git a/src/azure/iot/hub/protocol/models/configuration_py3.py b/src/azure/iot/hub/protocol/models/configuration_py3.py deleted file mode 100644 index e91eaaf..0000000 --- a/src/azure/iot/hub/protocol/models/configuration_py3.py +++ /dev/null @@ -1,83 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is -# regenerated. -# -------------------------------------------------------------------------- - -from msrest.serialization import Model - - -class Configuration(Model): - """The configuration for Iot Hub device and module twins. - - :param id: The unique identifier of the configuration. - :type id: str - :param schema_version: The schema version of the configuration. - :type schema_version: str - :param labels: The key-value pairs used to describe the configuration. - :type labels: dict[str, str] - :param content: The content of the configuration. - :type content: ~protocol.models.ConfigurationContent - :param target_condition: The query used to define the targeted devices or - modules. The query is based on twin tags and/or reported properties. - :type target_condition: str - :param created_time_utc: The creation date and time of the configuration. - :type created_time_utc: datetime - :param last_updated_time_utc: The update date and time of the - configuration. - :type last_updated_time_utc: datetime - :param priority: The priority number assigned to the configuration. - :type priority: int - :param system_metrics: The system metrics computed by the IoT Hub that - cannot be customized. - :type system_metrics: ~protocol.models.ConfigurationMetrics - :param metrics: The custom metrics specified by the developer as queries - against twin reported properties. - :type metrics: ~protocol.models.ConfigurationMetrics - :param etag: The ETag of the configuration. - :type etag: str - """ - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "schema_version": {"key": "schemaVersion", "type": "str"}, - "labels": {"key": "labels", "type": "{str}"}, - "content": {"key": "content", "type": "ConfigurationContent"}, - "target_condition": {"key": "targetCondition", "type": "str"}, - "created_time_utc": {"key": "createdTimeUtc", "type": "iso-8601"}, - "last_updated_time_utc": {"key": "lastUpdatedTimeUtc", "type": "iso-8601"}, - "priority": {"key": "priority", "type": "int"}, - "system_metrics": {"key": "systemMetrics", "type": "ConfigurationMetrics"}, - "metrics": {"key": "metrics", "type": "ConfigurationMetrics"}, - "etag": {"key": "etag", "type": "str"}, - } - - def __init__( - self, - *, - id: str = None, - schema_version: str = None, - labels=None, - content=None, - target_condition: str = None, - created_time_utc=None, - last_updated_time_utc=None, - priority: int = None, - system_metrics=None, - metrics=None, - etag: str = None, - **kwargs - ) -> None: - super(Configuration, self).__init__(**kwargs) - self.id = id - self.schema_version = schema_version - self.labels = labels - self.content = content - self.target_condition = target_condition - self.created_time_utc = created_time_utc - self.last_updated_time_utc = last_updated_time_utc - self.priority = priority - self.system_metrics = system_metrics - self.metrics = metrics - self.etag = etag diff --git a/src/azure/iot/hub/protocol/models/configuration_queries_test_input.py b/src/azure/iot/hub/protocol/models/configuration_queries_test_input.py deleted file mode 100644 index d4c1974..0000000 --- a/src/azure/iot/hub/protocol/models/configuration_queries_test_input.py +++ /dev/null @@ -1,30 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is -# regenerated. -# -------------------------------------------------------------------------- - -from msrest.serialization import Model - - -class ConfigurationQueriesTestInput(Model): - """ConfigurationQueriesTestInput. - - :param target_condition: The query used to define targeted devices or - modules. The query is based on twin tags and/or reported properties. - :type target_condition: str - :param custom_metric_queries: The key-value pairs with queries and their - identifier. - :type custom_metric_queries: dict[str, str] - """ - - _attribute_map = { - "target_condition": {"key": "targetCondition", "type": "str"}, - "custom_metric_queries": {"key": "customMetricQueries", "type": "{str}"}, - } - - def __init__(self, **kwargs): - super(ConfigurationQueriesTestInput, self).__init__(**kwargs) - self.target_condition = kwargs.get("target_condition", None) - self.custom_metric_queries = kwargs.get("custom_metric_queries", None) diff --git a/src/azure/iot/hub/protocol/models/configuration_queries_test_input_py3.py b/src/azure/iot/hub/protocol/models/configuration_queries_test_input_py3.py deleted file mode 100644 index 65a45e1..0000000 --- a/src/azure/iot/hub/protocol/models/configuration_queries_test_input_py3.py +++ /dev/null @@ -1,32 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is -# regenerated. -# -------------------------------------------------------------------------- - -from msrest.serialization import Model - - -class ConfigurationQueriesTestInput(Model): - """ConfigurationQueriesTestInput. - - :param target_condition: The query used to define targeted devices or - modules. The query is based on twin tags and/or reported properties. - :type target_condition: str - :param custom_metric_queries: The key-value pairs with queries and their - identifier. - :type custom_metric_queries: dict[str, str] - """ - - _attribute_map = { - "target_condition": {"key": "targetCondition", "type": "str"}, - "custom_metric_queries": {"key": "customMetricQueries", "type": "{str}"}, - } - - def __init__( - self, *, target_condition: str = None, custom_metric_queries=None, **kwargs - ) -> None: - super(ConfigurationQueriesTestInput, self).__init__(**kwargs) - self.target_condition = target_condition - self.custom_metric_queries = custom_metric_queries diff --git a/src/azure/iot/hub/protocol/models/configuration_queries_test_response.py b/src/azure/iot/hub/protocol/models/configuration_queries_test_response.py deleted file mode 100644 index dfda7d5..0000000 --- a/src/azure/iot/hub/protocol/models/configuration_queries_test_response.py +++ /dev/null @@ -1,30 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is -# regenerated. -# -------------------------------------------------------------------------- - -from msrest.serialization import Model - - -class ConfigurationQueriesTestResponse(Model): - """ConfigurationQueriesTestResponse. - - :param target_condition_error: The errors from running the target - condition query. - :type target_condition_error: str - :param custom_metric_query_errors: The errors from running the custom - metric query. - :type custom_metric_query_errors: dict[str, str] - """ - - _attribute_map = { - "target_condition_error": {"key": "targetConditionError", "type": "str"}, - "custom_metric_query_errors": {"key": "customMetricQueryErrors", "type": "{str}"}, - } - - def __init__(self, **kwargs): - super(ConfigurationQueriesTestResponse, self).__init__(**kwargs) - self.target_condition_error = kwargs.get("target_condition_error", None) - self.custom_metric_query_errors = kwargs.get("custom_metric_query_errors", None) diff --git a/src/azure/iot/hub/protocol/models/configuration_queries_test_response_py3.py b/src/azure/iot/hub/protocol/models/configuration_queries_test_response_py3.py deleted file mode 100644 index b015928..0000000 --- a/src/azure/iot/hub/protocol/models/configuration_queries_test_response_py3.py +++ /dev/null @@ -1,32 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is -# regenerated. -# -------------------------------------------------------------------------- - -from msrest.serialization import Model - - -class ConfigurationQueriesTestResponse(Model): - """ConfigurationQueriesTestResponse. - - :param target_condition_error: The errors from running the target - condition query. - :type target_condition_error: str - :param custom_metric_query_errors: The errors from running the custom - metric query. - :type custom_metric_query_errors: dict[str, str] - """ - - _attribute_map = { - "target_condition_error": {"key": "targetConditionError", "type": "str"}, - "custom_metric_query_errors": {"key": "customMetricQueryErrors", "type": "{str}"}, - } - - def __init__( - self, *, target_condition_error: str = None, custom_metric_query_errors=None, **kwargs - ) -> None: - super(ConfigurationQueriesTestResponse, self).__init__(**kwargs) - self.target_condition_error = target_condition_error - self.custom_metric_query_errors = custom_metric_query_errors diff --git a/src/azure/iot/hub/protocol/models/device.py b/src/azure/iot/hub/protocol/models/device.py deleted file mode 100644 index 9b814d0..0000000 --- a/src/azure/iot/hub/protocol/models/device.py +++ /dev/null @@ -1,91 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is -# regenerated. -# -------------------------------------------------------------------------- - -from msrest.serialization import Model - - -class Device(Model): - """Device. - - :param device_id: The unique identifier of the device. - :type device_id: str - :param generation_id: The IoT Hub-generated, case-sensitive string up to - 128 characters long. This value is used to distinguish devices with the - same deviceId, when they have been deleted and re-created. - :type generation_id: str - :param etag: The string representing a weak ETag for the device identity, - as per RFC7232. - :type etag: str - :param connection_state: The state of the device. Possible values include: - 'Disconnected', 'Connected' - :type connection_state: str or ~protocol.models.enum - :param status: The status of the device. If the status disabled, a device - cannot connect to the service. Possible values include: 'enabled', - 'disabled' - :type status: str or ~protocol.models.enum - :param status_reason: The 128 character-long string that stores the reason - for the device identity status. All UTF-8 characters are allowed. - :type status_reason: str - :param connection_state_updated_time: The date and time the connection - state was last updated. - :type connection_state_updated_time: datetime - :param status_updated_time: The date and time when the status field was - last updated. - :type status_updated_time: datetime - :param last_activity_time: The date and last time the device last - connected, received, or sent a message. - :type last_activity_time: datetime - :param cloud_to_device_message_count: The number of cloud-to-device - messages currently queued to be sent to the device. - :type cloud_to_device_message_count: int - :param authentication: The authentication mechanism used by the device. - :type authentication: ~protocol.models.AuthenticationMechanism - :param capabilities: The set of capabilities of the device. For example, - if this device is an edge device or not. - :type capabilities: ~protocol.models.DeviceCapabilities - :param device_scope: The scope of the device. Auto generated and immutable - for edge devices and modifiable in leaf devices to create child/parent - relationship. - :type device_scope: str - :param parent_scopes: The scopes of the upper level edge devices if - applicable. Only available for edge devices. - :type parent_scopes: list[str] - """ - - _attribute_map = { - "device_id": {"key": "deviceId", "type": "str"}, - "generation_id": {"key": "generationId", "type": "str"}, - "etag": {"key": "etag", "type": "str"}, - "connection_state": {"key": "connectionState", "type": "str"}, - "status": {"key": "status", "type": "str"}, - "status_reason": {"key": "statusReason", "type": "str"}, - "connection_state_updated_time": {"key": "connectionStateUpdatedTime", "type": "iso-8601"}, - "status_updated_time": {"key": "statusUpdatedTime", "type": "iso-8601"}, - "last_activity_time": {"key": "lastActivityTime", "type": "iso-8601"}, - "cloud_to_device_message_count": {"key": "cloudToDeviceMessageCount", "type": "int"}, - "authentication": {"key": "authentication", "type": "AuthenticationMechanism"}, - "capabilities": {"key": "capabilities", "type": "DeviceCapabilities"}, - "device_scope": {"key": "deviceScope", "type": "str"}, - "parent_scopes": {"key": "parentScopes", "type": "[str]"}, - } - - def __init__(self, **kwargs): - super(Device, self).__init__(**kwargs) - self.device_id = kwargs.get("device_id", None) - self.generation_id = kwargs.get("generation_id", None) - self.etag = kwargs.get("etag", None) - self.connection_state = kwargs.get("connection_state", None) - self.status = kwargs.get("status", None) - self.status_reason = kwargs.get("status_reason", None) - self.connection_state_updated_time = kwargs.get("connection_state_updated_time", None) - self.status_updated_time = kwargs.get("status_updated_time", None) - self.last_activity_time = kwargs.get("last_activity_time", None) - self.cloud_to_device_message_count = kwargs.get("cloud_to_device_message_count", None) - self.authentication = kwargs.get("authentication", None) - self.capabilities = kwargs.get("capabilities", None) - self.device_scope = kwargs.get("device_scope", None) - self.parent_scopes = kwargs.get("parent_scopes", None) diff --git a/src/azure/iot/hub/protocol/models/device_capabilities.py b/src/azure/iot/hub/protocol/models/device_capabilities.py deleted file mode 100644 index 5381432..0000000 --- a/src/azure/iot/hub/protocol/models/device_capabilities.py +++ /dev/null @@ -1,23 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is -# regenerated. -# -------------------------------------------------------------------------- - -from msrest.serialization import Model - - -class DeviceCapabilities(Model): - """The status of capabilities enabled on the device. - - :param iot_edge: The property that determines if the device is an edge - device or not. - :type iot_edge: bool - """ - - _attribute_map = {"iot_edge": {"key": "iotEdge", "type": "bool"}} - - def __init__(self, **kwargs): - super(DeviceCapabilities, self).__init__(**kwargs) - self.iot_edge = kwargs.get("iot_edge", None) diff --git a/src/azure/iot/hub/protocol/models/device_capabilities_py3.py b/src/azure/iot/hub/protocol/models/device_capabilities_py3.py deleted file mode 100644 index 813ca6d..0000000 --- a/src/azure/iot/hub/protocol/models/device_capabilities_py3.py +++ /dev/null @@ -1,23 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is -# regenerated. -# -------------------------------------------------------------------------- - -from msrest.serialization import Model - - -class DeviceCapabilities(Model): - """The status of capabilities enabled on the device. - - :param iot_edge: The property that determines if the device is an edge - device or not. - :type iot_edge: bool - """ - - _attribute_map = {"iot_edge": {"key": "iotEdge", "type": "bool"}} - - def __init__(self, *, iot_edge: bool = None, **kwargs) -> None: - super(DeviceCapabilities, self).__init__(**kwargs) - self.iot_edge = iot_edge diff --git a/src/azure/iot/hub/protocol/models/device_job_statistics.py b/src/azure/iot/hub/protocol/models/device_job_statistics.py deleted file mode 100644 index f13391b..0000000 --- a/src/azure/iot/hub/protocol/models/device_job_statistics.py +++ /dev/null @@ -1,40 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is -# regenerated. -# -------------------------------------------------------------------------- - -from msrest.serialization import Model - - -class DeviceJobStatistics(Model): - """The job statistics regarding execution status. - - :param device_count: The number of devices targeted by the job. - :type device_count: int - :param failed_count: The number of failed jobs. - :type failed_count: int - :param succeeded_count: The number of succeeded jobs. - :type succeeded_count: int - :param running_count: The number of running jobs. - :type running_count: int - :param pending_count: The number of pending (scheduled) jobs. - :type pending_count: int - """ - - _attribute_map = { - "device_count": {"key": "deviceCount", "type": "int"}, - "failed_count": {"key": "failedCount", "type": "int"}, - "succeeded_count": {"key": "succeededCount", "type": "int"}, - "running_count": {"key": "runningCount", "type": "int"}, - "pending_count": {"key": "pendingCount", "type": "int"}, - } - - def __init__(self, **kwargs): - super(DeviceJobStatistics, self).__init__(**kwargs) - self.device_count = kwargs.get("device_count", None) - self.failed_count = kwargs.get("failed_count", None) - self.succeeded_count = kwargs.get("succeeded_count", None) - self.running_count = kwargs.get("running_count", None) - self.pending_count = kwargs.get("pending_count", None) diff --git a/src/azure/iot/hub/protocol/models/device_job_statistics_py3.py b/src/azure/iot/hub/protocol/models/device_job_statistics_py3.py deleted file mode 100644 index eaef475..0000000 --- a/src/azure/iot/hub/protocol/models/device_job_statistics_py3.py +++ /dev/null @@ -1,49 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is -# regenerated. -# -------------------------------------------------------------------------- - -from msrest.serialization import Model - - -class DeviceJobStatistics(Model): - """The job statistics regarding execution status. - - :param device_count: The number of devices targeted by the job. - :type device_count: int - :param failed_count: The number of failed jobs. - :type failed_count: int - :param succeeded_count: The number of succeeded jobs. - :type succeeded_count: int - :param running_count: The number of running jobs. - :type running_count: int - :param pending_count: The number of pending (scheduled) jobs. - :type pending_count: int - """ - - _attribute_map = { - "device_count": {"key": "deviceCount", "type": "int"}, - "failed_count": {"key": "failedCount", "type": "int"}, - "succeeded_count": {"key": "succeededCount", "type": "int"}, - "running_count": {"key": "runningCount", "type": "int"}, - "pending_count": {"key": "pendingCount", "type": "int"}, - } - - def __init__( - self, - *, - device_count: int = None, - failed_count: int = None, - succeeded_count: int = None, - running_count: int = None, - pending_count: int = None, - **kwargs - ) -> None: - super(DeviceJobStatistics, self).__init__(**kwargs) - self.device_count = device_count - self.failed_count = failed_count - self.succeeded_count = succeeded_count - self.running_count = running_count - self.pending_count = pending_count diff --git a/src/azure/iot/hub/protocol/models/device_py3.py b/src/azure/iot/hub/protocol/models/device_py3.py deleted file mode 100644 index 8a42689..0000000 --- a/src/azure/iot/hub/protocol/models/device_py3.py +++ /dev/null @@ -1,109 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is -# regenerated. -# -------------------------------------------------------------------------- - -from msrest.serialization import Model - - -class Device(Model): - """Device. - - :param device_id: The unique identifier of the device. - :type device_id: str - :param generation_id: The IoT Hub-generated, case-sensitive string up to - 128 characters long. This value is used to distinguish devices with the - same deviceId, when they have been deleted and re-created. - :type generation_id: str - :param etag: The string representing a weak ETag for the device identity, - as per RFC7232. - :type etag: str - :param connection_state: The state of the device. Possible values include: - 'Disconnected', 'Connected' - :type connection_state: str or ~protocol.models.enum - :param status: The status of the device. If the status disabled, a device - cannot connect to the service. Possible values include: 'enabled', - 'disabled' - :type status: str or ~protocol.models.enum - :param status_reason: The 128 character-long string that stores the reason - for the device identity status. All UTF-8 characters are allowed. - :type status_reason: str - :param connection_state_updated_time: The date and time the connection - state was last updated. - :type connection_state_updated_time: datetime - :param status_updated_time: The date and time when the status field was - last updated. - :type status_updated_time: datetime - :param last_activity_time: The date and last time the device last - connected, received, or sent a message. - :type last_activity_time: datetime - :param cloud_to_device_message_count: The number of cloud-to-device - messages currently queued to be sent to the device. - :type cloud_to_device_message_count: int - :param authentication: The authentication mechanism used by the device. - :type authentication: ~protocol.models.AuthenticationMechanism - :param capabilities: The set of capabilities of the device. For example, - if this device is an edge device or not. - :type capabilities: ~protocol.models.DeviceCapabilities - :param device_scope: The scope of the device. Auto generated and immutable - for edge devices and modifiable in leaf devices to create child/parent - relationship. - :type device_scope: str - :param parent_scopes: The scopes of the upper level edge devices if - applicable. Only available for edge devices. - :type parent_scopes: list[str] - """ - - _attribute_map = { - "device_id": {"key": "deviceId", "type": "str"}, - "generation_id": {"key": "generationId", "type": "str"}, - "etag": {"key": "etag", "type": "str"}, - "connection_state": {"key": "connectionState", "type": "str"}, - "status": {"key": "status", "type": "str"}, - "status_reason": {"key": "statusReason", "type": "str"}, - "connection_state_updated_time": {"key": "connectionStateUpdatedTime", "type": "iso-8601"}, - "status_updated_time": {"key": "statusUpdatedTime", "type": "iso-8601"}, - "last_activity_time": {"key": "lastActivityTime", "type": "iso-8601"}, - "cloud_to_device_message_count": {"key": "cloudToDeviceMessageCount", "type": "int"}, - "authentication": {"key": "authentication", "type": "AuthenticationMechanism"}, - "capabilities": {"key": "capabilities", "type": "DeviceCapabilities"}, - "device_scope": {"key": "deviceScope", "type": "str"}, - "parent_scopes": {"key": "parentScopes", "type": "[str]"}, - } - - def __init__( - self, - *, - device_id: str = None, - generation_id: str = None, - etag: str = None, - connection_state=None, - status=None, - status_reason: str = None, - connection_state_updated_time=None, - status_updated_time=None, - last_activity_time=None, - cloud_to_device_message_count: int = None, - authentication=None, - capabilities=None, - device_scope: str = None, - parent_scopes=None, - **kwargs - ) -> None: - super(Device, self).__init__(**kwargs) - self.device_id = device_id - self.generation_id = generation_id - self.etag = etag - self.connection_state = connection_state - self.status = status - self.status_reason = status_reason - self.connection_state_updated_time = connection_state_updated_time - self.status_updated_time = status_updated_time - self.last_activity_time = last_activity_time - self.cloud_to_device_message_count = cloud_to_device_message_count - self.authentication = authentication - self.capabilities = capabilities - self.device_scope = device_scope - self.parent_scopes = parent_scopes diff --git a/src/azure/iot/hub/protocol/models/device_registry_operation_error.py b/src/azure/iot/hub/protocol/models/device_registry_operation_error.py deleted file mode 100644 index f983bf3..0000000 --- a/src/azure/iot/hub/protocol/models/device_registry_operation_error.py +++ /dev/null @@ -1,138 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is -# regenerated. -# -------------------------------------------------------------------------- - -from msrest.serialization import Model - - -class DeviceRegistryOperationError(Model): - """The device registry operation error details. - - :param device_id: The unique identifier of the device. - :type device_id: str - :param error_code: The error code. Possible values include: - 'InvalidErrorCode', 'GenericBadRequest', 'InvalidProtocolVersion', - 'DeviceInvalidResultCount', 'InvalidOperation', 'ArgumentInvalid', - 'ArgumentNull', 'IotHubFormatError', - 'DeviceStorageEntitySerializationError', 'BlobContainerValidationError', - 'ImportWarningExistsError', 'InvalidSchemaVersion', - 'DeviceDefinedMultipleTimes', 'DeserializationError', - 'BulkRegistryOperationFailure', 'DefaultStorageEndpointNotConfigured', - 'InvalidFileUploadCorrelationId', 'ExpiredFileUploadCorrelationId', - 'InvalidStorageEndpoint', 'InvalidMessagingEndpoint', - 'InvalidFileUploadCompletionStatus', 'InvalidStorageEndpointOrBlob', - 'RequestCanceled', 'InvalidStorageEndpointProperty', 'EtagDoesNotMatch', - 'RequestTimedOut', 'UnsupportedOperationOnReplica', 'NullMessage', - 'ConnectionForcefullyClosedOnNewConnection', 'InvalidDeviceScope', - 'ConnectionForcefullyClosedOnFaultInjection', - 'ConnectionRejectedOnFaultInjection', 'InvalidEndpointAuthenticationType', - 'ManagedIdentityNotEnabled', 'InvalidRouteTestInput', - 'InvalidSourceOnRoute', 'RoutingNotEnabled', - 'InvalidContentEncodingOrType', 'InvalidEndorsementKey', - 'InvalidRegistrationId', 'InvalidStorageRootKey', - 'InvalidEnrollmentGroupId', 'TooManyEnrollments', - 'RegistrationIdDefinedMultipleTimes', 'CustomAllocationFailed', - 'CustomAllocationIotHubNotSpecified', - 'CustomAllocationUnauthorizedAccess', 'CannotRegisterModuleToModule', - 'TenantHubRoutingNotEnabled', 'InvalidConfigurationTargetCondition', - 'InvalidConfigurationContent', - 'CannotModifyImmutableConfigurationContent', - 'InvalidConfigurationCustomMetricsQuery', 'InvalidPnPInterfaceDefinition', - 'InvalidPnPDesiredProperties', 'InvalidPnPReportedProperties', - 'InvalidPnPWritableReportedProperties', 'InvalidDigitalTwinJsonPatch', - 'InvalidDigitalTwinPayload', 'InvalidDigitalTwinPatch', - 'InvalidDigitalTwinPatchPath', 'GenericUnauthorized', 'IotHubNotFound', - 'IotHubUnauthorizedAccess', 'IotHubUnauthorized', 'ElasticPoolNotFound', - 'SystemModuleModifyUnauthorizedAccess', 'GenericForbidden', - 'IotHubSuspended', 'IotHubQuotaExceeded', 'JobQuotaExceeded', - 'DeviceMaximumQueueDepthExceeded', 'IotHubMaxCbsTokenExceeded', - 'DeviceMaximumActiveFileUploadLimitExceeded', - 'DeviceMaximumQueueSizeExceeded', 'RoutingEndpointResponseForbidden', - 'InvalidMessageExpiryTime', 'OperationNotAvailableInCurrentTier', - 'KeyEncryptionKeyRevoked', 'DeviceModelMaxPropertiesExceeded', - 'DeviceModelMaxIndexablePropertiesExceeded', 'IotDpsSuspended', - 'IotDpsSuspending', 'GenericNotFound', 'DeviceNotFound', 'JobNotFound', - 'QuotaMetricNotFound', 'SystemPropertyNotFound', 'AmqpAddressNotFound', - 'RoutingEndpointResponseNotFound', 'CertificateNotFound', - 'ElasticPoolTenantHubNotFound', 'ModuleNotFound', - 'AzureTableStoreNotFound', 'IotHubFailingOver', 'FeatureNotSupported', - 'DigitalTwinInterfaceNotFound', 'QueryStoreClusterNotFound', - 'DeviceNotOnline', 'DeviceConnectionClosedRemotely', 'EnrollmentNotFound', - 'DeviceRegistrationNotFound', 'AsyncOperationNotFound', - 'EnrollmentGroupNotFound', 'DeviceRecordNotFound', 'GroupRecordNotFound', - 'DeviceGroupNotFound', 'ProvisioningSettingsNotFound', - 'ProvisioningRecordNotFound', 'LinkedHubNotFound', - 'CertificateAuthorityNotFound', 'ConfigurationNotFound', 'GroupNotFound', - 'DigitalTwinModelNotFound', 'InterfaceNameModelNotFound', - 'GenericMethodNotAllowed', 'OperationNotAllowedInCurrentState', - 'ImportDevicesNotSupported', 'BulkAddDevicesNotSupported', - 'GenericConflict', 'DeviceAlreadyExists', 'LinkCreationConflict', - 'CallbackSubscriptionConflict', 'ModelAlreadyExists', 'DeviceLocked', - 'DeviceJobAlreadyExists', 'JobAlreadyExists', 'EnrollmentConflict', - 'EnrollmentGroupConflict', 'RegistrationStatusConflict', - 'DeviceRecordConflict', 'GroupRecordConflict', 'DeviceGroupConflict', - 'ProvisioningSettingsConflict', 'ProvisioningRecordConflict', - 'LinkedHubConflict', 'CertificateAuthorityConflict', - 'ModuleAlreadyExistsOnDevice', 'ConfigurationAlreadyExists', - 'ApplyConfigurationAlreadyInProgressOnDevice', - 'DigitalTwinModelAlreadyExists', - 'DigitalTwinModelExistsWithOtherModelType', - 'InterfaceNameModelAlreadyExists', 'GenericPreconditionFailed', - 'PreconditionFailed', 'DeviceMessageLockLost', 'JobRunPreconditionFailed', - 'InflightMessagesInLink', 'GenericRequestEntityTooLarge', - 'MessageTooLarge', 'TooManyDevices', 'TooManyModulesOnDevice', - 'ConfigurationCountLimitExceeded', 'DigitalTwinModelCountLimitExceeded', - 'InterfaceNameCompressionModelCountLimitExceeded', - 'GenericUnsupportedMediaType', 'IncompatibleDataType', - 'GenericTooManyRequests', 'ThrottlingException', - 'ThrottleBacklogLimitExceeded', 'ThrottlingBacklogTimeout', - 'ThrottlingMaxActiveJobCountExceeded', 'DeviceThrottlingLimitExceeded', - 'ClientClosedRequest', 'GenericServerError', 'ServerError', - 'JobCancelled', 'StatisticsRetrievalError', 'ConnectionForcefullyClosed', - 'InvalidBlobState', 'BackupTimedOut', 'AzureStorageTimeout', - 'GenericTimeout', 'InvalidThrottleParameter', 'EventHubLinkAlreadyClosed', - 'ReliableBlobStoreError', 'RetryAttemptsExhausted', - 'AzureTableStoreError', 'CheckpointStoreNotFound', - 'DocumentDbInvalidReturnValue', 'ReliableDocDbStoreStoreError', - 'ReliableBlobStoreTimeoutError', 'ConfigReadFailed', - 'InvalidContainerReceiveLink', 'InvalidPartitionEpoch', 'RestoreTimedOut', - 'StreamReservationFailure', 'SerializationError', - 'UnexpectedPropertyValue', 'OrchestrationOperationFailed', - 'ModelRepoEndpointError', 'ResolutionError', 'UnableToFetchCredentials', - 'UnableToFetchTenantInfo', 'UnableToShareIdentity', - 'UnableToExpandDiscoveryInfo', 'UnableToExpandComponentInfo', - 'UnableToCompressComponentInfo', 'UnableToCompressDiscoveryInfo', - 'OrphanDiscoveryDocument', 'GenericBadGateway', - 'InvalidResponseWhileProxying', 'GenericServiceUnavailable', - 'ServiceUnavailable', 'PartitionNotFound', 'IotHubActivationFailed', - 'ServerBusy', 'IotHubRestoring', 'ReceiveLinkOpensThrottled', - 'ConnectionUnavailable', 'DeviceUnavailable', 'ConfigurationNotAvailable', - 'GroupNotAvailable', 'HostingServiceNotAvailable', - 'GenericGatewayTimeout', 'GatewayTimeout' - :type error_code: str or ~protocol.models.enum - :param error_status: The details of the error. - :type error_status: str - :param module_id: The unique identifier of the module, if applicable. - :type module_id: str - :param operation: The type of the operation that failed. - :type operation: str - """ - - _attribute_map = { - "device_id": {"key": "deviceId", "type": "str"}, - "error_code": {"key": "errorCode", "type": "str"}, - "error_status": {"key": "errorStatus", "type": "str"}, - "module_id": {"key": "moduleId", "type": "str"}, - "operation": {"key": "operation", "type": "str"}, - } - - def __init__(self, **kwargs): - super(DeviceRegistryOperationError, self).__init__(**kwargs) - self.device_id = kwargs.get("device_id", None) - self.error_code = kwargs.get("error_code", None) - self.error_status = kwargs.get("error_status", None) - self.module_id = kwargs.get("module_id", None) - self.operation = kwargs.get("operation", None) diff --git a/src/azure/iot/hub/protocol/models/device_registry_operation_error_py3.py b/src/azure/iot/hub/protocol/models/device_registry_operation_error_py3.py deleted file mode 100644 index 4ac5d0d..0000000 --- a/src/azure/iot/hub/protocol/models/device_registry_operation_error_py3.py +++ /dev/null @@ -1,147 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is -# regenerated. -# -------------------------------------------------------------------------- - -from msrest.serialization import Model - - -class DeviceRegistryOperationError(Model): - """The device registry operation error details. - - :param device_id: The unique identifier of the device. - :type device_id: str - :param error_code: The error code. Possible values include: - 'InvalidErrorCode', 'GenericBadRequest', 'InvalidProtocolVersion', - 'DeviceInvalidResultCount', 'InvalidOperation', 'ArgumentInvalid', - 'ArgumentNull', 'IotHubFormatError', - 'DeviceStorageEntitySerializationError', 'BlobContainerValidationError', - 'ImportWarningExistsError', 'InvalidSchemaVersion', - 'DeviceDefinedMultipleTimes', 'DeserializationError', - 'BulkRegistryOperationFailure', 'DefaultStorageEndpointNotConfigured', - 'InvalidFileUploadCorrelationId', 'ExpiredFileUploadCorrelationId', - 'InvalidStorageEndpoint', 'InvalidMessagingEndpoint', - 'InvalidFileUploadCompletionStatus', 'InvalidStorageEndpointOrBlob', - 'RequestCanceled', 'InvalidStorageEndpointProperty', 'EtagDoesNotMatch', - 'RequestTimedOut', 'UnsupportedOperationOnReplica', 'NullMessage', - 'ConnectionForcefullyClosedOnNewConnection', 'InvalidDeviceScope', - 'ConnectionForcefullyClosedOnFaultInjection', - 'ConnectionRejectedOnFaultInjection', 'InvalidEndpointAuthenticationType', - 'ManagedIdentityNotEnabled', 'InvalidRouteTestInput', - 'InvalidSourceOnRoute', 'RoutingNotEnabled', - 'InvalidContentEncodingOrType', 'InvalidEndorsementKey', - 'InvalidRegistrationId', 'InvalidStorageRootKey', - 'InvalidEnrollmentGroupId', 'TooManyEnrollments', - 'RegistrationIdDefinedMultipleTimes', 'CustomAllocationFailed', - 'CustomAllocationIotHubNotSpecified', - 'CustomAllocationUnauthorizedAccess', 'CannotRegisterModuleToModule', - 'TenantHubRoutingNotEnabled', 'InvalidConfigurationTargetCondition', - 'InvalidConfigurationContent', - 'CannotModifyImmutableConfigurationContent', - 'InvalidConfigurationCustomMetricsQuery', 'InvalidPnPInterfaceDefinition', - 'InvalidPnPDesiredProperties', 'InvalidPnPReportedProperties', - 'InvalidPnPWritableReportedProperties', 'InvalidDigitalTwinJsonPatch', - 'InvalidDigitalTwinPayload', 'InvalidDigitalTwinPatch', - 'InvalidDigitalTwinPatchPath', 'GenericUnauthorized', 'IotHubNotFound', - 'IotHubUnauthorizedAccess', 'IotHubUnauthorized', 'ElasticPoolNotFound', - 'SystemModuleModifyUnauthorizedAccess', 'GenericForbidden', - 'IotHubSuspended', 'IotHubQuotaExceeded', 'JobQuotaExceeded', - 'DeviceMaximumQueueDepthExceeded', 'IotHubMaxCbsTokenExceeded', - 'DeviceMaximumActiveFileUploadLimitExceeded', - 'DeviceMaximumQueueSizeExceeded', 'RoutingEndpointResponseForbidden', - 'InvalidMessageExpiryTime', 'OperationNotAvailableInCurrentTier', - 'KeyEncryptionKeyRevoked', 'DeviceModelMaxPropertiesExceeded', - 'DeviceModelMaxIndexablePropertiesExceeded', 'IotDpsSuspended', - 'IotDpsSuspending', 'GenericNotFound', 'DeviceNotFound', 'JobNotFound', - 'QuotaMetricNotFound', 'SystemPropertyNotFound', 'AmqpAddressNotFound', - 'RoutingEndpointResponseNotFound', 'CertificateNotFound', - 'ElasticPoolTenantHubNotFound', 'ModuleNotFound', - 'AzureTableStoreNotFound', 'IotHubFailingOver', 'FeatureNotSupported', - 'DigitalTwinInterfaceNotFound', 'QueryStoreClusterNotFound', - 'DeviceNotOnline', 'DeviceConnectionClosedRemotely', 'EnrollmentNotFound', - 'DeviceRegistrationNotFound', 'AsyncOperationNotFound', - 'EnrollmentGroupNotFound', 'DeviceRecordNotFound', 'GroupRecordNotFound', - 'DeviceGroupNotFound', 'ProvisioningSettingsNotFound', - 'ProvisioningRecordNotFound', 'LinkedHubNotFound', - 'CertificateAuthorityNotFound', 'ConfigurationNotFound', 'GroupNotFound', - 'DigitalTwinModelNotFound', 'InterfaceNameModelNotFound', - 'GenericMethodNotAllowed', 'OperationNotAllowedInCurrentState', - 'ImportDevicesNotSupported', 'BulkAddDevicesNotSupported', - 'GenericConflict', 'DeviceAlreadyExists', 'LinkCreationConflict', - 'CallbackSubscriptionConflict', 'ModelAlreadyExists', 'DeviceLocked', - 'DeviceJobAlreadyExists', 'JobAlreadyExists', 'EnrollmentConflict', - 'EnrollmentGroupConflict', 'RegistrationStatusConflict', - 'DeviceRecordConflict', 'GroupRecordConflict', 'DeviceGroupConflict', - 'ProvisioningSettingsConflict', 'ProvisioningRecordConflict', - 'LinkedHubConflict', 'CertificateAuthorityConflict', - 'ModuleAlreadyExistsOnDevice', 'ConfigurationAlreadyExists', - 'ApplyConfigurationAlreadyInProgressOnDevice', - 'DigitalTwinModelAlreadyExists', - 'DigitalTwinModelExistsWithOtherModelType', - 'InterfaceNameModelAlreadyExists', 'GenericPreconditionFailed', - 'PreconditionFailed', 'DeviceMessageLockLost', 'JobRunPreconditionFailed', - 'InflightMessagesInLink', 'GenericRequestEntityTooLarge', - 'MessageTooLarge', 'TooManyDevices', 'TooManyModulesOnDevice', - 'ConfigurationCountLimitExceeded', 'DigitalTwinModelCountLimitExceeded', - 'InterfaceNameCompressionModelCountLimitExceeded', - 'GenericUnsupportedMediaType', 'IncompatibleDataType', - 'GenericTooManyRequests', 'ThrottlingException', - 'ThrottleBacklogLimitExceeded', 'ThrottlingBacklogTimeout', - 'ThrottlingMaxActiveJobCountExceeded', 'DeviceThrottlingLimitExceeded', - 'ClientClosedRequest', 'GenericServerError', 'ServerError', - 'JobCancelled', 'StatisticsRetrievalError', 'ConnectionForcefullyClosed', - 'InvalidBlobState', 'BackupTimedOut', 'AzureStorageTimeout', - 'GenericTimeout', 'InvalidThrottleParameter', 'EventHubLinkAlreadyClosed', - 'ReliableBlobStoreError', 'RetryAttemptsExhausted', - 'AzureTableStoreError', 'CheckpointStoreNotFound', - 'DocumentDbInvalidReturnValue', 'ReliableDocDbStoreStoreError', - 'ReliableBlobStoreTimeoutError', 'ConfigReadFailed', - 'InvalidContainerReceiveLink', 'InvalidPartitionEpoch', 'RestoreTimedOut', - 'StreamReservationFailure', 'SerializationError', - 'UnexpectedPropertyValue', 'OrchestrationOperationFailed', - 'ModelRepoEndpointError', 'ResolutionError', 'UnableToFetchCredentials', - 'UnableToFetchTenantInfo', 'UnableToShareIdentity', - 'UnableToExpandDiscoveryInfo', 'UnableToExpandComponentInfo', - 'UnableToCompressComponentInfo', 'UnableToCompressDiscoveryInfo', - 'OrphanDiscoveryDocument', 'GenericBadGateway', - 'InvalidResponseWhileProxying', 'GenericServiceUnavailable', - 'ServiceUnavailable', 'PartitionNotFound', 'IotHubActivationFailed', - 'ServerBusy', 'IotHubRestoring', 'ReceiveLinkOpensThrottled', - 'ConnectionUnavailable', 'DeviceUnavailable', 'ConfigurationNotAvailable', - 'GroupNotAvailable', 'HostingServiceNotAvailable', - 'GenericGatewayTimeout', 'GatewayTimeout' - :type error_code: str or ~protocol.models.enum - :param error_status: The details of the error. - :type error_status: str - :param module_id: The unique identifier of the module, if applicable. - :type module_id: str - :param operation: The type of the operation that failed. - :type operation: str - """ - - _attribute_map = { - "device_id": {"key": "deviceId", "type": "str"}, - "error_code": {"key": "errorCode", "type": "str"}, - "error_status": {"key": "errorStatus", "type": "str"}, - "module_id": {"key": "moduleId", "type": "str"}, - "operation": {"key": "operation", "type": "str"}, - } - - def __init__( - self, - *, - device_id: str = None, - error_code=None, - error_status: str = None, - module_id: str = None, - operation: str = None, - **kwargs - ) -> None: - super(DeviceRegistryOperationError, self).__init__(**kwargs) - self.device_id = device_id - self.error_code = error_code - self.error_status = error_status - self.module_id = module_id - self.operation = operation diff --git a/src/azure/iot/hub/protocol/models/device_registry_operation_warning.py b/src/azure/iot/hub/protocol/models/device_registry_operation_warning.py deleted file mode 100644 index 3206936..0000000 --- a/src/azure/iot/hub/protocol/models/device_registry_operation_warning.py +++ /dev/null @@ -1,33 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is -# regenerated. -# -------------------------------------------------------------------------- - -from msrest.serialization import Model - - -class DeviceRegistryOperationWarning(Model): - """The device registry operation warning details. - - :param device_id: The unique identifier of the device. - :type device_id: str - :param warning_code: The warning code. Possible values include: - 'DeviceRegisteredWithoutTwin' - :type warning_code: str or ~protocol.models.enum - :param warning_status: The details of the warning. - :type warning_status: str - """ - - _attribute_map = { - "device_id": {"key": "deviceId", "type": "str"}, - "warning_code": {"key": "warningCode", "type": "str"}, - "warning_status": {"key": "warningStatus", "type": "str"}, - } - - def __init__(self, **kwargs): - super(DeviceRegistryOperationWarning, self).__init__(**kwargs) - self.device_id = kwargs.get("device_id", None) - self.warning_code = kwargs.get("warning_code", None) - self.warning_status = kwargs.get("warning_status", None) diff --git a/src/azure/iot/hub/protocol/models/device_registry_operation_warning_py3.py b/src/azure/iot/hub/protocol/models/device_registry_operation_warning_py3.py deleted file mode 100644 index 9e3075d..0000000 --- a/src/azure/iot/hub/protocol/models/device_registry_operation_warning_py3.py +++ /dev/null @@ -1,35 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is -# regenerated. -# -------------------------------------------------------------------------- - -from msrest.serialization import Model - - -class DeviceRegistryOperationWarning(Model): - """The device registry operation warning details. - - :param device_id: The unique identifier of the device. - :type device_id: str - :param warning_code: The warning code. Possible values include: - 'DeviceRegisteredWithoutTwin' - :type warning_code: str or ~protocol.models.enum - :param warning_status: The details of the warning. - :type warning_status: str - """ - - _attribute_map = { - "device_id": {"key": "deviceId", "type": "str"}, - "warning_code": {"key": "warningCode", "type": "str"}, - "warning_status": {"key": "warningStatus", "type": "str"}, - } - - def __init__( - self, *, device_id: str = None, warning_code=None, warning_status: str = None, **kwargs - ) -> None: - super(DeviceRegistryOperationWarning, self).__init__(**kwargs) - self.device_id = device_id - self.warning_code = warning_code - self.warning_status = warning_status diff --git a/src/azure/iot/hub/protocol/models/export_import_device.py b/src/azure/iot/hub/protocol/models/export_import_device.py deleted file mode 100644 index acb3f8e..0000000 --- a/src/azure/iot/hub/protocol/models/export_import_device.py +++ /dev/null @@ -1,86 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is -# regenerated. -# -------------------------------------------------------------------------- - -from msrest.serialization import Model - - -class ExportImportDevice(Model): - """ExportImportDevice. - - :param id: The unique identifier of the device. - :type id: str - :param module_id: The unique identifier of the module, if applicable. - :type module_id: str - :param e_tag: The string representing a weak ETag for the device RFC7232. - The value is only used if import mode is updateIfMatchETag, in that case - the import operation is performed only if this ETag matches the value - maintained by the server. - :type e_tag: str - :param import_mode: The type of registry operation and ETag preferences. - Possible values include: 'create', 'update', 'updateIfMatchETag', - 'delete', 'deleteIfMatchETag', 'updateTwin', 'updateTwinIfMatchETag' - :type import_mode: str or ~protocol.models.enum - :param status: The status of the module. If disabled, the module cannot - connect to the service. Possible values include: 'enabled', 'disabled' - :type status: str or ~protocol.models.enum - :param status_reason: The 128 character-long string that stores the reason - for the device identity status. All UTF-8 characters are allowed. - :type status_reason: str - :param authentication: The authentication mechanism used by the module. - This parameter is optional and defaults to SAS if not provided. In that - case, primary/secondary access keys are auto-generated. - :type authentication: ~protocol.models.AuthenticationMechanism - :param twin_etag: The string representing a weak ETag for the device twin - RFC7232. The value is only used if import mode is updateIfMatchETag, in - that case the import operation is performed only if this ETag matches the - value maintained by the server. - :type twin_etag: str - :param tags: The JSON document read and written by the solution back end. - The tags are not visible to device apps. - :type tags: dict[str, object] - :param properties: The desired and reported properties for the device. - :type properties: ~protocol.models.PropertyContainer - :param capabilities: The status of capabilities enabled on the device. - :type capabilities: ~protocol.models.DeviceCapabilities - :param device_scope: The scope of the device. - :type device_scope: str - :param parent_scopes: The scopes of the upper level edge devices if - applicable. Only available for edge devices. - :type parent_scopes: list[str] - """ - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "module_id": {"key": "moduleId", "type": "str"}, - "e_tag": {"key": "eTag", "type": "str"}, - "import_mode": {"key": "importMode", "type": "str"}, - "status": {"key": "status", "type": "str"}, - "status_reason": {"key": "statusReason", "type": "str"}, - "authentication": {"key": "authentication", "type": "AuthenticationMechanism"}, - "twin_etag": {"key": "twinETag", "type": "str"}, - "tags": {"key": "tags", "type": "{object}"}, - "properties": {"key": "properties", "type": "PropertyContainer"}, - "capabilities": {"key": "capabilities", "type": "DeviceCapabilities"}, - "device_scope": {"key": "deviceScope", "type": "str"}, - "parent_scopes": {"key": "parentScopes", "type": "[str]"}, - } - - def __init__(self, **kwargs): - super(ExportImportDevice, self).__init__(**kwargs) - self.id = kwargs.get("id", None) - self.module_id = kwargs.get("module_id", None) - self.e_tag = kwargs.get("e_tag", None) - self.import_mode = kwargs.get("import_mode", None) - self.status = kwargs.get("status", None) - self.status_reason = kwargs.get("status_reason", None) - self.authentication = kwargs.get("authentication", None) - self.twin_etag = kwargs.get("twin_etag", None) - self.tags = kwargs.get("tags", None) - self.properties = kwargs.get("properties", None) - self.capabilities = kwargs.get("capabilities", None) - self.device_scope = kwargs.get("device_scope", None) - self.parent_scopes = kwargs.get("parent_scopes", None) diff --git a/src/azure/iot/hub/protocol/models/export_import_device_py3.py b/src/azure/iot/hub/protocol/models/export_import_device_py3.py deleted file mode 100644 index c3d4c0b..0000000 --- a/src/azure/iot/hub/protocol/models/export_import_device_py3.py +++ /dev/null @@ -1,103 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is -# regenerated. -# -------------------------------------------------------------------------- - -from msrest.serialization import Model - - -class ExportImportDevice(Model): - """ExportImportDevice. - - :param id: The unique identifier of the device. - :type id: str - :param module_id: The unique identifier of the module, if applicable. - :type module_id: str - :param e_tag: The string representing a weak ETag for the device RFC7232. - The value is only used if import mode is updateIfMatchETag, in that case - the import operation is performed only if this ETag matches the value - maintained by the server. - :type e_tag: str - :param import_mode: The type of registry operation and ETag preferences. - Possible values include: 'create', 'update', 'updateIfMatchETag', - 'delete', 'deleteIfMatchETag', 'updateTwin', 'updateTwinIfMatchETag' - :type import_mode: str or ~protocol.models.enum - :param status: The status of the module. If disabled, the module cannot - connect to the service. Possible values include: 'enabled', 'disabled' - :type status: str or ~protocol.models.enum - :param status_reason: The 128 character-long string that stores the reason - for the device identity status. All UTF-8 characters are allowed. - :type status_reason: str - :param authentication: The authentication mechanism used by the module. - This parameter is optional and defaults to SAS if not provided. In that - case, primary/secondary access keys are auto-generated. - :type authentication: ~protocol.models.AuthenticationMechanism - :param twin_etag: The string representing a weak ETag for the device twin - RFC7232. The value is only used if import mode is updateIfMatchETag, in - that case the import operation is performed only if this ETag matches the - value maintained by the server. - :type twin_etag: str - :param tags: The JSON document read and written by the solution back end. - The tags are not visible to device apps. - :type tags: dict[str, object] - :param properties: The desired and reported properties for the device. - :type properties: ~protocol.models.PropertyContainer - :param capabilities: The status of capabilities enabled on the device. - :type capabilities: ~protocol.models.DeviceCapabilities - :param device_scope: The scope of the device. - :type device_scope: str - :param parent_scopes: The scopes of the upper level edge devices if - applicable. Only available for edge devices. - :type parent_scopes: list[str] - """ - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "module_id": {"key": "moduleId", "type": "str"}, - "e_tag": {"key": "eTag", "type": "str"}, - "import_mode": {"key": "importMode", "type": "str"}, - "status": {"key": "status", "type": "str"}, - "status_reason": {"key": "statusReason", "type": "str"}, - "authentication": {"key": "authentication", "type": "AuthenticationMechanism"}, - "twin_etag": {"key": "twinETag", "type": "str"}, - "tags": {"key": "tags", "type": "{object}"}, - "properties": {"key": "properties", "type": "PropertyContainer"}, - "capabilities": {"key": "capabilities", "type": "DeviceCapabilities"}, - "device_scope": {"key": "deviceScope", "type": "str"}, - "parent_scopes": {"key": "parentScopes", "type": "[str]"}, - } - - def __init__( - self, - *, - id: str = None, - module_id: str = None, - e_tag: str = None, - import_mode=None, - status=None, - status_reason: str = None, - authentication=None, - twin_etag: str = None, - tags=None, - properties=None, - capabilities=None, - device_scope: str = None, - parent_scopes=None, - **kwargs - ) -> None: - super(ExportImportDevice, self).__init__(**kwargs) - self.id = id - self.module_id = module_id - self.e_tag = e_tag - self.import_mode = import_mode - self.status = status - self.status_reason = status_reason - self.authentication = authentication - self.twin_etag = twin_etag - self.tags = tags - self.properties = properties - self.capabilities = capabilities - self.device_scope = device_scope - self.parent_scopes = parent_scopes diff --git a/src/azure/iot/hub/protocol/models/job_properties.py b/src/azure/iot/hub/protocol/models/job_properties.py deleted file mode 100644 index 04dd2d2..0000000 --- a/src/azure/iot/hub/protocol/models/job_properties.py +++ /dev/null @@ -1,106 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is -# regenerated. -# -------------------------------------------------------------------------- - -from msrest.serialization import Model - - -class JobProperties(Model): - """JobProperties. - - :param job_id: The unique identifier of the job. - :type job_id: str - :param start_time_utc: System generated. Ignored at creation. The start - date and time of the job in UTC. - :type start_time_utc: datetime - :param end_time_utc: System generated. Ignored at creation. The end date - and time of the job in UTC. - :type end_time_utc: datetime - :param type: The job type. Possible values include: 'unknown', 'export', - 'import', 'backup', 'readDeviceProperties', 'writeDeviceProperties', - 'updateDeviceConfiguration', 'rebootDevice', 'factoryResetDevice', - 'firmwareUpdate', 'scheduleDeviceMethod', 'scheduleUpdateTwin', - 'restoreFromBackup', 'failoverDataCopy' - :type type: str or ~protocol.models.enum - :param status: System generated. Ignored at creation. The status of the - job. Possible values include: 'unknown', 'enqueued', 'running', - 'completed', 'failed', 'cancelled', 'scheduled', 'queued' - :type status: str or ~protocol.models.enum - :param progress: System generated. Ignored at creation. The percentage of - job completion. - :type progress: int - :param input_blob_container_uri: The URI containing SAS token to a blob - container that contains registry data to sync. - :type input_blob_container_uri: str - :param input_blob_name: The blob name to use when importing from the input - blob container. - :type input_blob_name: str - :param output_blob_container_uri: The SAS token to access the blob - container. This is used to output the status and results of the job. - :type output_blob_container_uri: str - :param output_blob_name: The blob name that will be created in the output - blob container. This blob will contain the exported device registry - information for the IoT Hub. - :type output_blob_name: str - :param exclude_keys_in_export: Optional for export jobs; ignored for other - jobs. If not specified, the service defaults to false. If false, - authorization keys are included in export output. Keys are exported as - null otherwise. - :type exclude_keys_in_export: bool - :param storage_authentication_type: The authentication type used for - connecting to the storage account. Possible values include: 'keyBased', - 'identityBased' - :type storage_authentication_type: str or ~protocol.models.enum - :param identity: - :type identity: ~protocol.models.ManagedIdentity - :param failure_reason: System genereated. Ignored at creation. The reason - for failure, if a failure occurred. - :type failure_reason: str - :param include_configurations: Defaults to false. If true, then - configurations are included in the data export/import. - :type include_configurations: bool - :param configurations_blob_name: Defaults to configurations.txt. Specifies - the name of the blob to use when exporting/importing configurations. - :type configurations_blob_name: str - """ - - _attribute_map = { - "job_id": {"key": "jobId", "type": "str"}, - "start_time_utc": {"key": "startTimeUtc", "type": "iso-8601"}, - "end_time_utc": {"key": "endTimeUtc", "type": "iso-8601"}, - "type": {"key": "type", "type": "str"}, - "status": {"key": "status", "type": "str"}, - "progress": {"key": "progress", "type": "int"}, - "input_blob_container_uri": {"key": "inputBlobContainerUri", "type": "str"}, - "input_blob_name": {"key": "inputBlobName", "type": "str"}, - "output_blob_container_uri": {"key": "outputBlobContainerUri", "type": "str"}, - "output_blob_name": {"key": "outputBlobName", "type": "str"}, - "exclude_keys_in_export": {"key": "excludeKeysInExport", "type": "bool"}, - "storage_authentication_type": {"key": "storageAuthenticationType", "type": "str"}, - "identity": {"key": "identity", "type": "ManagedIdentity"}, - "failure_reason": {"key": "failureReason", "type": "str"}, - "include_configurations": {"key": "includeConfigurations", "type": "bool"}, - "configurations_blob_name": {"key": "configurationsBlobName", "type": "str"}, - } - - def __init__(self, **kwargs): - super(JobProperties, self).__init__(**kwargs) - self.job_id = kwargs.get("job_id", None) - self.start_time_utc = kwargs.get("start_time_utc", None) - self.end_time_utc = kwargs.get("end_time_utc", None) - self.type = kwargs.get("type", None) - self.status = kwargs.get("status", None) - self.progress = kwargs.get("progress", None) - self.input_blob_container_uri = kwargs.get("input_blob_container_uri", None) - self.input_blob_name = kwargs.get("input_blob_name", None) - self.output_blob_container_uri = kwargs.get("output_blob_container_uri", None) - self.output_blob_name = kwargs.get("output_blob_name", None) - self.exclude_keys_in_export = kwargs.get("exclude_keys_in_export", None) - self.storage_authentication_type = kwargs.get("storage_authentication_type", None) - self.identity = kwargs.get("identity", None) - self.failure_reason = kwargs.get("failure_reason", None) - self.include_configurations = kwargs.get("include_configurations", None) - self.configurations_blob_name = kwargs.get("configurations_blob_name", None) diff --git a/src/azure/iot/hub/protocol/models/job_properties_py3.py b/src/azure/iot/hub/protocol/models/job_properties_py3.py deleted file mode 100644 index 08d3324..0000000 --- a/src/azure/iot/hub/protocol/models/job_properties_py3.py +++ /dev/null @@ -1,126 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is -# regenerated. -# -------------------------------------------------------------------------- - -from msrest.serialization import Model - - -class JobProperties(Model): - """JobProperties. - - :param job_id: The unique identifier of the job. - :type job_id: str - :param start_time_utc: System generated. Ignored at creation. The start - date and time of the job in UTC. - :type start_time_utc: datetime - :param end_time_utc: System generated. Ignored at creation. The end date - and time of the job in UTC. - :type end_time_utc: datetime - :param type: The job type. Possible values include: 'unknown', 'export', - 'import', 'backup', 'readDeviceProperties', 'writeDeviceProperties', - 'updateDeviceConfiguration', 'rebootDevice', 'factoryResetDevice', - 'firmwareUpdate', 'scheduleDeviceMethod', 'scheduleUpdateTwin', - 'restoreFromBackup', 'failoverDataCopy' - :type type: str or ~protocol.models.enum - :param status: System generated. Ignored at creation. The status of the - job. Possible values include: 'unknown', 'enqueued', 'running', - 'completed', 'failed', 'cancelled', 'scheduled', 'queued' - :type status: str or ~protocol.models.enum - :param progress: System generated. Ignored at creation. The percentage of - job completion. - :type progress: int - :param input_blob_container_uri: The URI containing SAS token to a blob - container that contains registry data to sync. - :type input_blob_container_uri: str - :param input_blob_name: The blob name to use when importing from the input - blob container. - :type input_blob_name: str - :param output_blob_container_uri: The SAS token to access the blob - container. This is used to output the status and results of the job. - :type output_blob_container_uri: str - :param output_blob_name: The blob name that will be created in the output - blob container. This blob will contain the exported device registry - information for the IoT Hub. - :type output_blob_name: str - :param exclude_keys_in_export: Optional for export jobs; ignored for other - jobs. If not specified, the service defaults to false. If false, - authorization keys are included in export output. Keys are exported as - null otherwise. - :type exclude_keys_in_export: bool - :param storage_authentication_type: The authentication type used for - connecting to the storage account. Possible values include: 'keyBased', - 'identityBased' - :type storage_authentication_type: str or ~protocol.models.enum - :param identity: - :type identity: ~protocol.models.ManagedIdentity - :param failure_reason: System genereated. Ignored at creation. The reason - for failure, if a failure occurred. - :type failure_reason: str - :param include_configurations: Defaults to false. If true, then - configurations are included in the data export/import. - :type include_configurations: bool - :param configurations_blob_name: Defaults to configurations.txt. Specifies - the name of the blob to use when exporting/importing configurations. - :type configurations_blob_name: str - """ - - _attribute_map = { - "job_id": {"key": "jobId", "type": "str"}, - "start_time_utc": {"key": "startTimeUtc", "type": "iso-8601"}, - "end_time_utc": {"key": "endTimeUtc", "type": "iso-8601"}, - "type": {"key": "type", "type": "str"}, - "status": {"key": "status", "type": "str"}, - "progress": {"key": "progress", "type": "int"}, - "input_blob_container_uri": {"key": "inputBlobContainerUri", "type": "str"}, - "input_blob_name": {"key": "inputBlobName", "type": "str"}, - "output_blob_container_uri": {"key": "outputBlobContainerUri", "type": "str"}, - "output_blob_name": {"key": "outputBlobName", "type": "str"}, - "exclude_keys_in_export": {"key": "excludeKeysInExport", "type": "bool"}, - "storage_authentication_type": {"key": "storageAuthenticationType", "type": "str"}, - "identity": {"key": "identity", "type": "ManagedIdentity"}, - "failure_reason": {"key": "failureReason", "type": "str"}, - "include_configurations": {"key": "includeConfigurations", "type": "bool"}, - "configurations_blob_name": {"key": "configurationsBlobName", "type": "str"}, - } - - def __init__( - self, - *, - job_id: str = None, - start_time_utc=None, - end_time_utc=None, - type=None, - status=None, - progress: int = None, - input_blob_container_uri: str = None, - input_blob_name: str = None, - output_blob_container_uri: str = None, - output_blob_name: str = None, - exclude_keys_in_export: bool = None, - storage_authentication_type=None, - identity=None, - failure_reason: str = None, - include_configurations: bool = None, - configurations_blob_name: str = None, - **kwargs - ) -> None: - super(JobProperties, self).__init__(**kwargs) - self.job_id = job_id - self.start_time_utc = start_time_utc - self.end_time_utc = end_time_utc - self.type = type - self.status = status - self.progress = progress - self.input_blob_container_uri = input_blob_container_uri - self.input_blob_name = input_blob_name - self.output_blob_container_uri = output_blob_container_uri - self.output_blob_name = output_blob_name - self.exclude_keys_in_export = exclude_keys_in_export - self.storage_authentication_type = storage_authentication_type - self.identity = identity - self.failure_reason = failure_reason - self.include_configurations = include_configurations - self.configurations_blob_name = configurations_blob_name diff --git a/src/azure/iot/hub/protocol/models/job_request.py b/src/azure/iot/hub/protocol/models/job_request.py deleted file mode 100644 index 6e60148..0000000 --- a/src/azure/iot/hub/protocol/models/job_request.py +++ /dev/null @@ -1,56 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is -# regenerated. -# -------------------------------------------------------------------------- - -from msrest.serialization import Model - - -class JobRequest(Model): - """JobRequest. - - :param job_id: The unique identifier of the job. - :type job_id: str - :param type: The job type. Possible values include: 'unknown', 'export', - 'import', 'backup', 'readDeviceProperties', 'writeDeviceProperties', - 'updateDeviceConfiguration', 'rebootDevice', 'factoryResetDevice', - 'firmwareUpdate', 'scheduleDeviceMethod', 'scheduleUpdateTwin', - 'restoreFromBackup', 'failoverDataCopy' - :type type: str or ~protocol.models.enum - :param cloud_to_device_method: The method type and parameters. This is - required if the job type is cloudToDeviceMethod. - :type cloud_to_device_method: ~protocol.models.CloudToDeviceMethod - :param update_twin: - :type update_twin: ~protocol.models.Twin - :param query_condition: The condition for devices to execute the job. This - is required if the job type is updateTwin or cloudToDeviceMethod. - :type query_condition: str - :param start_time: The start date and time of the job in ISO 8601 - standard. - :type start_time: datetime - :param max_execution_time_in_seconds: The maximum execution time in - secounds. - :type max_execution_time_in_seconds: long - """ - - _attribute_map = { - "job_id": {"key": "jobId", "type": "str"}, - "type": {"key": "type", "type": "str"}, - "cloud_to_device_method": {"key": "cloudToDeviceMethod", "type": "CloudToDeviceMethod"}, - "update_twin": {"key": "updateTwin", "type": "Twin"}, - "query_condition": {"key": "queryCondition", "type": "str"}, - "start_time": {"key": "startTime", "type": "iso-8601"}, - "max_execution_time_in_seconds": {"key": "maxExecutionTimeInSeconds", "type": "long"}, - } - - def __init__(self, **kwargs): - super(JobRequest, self).__init__(**kwargs) - self.job_id = kwargs.get("job_id", None) - self.type = kwargs.get("type", None) - self.cloud_to_device_method = kwargs.get("cloud_to_device_method", None) - self.update_twin = kwargs.get("update_twin", None) - self.query_condition = kwargs.get("query_condition", None) - self.start_time = kwargs.get("start_time", None) - self.max_execution_time_in_seconds = kwargs.get("max_execution_time_in_seconds", None) diff --git a/src/azure/iot/hub/protocol/models/job_request_py3.py b/src/azure/iot/hub/protocol/models/job_request_py3.py deleted file mode 100644 index c59246d..0000000 --- a/src/azure/iot/hub/protocol/models/job_request_py3.py +++ /dev/null @@ -1,67 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is -# regenerated. -# -------------------------------------------------------------------------- - -from msrest.serialization import Model - - -class JobRequest(Model): - """JobRequest. - - :param job_id: The unique identifier of the job. - :type job_id: str - :param type: The job type. Possible values include: 'unknown', 'export', - 'import', 'backup', 'readDeviceProperties', 'writeDeviceProperties', - 'updateDeviceConfiguration', 'rebootDevice', 'factoryResetDevice', - 'firmwareUpdate', 'scheduleDeviceMethod', 'scheduleUpdateTwin', - 'restoreFromBackup', 'failoverDataCopy' - :type type: str or ~protocol.models.enum - :param cloud_to_device_method: The method type and parameters. This is - required if the job type is cloudToDeviceMethod. - :type cloud_to_device_method: ~protocol.models.CloudToDeviceMethod - :param update_twin: - :type update_twin: ~protocol.models.Twin - :param query_condition: The condition for devices to execute the job. This - is required if the job type is updateTwin or cloudToDeviceMethod. - :type query_condition: str - :param start_time: The start date and time of the job in ISO 8601 - standard. - :type start_time: datetime - :param max_execution_time_in_seconds: The maximum execution time in - secounds. - :type max_execution_time_in_seconds: long - """ - - _attribute_map = { - "job_id": {"key": "jobId", "type": "str"}, - "type": {"key": "type", "type": "str"}, - "cloud_to_device_method": {"key": "cloudToDeviceMethod", "type": "CloudToDeviceMethod"}, - "update_twin": {"key": "updateTwin", "type": "Twin"}, - "query_condition": {"key": "queryCondition", "type": "str"}, - "start_time": {"key": "startTime", "type": "iso-8601"}, - "max_execution_time_in_seconds": {"key": "maxExecutionTimeInSeconds", "type": "long"}, - } - - def __init__( - self, - *, - job_id: str = None, - type=None, - cloud_to_device_method=None, - update_twin=None, - query_condition: str = None, - start_time=None, - max_execution_time_in_seconds: int = None, - **kwargs - ) -> None: - super(JobRequest, self).__init__(**kwargs) - self.job_id = job_id - self.type = type - self.cloud_to_device_method = cloud_to_device_method - self.update_twin = update_twin - self.query_condition = query_condition - self.start_time = start_time - self.max_execution_time_in_seconds = max_execution_time_in_seconds diff --git a/src/azure/iot/hub/protocol/models/job_response.py b/src/azure/iot/hub/protocol/models/job_response.py deleted file mode 100644 index b6c7985..0000000 --- a/src/azure/iot/hub/protocol/models/job_response.py +++ /dev/null @@ -1,83 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is -# regenerated. -# -------------------------------------------------------------------------- - -from msrest.serialization import Model - - -class JobResponse(Model): - """JobResponse. - - :param job_id: System generated. Ignored at creation. The unique - identifier of the job. - :type job_id: str - :param query_condition: The device query condition. - :type query_condition: str - :param created_time: System generated. Ignored at creation. The creation - date and time of the job. - :type created_time: datetime - :param start_time: The start date and time of the scheduled job in UTC. - :type start_time: datetime - :param end_time: System generated. Ignored at creation. The end date and - time of the job in UTC. - :type end_time: datetime - :param max_execution_time_in_seconds: The maximum execution time in - secounds. - :type max_execution_time_in_seconds: long - :param type: The job type. Possible values include: 'unknown', 'export', - 'import', 'backup', 'readDeviceProperties', 'writeDeviceProperties', - 'updateDeviceConfiguration', 'rebootDevice', 'factoryResetDevice', - 'firmwareUpdate', 'scheduleDeviceMethod', 'scheduleUpdateTwin', - 'restoreFromBackup', 'failoverDataCopy' - :type type: str or ~protocol.models.enum - :param cloud_to_device_method: The method type and parameters. This is - required if job type is cloudToDeviceMethod. - :type cloud_to_device_method: ~protocol.models.CloudToDeviceMethod - :param update_twin: - :type update_twin: ~protocol.models.Twin - :param status: System generated. Ignored at creation. The status of the - job. Possible values include: 'unknown', 'enqueued', 'running', - 'completed', 'failed', 'cancelled', 'scheduled', 'queued' - :type status: str or ~protocol.models.enum - :param failure_reason: The reason for the failure, if a failure occurred. - :type failure_reason: str - :param status_message: The status message of the job. - :type status_message: str - :param device_job_statistics: The details regarding job execution status. - :type device_job_statistics: ~protocol.models.DeviceJobStatistics - """ - - _attribute_map = { - "job_id": {"key": "jobId", "type": "str"}, - "query_condition": {"key": "queryCondition", "type": "str"}, - "created_time": {"key": "createdTime", "type": "iso-8601"}, - "start_time": {"key": "startTime", "type": "iso-8601"}, - "end_time": {"key": "endTime", "type": "iso-8601"}, - "max_execution_time_in_seconds": {"key": "maxExecutionTimeInSeconds", "type": "long"}, - "type": {"key": "type", "type": "str"}, - "cloud_to_device_method": {"key": "cloudToDeviceMethod", "type": "CloudToDeviceMethod"}, - "update_twin": {"key": "updateTwin", "type": "Twin"}, - "status": {"key": "status", "type": "str"}, - "failure_reason": {"key": "failureReason", "type": "str"}, - "status_message": {"key": "statusMessage", "type": "str"}, - "device_job_statistics": {"key": "deviceJobStatistics", "type": "DeviceJobStatistics"}, - } - - def __init__(self, **kwargs): - super(JobResponse, self).__init__(**kwargs) - self.job_id = kwargs.get("job_id", None) - self.query_condition = kwargs.get("query_condition", None) - self.created_time = kwargs.get("created_time", None) - self.start_time = kwargs.get("start_time", None) - self.end_time = kwargs.get("end_time", None) - self.max_execution_time_in_seconds = kwargs.get("max_execution_time_in_seconds", None) - self.type = kwargs.get("type", None) - self.cloud_to_device_method = kwargs.get("cloud_to_device_method", None) - self.update_twin = kwargs.get("update_twin", None) - self.status = kwargs.get("status", None) - self.failure_reason = kwargs.get("failure_reason", None) - self.status_message = kwargs.get("status_message", None) - self.device_job_statistics = kwargs.get("device_job_statistics", None) diff --git a/src/azure/iot/hub/protocol/models/job_response_py3.py b/src/azure/iot/hub/protocol/models/job_response_py3.py deleted file mode 100644 index 41637e7..0000000 --- a/src/azure/iot/hub/protocol/models/job_response_py3.py +++ /dev/null @@ -1,100 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is -# regenerated. -# -------------------------------------------------------------------------- - -from msrest.serialization import Model - - -class JobResponse(Model): - """JobResponse. - - :param job_id: System generated. Ignored at creation. The unique - identifier of the job. - :type job_id: str - :param query_condition: The device query condition. - :type query_condition: str - :param created_time: System generated. Ignored at creation. The creation - date and time of the job. - :type created_time: datetime - :param start_time: The start date and time of the scheduled job in UTC. - :type start_time: datetime - :param end_time: System generated. Ignored at creation. The end date and - time of the job in UTC. - :type end_time: datetime - :param max_execution_time_in_seconds: The maximum execution time in - secounds. - :type max_execution_time_in_seconds: long - :param type: The job type. Possible values include: 'unknown', 'export', - 'import', 'backup', 'readDeviceProperties', 'writeDeviceProperties', - 'updateDeviceConfiguration', 'rebootDevice', 'factoryResetDevice', - 'firmwareUpdate', 'scheduleDeviceMethod', 'scheduleUpdateTwin', - 'restoreFromBackup', 'failoverDataCopy' - :type type: str or ~protocol.models.enum - :param cloud_to_device_method: The method type and parameters. This is - required if job type is cloudToDeviceMethod. - :type cloud_to_device_method: ~protocol.models.CloudToDeviceMethod - :param update_twin: - :type update_twin: ~protocol.models.Twin - :param status: System generated. Ignored at creation. The status of the - job. Possible values include: 'unknown', 'enqueued', 'running', - 'completed', 'failed', 'cancelled', 'scheduled', 'queued' - :type status: str or ~protocol.models.enum - :param failure_reason: The reason for the failure, if a failure occurred. - :type failure_reason: str - :param status_message: The status message of the job. - :type status_message: str - :param device_job_statistics: The details regarding job execution status. - :type device_job_statistics: ~protocol.models.DeviceJobStatistics - """ - - _attribute_map = { - "job_id": {"key": "jobId", "type": "str"}, - "query_condition": {"key": "queryCondition", "type": "str"}, - "created_time": {"key": "createdTime", "type": "iso-8601"}, - "start_time": {"key": "startTime", "type": "iso-8601"}, - "end_time": {"key": "endTime", "type": "iso-8601"}, - "max_execution_time_in_seconds": {"key": "maxExecutionTimeInSeconds", "type": "long"}, - "type": {"key": "type", "type": "str"}, - "cloud_to_device_method": {"key": "cloudToDeviceMethod", "type": "CloudToDeviceMethod"}, - "update_twin": {"key": "updateTwin", "type": "Twin"}, - "status": {"key": "status", "type": "str"}, - "failure_reason": {"key": "failureReason", "type": "str"}, - "status_message": {"key": "statusMessage", "type": "str"}, - "device_job_statistics": {"key": "deviceJobStatistics", "type": "DeviceJobStatistics"}, - } - - def __init__( - self, - *, - job_id: str = None, - query_condition: str = None, - created_time=None, - start_time=None, - end_time=None, - max_execution_time_in_seconds: int = None, - type=None, - cloud_to_device_method=None, - update_twin=None, - status=None, - failure_reason: str = None, - status_message: str = None, - device_job_statistics=None, - **kwargs - ) -> None: - super(JobResponse, self).__init__(**kwargs) - self.job_id = job_id - self.query_condition = query_condition - self.created_time = created_time - self.start_time = start_time - self.end_time = end_time - self.max_execution_time_in_seconds = max_execution_time_in_seconds - self.type = type - self.cloud_to_device_method = cloud_to_device_method - self.update_twin = update_twin - self.status = status - self.failure_reason = failure_reason - self.status_message = status_message - self.device_job_statistics = device_job_statistics diff --git a/src/azure/iot/hub/protocol/models/managed_identity.py b/src/azure/iot/hub/protocol/models/managed_identity.py deleted file mode 100644 index 09a596b..0000000 --- a/src/azure/iot/hub/protocol/models/managed_identity.py +++ /dev/null @@ -1,22 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is -# regenerated. -# -------------------------------------------------------------------------- - -from msrest.serialization import Model - - -class ManagedIdentity(Model): - """ManagedIdentity. - - :param user_assigned_identity: - :type user_assigned_identity: str - """ - - _attribute_map = {"user_assigned_identity": {"key": "userAssignedIdentity", "type": "str"}} - - def __init__(self, **kwargs): - super(ManagedIdentity, self).__init__(**kwargs) - self.user_assigned_identity = kwargs.get("user_assigned_identity", None) diff --git a/src/azure/iot/hub/protocol/models/managed_identity_py3.py b/src/azure/iot/hub/protocol/models/managed_identity_py3.py deleted file mode 100644 index 5225703..0000000 --- a/src/azure/iot/hub/protocol/models/managed_identity_py3.py +++ /dev/null @@ -1,22 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is -# regenerated. -# -------------------------------------------------------------------------- - -from msrest.serialization import Model - - -class ManagedIdentity(Model): - """ManagedIdentity. - - :param user_assigned_identity: - :type user_assigned_identity: str - """ - - _attribute_map = {"user_assigned_identity": {"key": "userAssignedIdentity", "type": "str"}} - - def __init__(self, *, user_assigned_identity: str = None, **kwargs) -> None: - super(ManagedIdentity, self).__init__(**kwargs) - self.user_assigned_identity = user_assigned_identity diff --git a/src/azure/iot/hub/protocol/models/module.py b/src/azure/iot/hub/protocol/models/module.py deleted file mode 100644 index 6e82982..0000000 --- a/src/azure/iot/hub/protocol/models/module.py +++ /dev/null @@ -1,69 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is -# regenerated. -# -------------------------------------------------------------------------- - -from msrest.serialization import Model - - -class Module(Model): - """The module identity on a device. - - :param module_id: The unique identifier of the module. - :type module_id: str - :param managed_by: Identifies who manages this module. For instance, this - value is \\"IotEdge\\" if the edge runtime owns this module. - :type managed_by: str - :param device_id: The unique identifier of the device. - :type device_id: str - :param generation_id: The IoT Hub generated, case-sensitive string up to - 128 characters long. This value is used to distinguish modules with the - same moduleId, when they have been deleted and re-created. - :type generation_id: str - :param etag: The string representing a weak ETag for the module identity, - as per RFC7232. - :type etag: str - :param connection_state: The connection state of the device. Possible - values include: 'Disconnected', 'Connected' - :type connection_state: str or ~protocol.models.enum - :param connection_state_updated_time: The date and time the connection - state was last updated. - :type connection_state_updated_time: datetime - :param last_activity_time: The date and time the device last connected, - received, or sent a message. - :type last_activity_time: datetime - :param cloud_to_device_message_count: The number of cloud-to-module - messages currently queued to be sent to the module. - :type cloud_to_device_message_count: int - :param authentication: The authentication mechanism used by the module - when connecting to the service and edge hub. - :type authentication: ~protocol.models.AuthenticationMechanism - """ - - _attribute_map = { - "module_id": {"key": "moduleId", "type": "str"}, - "managed_by": {"key": "managedBy", "type": "str"}, - "device_id": {"key": "deviceId", "type": "str"}, - "generation_id": {"key": "generationId", "type": "str"}, - "etag": {"key": "etag", "type": "str"}, - "connection_state": {"key": "connectionState", "type": "str"}, - "connection_state_updated_time": {"key": "connectionStateUpdatedTime", "type": "iso-8601"}, - "last_activity_time": {"key": "lastActivityTime", "type": "iso-8601"}, - "cloud_to_device_message_count": {"key": "cloudToDeviceMessageCount", "type": "int"}, - "authentication": {"key": "authentication", "type": "AuthenticationMechanism"}, - } - - def __init__(self, **kwargs): - super(Module, self).__init__(**kwargs) - self.module_id = kwargs.get("module_id", None) - self.managed_by = kwargs.get("managed_by", None) - self.device_id = kwargs.get("device_id", None) - self.generation_id = kwargs.get("generation_id", None) - self.etag = kwargs.get("etag", None) - self.connection_state = kwargs.get("connection_state", None) - self.connection_state_updated_time = kwargs.get("connection_state_updated_time", None) - self.last_activity_time = kwargs.get("last_activity_time", None) - self.cloud_to_device_message_count = kwargs.get("cloud_to_device_message_count", None) - self.authentication = kwargs.get("authentication", None) diff --git a/src/azure/iot/hub/protocol/models/module_py3.py b/src/azure/iot/hub/protocol/models/module_py3.py deleted file mode 100644 index 502fb4c..0000000 --- a/src/azure/iot/hub/protocol/models/module_py3.py +++ /dev/null @@ -1,83 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is -# regenerated. -# -------------------------------------------------------------------------- - -from msrest.serialization import Model - - -class Module(Model): - """The module identity on a device. - - :param module_id: The unique identifier of the module. - :type module_id: str - :param managed_by: Identifies who manages this module. For instance, this - value is \\"IotEdge\\" if the edge runtime owns this module. - :type managed_by: str - :param device_id: The unique identifier of the device. - :type device_id: str - :param generation_id: The IoT Hub generated, case-sensitive string up to - 128 characters long. This value is used to distinguish modules with the - same moduleId, when they have been deleted and re-created. - :type generation_id: str - :param etag: The string representing a weak ETag for the module identity, - as per RFC7232. - :type etag: str - :param connection_state: The connection state of the device. Possible - values include: 'Disconnected', 'Connected' - :type connection_state: str or ~protocol.models.enum - :param connection_state_updated_time: The date and time the connection - state was last updated. - :type connection_state_updated_time: datetime - :param last_activity_time: The date and time the device last connected, - received, or sent a message. - :type last_activity_time: datetime - :param cloud_to_device_message_count: The number of cloud-to-module - messages currently queued to be sent to the module. - :type cloud_to_device_message_count: int - :param authentication: The authentication mechanism used by the module - when connecting to the service and edge hub. - :type authentication: ~protocol.models.AuthenticationMechanism - """ - - _attribute_map = { - "module_id": {"key": "moduleId", "type": "str"}, - "managed_by": {"key": "managedBy", "type": "str"}, - "device_id": {"key": "deviceId", "type": "str"}, - "generation_id": {"key": "generationId", "type": "str"}, - "etag": {"key": "etag", "type": "str"}, - "connection_state": {"key": "connectionState", "type": "str"}, - "connection_state_updated_time": {"key": "connectionStateUpdatedTime", "type": "iso-8601"}, - "last_activity_time": {"key": "lastActivityTime", "type": "iso-8601"}, - "cloud_to_device_message_count": {"key": "cloudToDeviceMessageCount", "type": "int"}, - "authentication": {"key": "authentication", "type": "AuthenticationMechanism"}, - } - - def __init__( - self, - *, - module_id: str = None, - managed_by: str = None, - device_id: str = None, - generation_id: str = None, - etag: str = None, - connection_state=None, - connection_state_updated_time=None, - last_activity_time=None, - cloud_to_device_message_count: int = None, - authentication=None, - **kwargs - ) -> None: - super(Module, self).__init__(**kwargs) - self.module_id = module_id - self.managed_by = managed_by - self.device_id = device_id - self.generation_id = generation_id - self.etag = etag - self.connection_state = connection_state - self.connection_state_updated_time = connection_state_updated_time - self.last_activity_time = last_activity_time - self.cloud_to_device_message_count = cloud_to_device_message_count - self.authentication = authentication diff --git a/src/azure/iot/hub/protocol/models/property_container.py b/src/azure/iot/hub/protocol/models/property_container.py deleted file mode 100644 index c242995..0000000 --- a/src/azure/iot/hub/protocol/models/property_container.py +++ /dev/null @@ -1,37 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is -# regenerated. -# -------------------------------------------------------------------------- - -from msrest.serialization import Model - - -class PropertyContainer(Model): - """The desired and reported properties of the twin. The maximum depth of the - object is 10. - - :param desired: The collection of desired property key-value pairs. The - keys are UTF-8 encoded, case-sensitive and up-to 1KB in length. Allowed - characters exclude UNICODE control characters (segments C0 and C1), '.', - '$' and space. The desired porperty values are JSON objects, up-to 4KB in - length. - :type desired: dict[str, object] - :param reported: The collection of reported property key-value pairs. The - keys are UTF-8 encoded, case-sensitive and up-to 1KB in length. Allowed - characters exclude UNICODE control characters (segments C0 and C1), '.', - '$' and space. The reported property values are JSON objects, up-to 4KB in - length. - :type reported: dict[str, object] - """ - - _attribute_map = { - "desired": {"key": "desired", "type": "{object}"}, - "reported": {"key": "reported", "type": "{object}"}, - } - - def __init__(self, **kwargs): - super(PropertyContainer, self).__init__(**kwargs) - self.desired = kwargs.get("desired", None) - self.reported = kwargs.get("reported", None) diff --git a/src/azure/iot/hub/protocol/models/property_container_py3.py b/src/azure/iot/hub/protocol/models/property_container_py3.py deleted file mode 100644 index 0ef4cbd..0000000 --- a/src/azure/iot/hub/protocol/models/property_container_py3.py +++ /dev/null @@ -1,37 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is -# regenerated. -# -------------------------------------------------------------------------- - -from msrest.serialization import Model - - -class PropertyContainer(Model): - """The desired and reported properties of the twin. The maximum depth of the - object is 10. - - :param desired: The collection of desired property key-value pairs. The - keys are UTF-8 encoded, case-sensitive and up-to 1KB in length. Allowed - characters exclude UNICODE control characters (segments C0 and C1), '.', - '$' and space. The desired porperty values are JSON objects, up-to 4KB in - length. - :type desired: dict[str, object] - :param reported: The collection of reported property key-value pairs. The - keys are UTF-8 encoded, case-sensitive and up-to 1KB in length. Allowed - characters exclude UNICODE control characters (segments C0 and C1), '.', - '$' and space. The reported property values are JSON objects, up-to 4KB in - length. - :type reported: dict[str, object] - """ - - _attribute_map = { - "desired": {"key": "desired", "type": "{object}"}, - "reported": {"key": "reported", "type": "{object}"}, - } - - def __init__(self, *, desired=None, reported=None, **kwargs) -> None: - super(PropertyContainer, self).__init__(**kwargs) - self.desired = desired - self.reported = reported diff --git a/src/azure/iot/hub/protocol/models/purge_message_queue_result.py b/src/azure/iot/hub/protocol/models/purge_message_queue_result.py deleted file mode 100644 index 5349481..0000000 --- a/src/azure/iot/hub/protocol/models/purge_message_queue_result.py +++ /dev/null @@ -1,32 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is -# regenerated. -# -------------------------------------------------------------------------- - -from msrest.serialization import Model - - -class PurgeMessageQueueResult(Model): - """The result of a device message queue purge operation. - - :param total_messages_purged: - :type total_messages_purged: int - :param device_id: The unique identifier of the device. - :type device_id: str - :param module_id: The unique identifier of the module. - :type module_id: str - """ - - _attribute_map = { - "total_messages_purged": {"key": "totalMessagesPurged", "type": "int"}, - "device_id": {"key": "deviceId", "type": "str"}, - "module_id": {"key": "moduleId", "type": "str"}, - } - - def __init__(self, **kwargs): - super(PurgeMessageQueueResult, self).__init__(**kwargs) - self.total_messages_purged = kwargs.get("total_messages_purged", None) - self.device_id = kwargs.get("device_id", None) - self.module_id = kwargs.get("module_id", None) diff --git a/src/azure/iot/hub/protocol/models/purge_message_queue_result_py3.py b/src/azure/iot/hub/protocol/models/purge_message_queue_result_py3.py deleted file mode 100644 index 4b0ed8b..0000000 --- a/src/azure/iot/hub/protocol/models/purge_message_queue_result_py3.py +++ /dev/null @@ -1,39 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is -# regenerated. -# -------------------------------------------------------------------------- - -from msrest.serialization import Model - - -class PurgeMessageQueueResult(Model): - """The result of a device message queue purge operation. - - :param total_messages_purged: - :type total_messages_purged: int - :param device_id: The unique identifier of the device. - :type device_id: str - :param module_id: The unique identifier of the module. - :type module_id: str - """ - - _attribute_map = { - "total_messages_purged": {"key": "totalMessagesPurged", "type": "int"}, - "device_id": {"key": "deviceId", "type": "str"}, - "module_id": {"key": "moduleId", "type": "str"}, - } - - def __init__( - self, - *, - total_messages_purged: int = None, - device_id: str = None, - module_id: str = None, - **kwargs - ) -> None: - super(PurgeMessageQueueResult, self).__init__(**kwargs) - self.total_messages_purged = total_messages_purged - self.device_id = device_id - self.module_id = module_id diff --git a/src/azure/iot/hub/protocol/models/query_result.py b/src/azure/iot/hub/protocol/models/query_result.py deleted file mode 100644 index 4bd2ff5..0000000 --- a/src/azure/iot/hub/protocol/models/query_result.py +++ /dev/null @@ -1,34 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is -# regenerated. -# -------------------------------------------------------------------------- - -from msrest.serialization import Model - - -class QueryResult(Model): - """The query result. - - :param type: The query result type. Possible values include: 'unknown', - 'twin', 'deviceJob', 'jobResponse', 'raw', 'enrollment', - 'enrollmentGroup', 'deviceRegistration' - :type type: str or ~protocol.models.enum - :param items: The query result items, as a collection. - :type items: list[object] - :param continuation_token: The continuation token. - :type continuation_token: str - """ - - _attribute_map = { - "type": {"key": "type", "type": "str"}, - "items": {"key": "items", "type": "[object]"}, - "continuation_token": {"key": "continuationToken", "type": "str"}, - } - - def __init__(self, **kwargs): - super(QueryResult, self).__init__(**kwargs) - self.type = kwargs.get("type", None) - self.items = kwargs.get("items", None) - self.continuation_token = kwargs.get("continuation_token", None) diff --git a/src/azure/iot/hub/protocol/models/query_result_py3.py b/src/azure/iot/hub/protocol/models/query_result_py3.py deleted file mode 100644 index 36b2ba0..0000000 --- a/src/azure/iot/hub/protocol/models/query_result_py3.py +++ /dev/null @@ -1,34 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is -# regenerated. -# -------------------------------------------------------------------------- - -from msrest.serialization import Model - - -class QueryResult(Model): - """The query result. - - :param type: The query result type. Possible values include: 'unknown', - 'twin', 'deviceJob', 'jobResponse', 'raw', 'enrollment', - 'enrollmentGroup', 'deviceRegistration' - :type type: str or ~protocol.models.enum - :param items: The query result items, as a collection. - :type items: list[object] - :param continuation_token: The continuation token. - :type continuation_token: str - """ - - _attribute_map = { - "type": {"key": "type", "type": "str"}, - "items": {"key": "items", "type": "[object]"}, - "continuation_token": {"key": "continuationToken", "type": "str"}, - } - - def __init__(self, *, type=None, items=None, continuation_token: str = None, **kwargs) -> None: - super(QueryResult, self).__init__(**kwargs) - self.type = type - self.items = items - self.continuation_token = continuation_token diff --git a/src/azure/iot/hub/protocol/models/query_specification.py b/src/azure/iot/hub/protocol/models/query_specification.py deleted file mode 100644 index 050340e..0000000 --- a/src/azure/iot/hub/protocol/models/query_specification.py +++ /dev/null @@ -1,22 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is -# regenerated. -# -------------------------------------------------------------------------- - -from msrest.serialization import Model - - -class QuerySpecification(Model): - """The Json query request. - - :param query: The query string. - :type query: str - """ - - _attribute_map = {"query": {"key": "query", "type": "str"}} - - def __init__(self, **kwargs): - super(QuerySpecification, self).__init__(**kwargs) - self.query = kwargs.get("query", None) diff --git a/src/azure/iot/hub/protocol/models/query_specification_py3.py b/src/azure/iot/hub/protocol/models/query_specification_py3.py deleted file mode 100644 index 75be3d6..0000000 --- a/src/azure/iot/hub/protocol/models/query_specification_py3.py +++ /dev/null @@ -1,22 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is -# regenerated. -# -------------------------------------------------------------------------- - -from msrest.serialization import Model - - -class QuerySpecification(Model): - """The Json query request. - - :param query: The query string. - :type query: str - """ - - _attribute_map = {"query": {"key": "query", "type": "str"}} - - def __init__(self, *, query: str = None, **kwargs) -> None: - super(QuerySpecification, self).__init__(**kwargs) - self.query = query diff --git a/src/azure/iot/hub/protocol/models/registry_statistics.py b/src/azure/iot/hub/protocol/models/registry_statistics.py deleted file mode 100644 index 440da8c..0000000 --- a/src/azure/iot/hub/protocol/models/registry_statistics.py +++ /dev/null @@ -1,33 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is -# regenerated. -# -------------------------------------------------------------------------- - -from msrest.serialization import Model - - -class RegistryStatistics(Model): - """RegistryStatistics. - - :param total_device_count: The total number of devices registered for the - IoT Hub. - :type total_device_count: long - :param enabled_device_count: The number of currently enabled devices. - :type enabled_device_count: long - :param disabled_device_count: The number of currently disabled devices. - :type disabled_device_count: long - """ - - _attribute_map = { - "total_device_count": {"key": "totalDeviceCount", "type": "long"}, - "enabled_device_count": {"key": "enabledDeviceCount", "type": "long"}, - "disabled_device_count": {"key": "disabledDeviceCount", "type": "long"}, - } - - def __init__(self, **kwargs): - super(RegistryStatistics, self).__init__(**kwargs) - self.total_device_count = kwargs.get("total_device_count", None) - self.enabled_device_count = kwargs.get("enabled_device_count", None) - self.disabled_device_count = kwargs.get("disabled_device_count", None) diff --git a/src/azure/iot/hub/protocol/models/registry_statistics_py3.py b/src/azure/iot/hub/protocol/models/registry_statistics_py3.py deleted file mode 100644 index 5670fde..0000000 --- a/src/azure/iot/hub/protocol/models/registry_statistics_py3.py +++ /dev/null @@ -1,40 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is -# regenerated. -# -------------------------------------------------------------------------- - -from msrest.serialization import Model - - -class RegistryStatistics(Model): - """RegistryStatistics. - - :param total_device_count: The total number of devices registered for the - IoT Hub. - :type total_device_count: long - :param enabled_device_count: The number of currently enabled devices. - :type enabled_device_count: long - :param disabled_device_count: The number of currently disabled devices. - :type disabled_device_count: long - """ - - _attribute_map = { - "total_device_count": {"key": "totalDeviceCount", "type": "long"}, - "enabled_device_count": {"key": "enabledDeviceCount", "type": "long"}, - "disabled_device_count": {"key": "disabledDeviceCount", "type": "long"}, - } - - def __init__( - self, - *, - total_device_count: int = None, - enabled_device_count: int = None, - disabled_device_count: int = None, - **kwargs - ) -> None: - super(RegistryStatistics, self).__init__(**kwargs) - self.total_device_count = total_device_count - self.enabled_device_count = enabled_device_count - self.disabled_device_count = disabled_device_count diff --git a/src/azure/iot/hub/protocol/models/service_statistics.py b/src/azure/iot/hub/protocol/models/service_statistics.py deleted file mode 100644 index ec41b08..0000000 --- a/src/azure/iot/hub/protocol/models/service_statistics.py +++ /dev/null @@ -1,22 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is -# regenerated. -# -------------------------------------------------------------------------- - -from msrest.serialization import Model - - -class ServiceStatistics(Model): - """ServiceStatistics. - - :param connected_device_count: The number of currently connected devices. - :type connected_device_count: long - """ - - _attribute_map = {"connected_device_count": {"key": "connectedDeviceCount", "type": "long"}} - - def __init__(self, **kwargs): - super(ServiceStatistics, self).__init__(**kwargs) - self.connected_device_count = kwargs.get("connected_device_count", None) diff --git a/src/azure/iot/hub/protocol/models/service_statistics_py3.py b/src/azure/iot/hub/protocol/models/service_statistics_py3.py deleted file mode 100644 index cf6905f..0000000 --- a/src/azure/iot/hub/protocol/models/service_statistics_py3.py +++ /dev/null @@ -1,22 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is -# regenerated. -# -------------------------------------------------------------------------- - -from msrest.serialization import Model - - -class ServiceStatistics(Model): - """ServiceStatistics. - - :param connected_device_count: The number of currently connected devices. - :type connected_device_count: long - """ - - _attribute_map = {"connected_device_count": {"key": "connectedDeviceCount", "type": "long"}} - - def __init__(self, *, connected_device_count: int = None, **kwargs) -> None: - super(ServiceStatistics, self).__init__(**kwargs) - self.connected_device_count = connected_device_count diff --git a/src/azure/iot/hub/protocol/models/symmetric_key.py b/src/azure/iot/hub/protocol/models/symmetric_key.py deleted file mode 100644 index 7e7e84b..0000000 --- a/src/azure/iot/hub/protocol/models/symmetric_key.py +++ /dev/null @@ -1,28 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is -# regenerated. -# -------------------------------------------------------------------------- - -from msrest.serialization import Model - - -class SymmetricKey(Model): - """SymmetricKey. - - :param primary_key: The base64 encoded primary key of the device. - :type primary_key: str - :param secondary_key: The base64 encoded secondary key of the device. - :type secondary_key: str - """ - - _attribute_map = { - "primary_key": {"key": "primaryKey", "type": "str"}, - "secondary_key": {"key": "secondaryKey", "type": "str"}, - } - - def __init__(self, **kwargs): - super(SymmetricKey, self).__init__(**kwargs) - self.primary_key = kwargs.get("primary_key", None) - self.secondary_key = kwargs.get("secondary_key", None) diff --git a/src/azure/iot/hub/protocol/models/symmetric_key_py3.py b/src/azure/iot/hub/protocol/models/symmetric_key_py3.py deleted file mode 100644 index c4837fa..0000000 --- a/src/azure/iot/hub/protocol/models/symmetric_key_py3.py +++ /dev/null @@ -1,28 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is -# regenerated. -# -------------------------------------------------------------------------- - -from msrest.serialization import Model - - -class SymmetricKey(Model): - """SymmetricKey. - - :param primary_key: The base64 encoded primary key of the device. - :type primary_key: str - :param secondary_key: The base64 encoded secondary key of the device. - :type secondary_key: str - """ - - _attribute_map = { - "primary_key": {"key": "primaryKey", "type": "str"}, - "secondary_key": {"key": "secondaryKey", "type": "str"}, - } - - def __init__(self, *, primary_key: str = None, secondary_key: str = None, **kwargs) -> None: - super(SymmetricKey, self).__init__(**kwargs) - self.primary_key = primary_key - self.secondary_key = secondary_key diff --git a/src/azure/iot/hub/protocol/models/twin.py b/src/azure/iot/hub/protocol/models/twin.py deleted file mode 100644 index 6c78a75..0000000 --- a/src/azure/iot/hub/protocol/models/twin.py +++ /dev/null @@ -1,122 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is -# regenerated. -# -------------------------------------------------------------------------- - -from msrest.serialization import Model - - -class Twin(Model): - """The state information for a device or module. This is implicitly created - and deleted when the corresponding device/ module identity is created or - deleted in the IoT Hub. - - :param device_id: The unique identifier of the device in the identity - registry of the IoT Hub. It is a case-sensitive string (up to 128 char - long) of ASCII 7-bit alphanumeric chars, and the following special - characters {'-', ':', '.', '+', '%', '_', '#', '*', '?', '!', '(', ')', - ',', '=', '@', ';', '$', '''}. - :type device_id: str - :param module_id: The unique identifier of the module in the identity - registry of the IoT Hub. It is a case-sensitive string (up to 128 char - long) of ASCII 7-bit alphanumeric chars, and the following special - characters {'-', ':', '.', '+', '%', '_', '#', '*', '?', '!', '(', ')', - ',', '=', '@', ';', '$', '''}. - :type module_id: str - :param tags: The collection of key-value pairs read and written by the - solution back end. They are not visible to device apps. They keys are - UTF-8 encoded, case-sensitive and up-to 1KB in length. Allowed characters - exclude UNICODE control characters (segments C0 and C1), '.', '$' and - space. The values are JSON objects, up-to 4KB in length. - :type tags: dict[str, object] - :param properties: The desired and reported properties of the twin. - :type properties: ~protocol.models.TwinProperties - :param etag: The string representing a ETag for the device twin, as per - RFC7232. - :type etag: str - :param version: The version for the device twin including tags and desired - properties - :type version: long - :param device_etag: The string representing a ETag for the device, as per - RFC7232. - :type device_etag: str - :param status: The enabled status of the device. If disabled, the device - cannot connect to the service. Possible values include: 'enabled', - 'disabled' - :type status: str or ~protocol.models.enum - :param status_reason: The reason for the current status of the device, if - any. - :type status_reason: str - :param status_update_time: The date and time when the status of the device - was last updated. - :type status_update_time: datetime - :param connection_state: The connection state of the device. Possible - values include: 'Disconnected', 'Connected' - :type connection_state: str or ~protocol.models.enum - :param last_activity_time: The date and time when the device last - connected or received or sent a message. The date and time is sepecified - in ISO8601 datetime format in UTC, for example, 2015-01-28T16:24:48.789Z. - This value is not updated if the device uses the HTTP/1 protocol to - perform messaging operations. - :type last_activity_time: datetime - :param cloud_to_device_message_count: The number of cloud-to-device - messages sent. - :type cloud_to_device_message_count: int - :param authentication_type: The authentication type used by the device. - Possible values include: 'sas', 'selfSigned', 'certificateAuthority', - 'none' - :type authentication_type: str or ~protocol.models.enum - :param x509_thumbprint: The X509 thumbprint of the device. - :type x509_thumbprint: ~protocol.models.X509Thumbprint - :param capabilities: - :type capabilities: ~protocol.models.DeviceCapabilities - :param device_scope: The scope of the device. - :type device_scope: str - :param parent_scopes: The scopes of the upper level edge devices if - applicable. Only available for edge devices. - :type parent_scopes: list[str] - """ - - _attribute_map = { - "device_id": {"key": "deviceId", "type": "str"}, - "module_id": {"key": "moduleId", "type": "str"}, - "tags": {"key": "tags", "type": "{object}"}, - "properties": {"key": "properties", "type": "TwinProperties"}, - "etag": {"key": "etag", "type": "str"}, - "version": {"key": "version", "type": "long"}, - "device_etag": {"key": "deviceEtag", "type": "str"}, - "status": {"key": "status", "type": "str"}, - "status_reason": {"key": "statusReason", "type": "str"}, - "status_update_time": {"key": "statusUpdateTime", "type": "iso-8601"}, - "connection_state": {"key": "connectionState", "type": "str"}, - "last_activity_time": {"key": "lastActivityTime", "type": "iso-8601"}, - "cloud_to_device_message_count": {"key": "cloudToDeviceMessageCount", "type": "int"}, - "authentication_type": {"key": "authenticationType", "type": "str"}, - "x509_thumbprint": {"key": "x509Thumbprint", "type": "X509Thumbprint"}, - "capabilities": {"key": "capabilities", "type": "DeviceCapabilities"}, - "device_scope": {"key": "deviceScope", "type": "str"}, - "parent_scopes": {"key": "parentScopes", "type": "[str]"}, - } - - def __init__(self, **kwargs): - super(Twin, self).__init__(**kwargs) - self.device_id = kwargs.get("device_id", None) - self.module_id = kwargs.get("module_id", None) - self.tags = kwargs.get("tags", None) - self.properties = kwargs.get("properties", None) - self.etag = kwargs.get("etag", None) - self.version = kwargs.get("version", None) - self.device_etag = kwargs.get("device_etag", None) - self.status = kwargs.get("status", None) - self.status_reason = kwargs.get("status_reason", None) - self.status_update_time = kwargs.get("status_update_time", None) - self.connection_state = kwargs.get("connection_state", None) - self.last_activity_time = kwargs.get("last_activity_time", None) - self.cloud_to_device_message_count = kwargs.get("cloud_to_device_message_count", None) - self.authentication_type = kwargs.get("authentication_type", None) - self.x509_thumbprint = kwargs.get("x509_thumbprint", None) - self.capabilities = kwargs.get("capabilities", None) - self.device_scope = kwargs.get("device_scope", None) - self.parent_scopes = kwargs.get("parent_scopes", None) diff --git a/src/azure/iot/hub/protocol/models/twin_properties.py b/src/azure/iot/hub/protocol/models/twin_properties.py deleted file mode 100644 index 9b898f8..0000000 --- a/src/azure/iot/hub/protocol/models/twin_properties.py +++ /dev/null @@ -1,37 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is -# regenerated. -# -------------------------------------------------------------------------- - -from msrest.serialization import Model - - -class TwinProperties(Model): - """The desired and reported properties of the twin. The maximum depth of the - object is 10. - - :param desired: The collection of desired property key-value pairs. The - keys are UTF-8 encoded, case-sensitive and up-to 1KB in length. Allowed - characters exclude UNICODE control characters (segments C0 and C1), '.', - '$' and space. The desired porperty values are JSON objects, up-to 4KB in - length. - :type desired: dict[str, object] - :param reported: The collection of reported property key-value pairs. The - keys are UTF-8 encoded, case-sensitive and up-to 1KB in length. Allowed - characters exclude UNICODE control characters (segments C0 and C1), '.', - '$' and space. The reported property values are JSON objects, up-to 4KB in - length. - :type reported: dict[str, object] - """ - - _attribute_map = { - "desired": {"key": "desired", "type": "{object}"}, - "reported": {"key": "reported", "type": "{object}"}, - } - - def __init__(self, **kwargs): - super(TwinProperties, self).__init__(**kwargs) - self.desired = kwargs.get("desired", None) - self.reported = kwargs.get("reported", None) diff --git a/src/azure/iot/hub/protocol/models/twin_properties_py3.py b/src/azure/iot/hub/protocol/models/twin_properties_py3.py deleted file mode 100644 index b7e55df..0000000 --- a/src/azure/iot/hub/protocol/models/twin_properties_py3.py +++ /dev/null @@ -1,37 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is -# regenerated. -# -------------------------------------------------------------------------- - -from msrest.serialization import Model - - -class TwinProperties(Model): - """The desired and reported properties of the twin. The maximum depth of the - object is 10. - - :param desired: The collection of desired property key-value pairs. The - keys are UTF-8 encoded, case-sensitive and up-to 1KB in length. Allowed - characters exclude UNICODE control characters (segments C0 and C1), '.', - '$' and space. The desired porperty values are JSON objects, up-to 4KB in - length. - :type desired: dict[str, object] - :param reported: The collection of reported property key-value pairs. The - keys are UTF-8 encoded, case-sensitive and up-to 1KB in length. Allowed - characters exclude UNICODE control characters (segments C0 and C1), '.', - '$' and space. The reported property values are JSON objects, up-to 4KB in - length. - :type reported: dict[str, object] - """ - - _attribute_map = { - "desired": {"key": "desired", "type": "{object}"}, - "reported": {"key": "reported", "type": "{object}"}, - } - - def __init__(self, *, desired=None, reported=None, **kwargs) -> None: - super(TwinProperties, self).__init__(**kwargs) - self.desired = desired - self.reported = reported diff --git a/src/azure/iot/hub/protocol/models/twin_py3.py b/src/azure/iot/hub/protocol/models/twin_py3.py deleted file mode 100644 index 9f7a193..0000000 --- a/src/azure/iot/hub/protocol/models/twin_py3.py +++ /dev/null @@ -1,144 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is -# regenerated. -# -------------------------------------------------------------------------- - -from msrest.serialization import Model - - -class Twin(Model): - """The state information for a device or module. This is implicitly created - and deleted when the corresponding device/ module identity is created or - deleted in the IoT Hub. - - :param device_id: The unique identifier of the device in the identity - registry of the IoT Hub. It is a case-sensitive string (up to 128 char - long) of ASCII 7-bit alphanumeric chars, and the following special - characters {'-', ':', '.', '+', '%', '_', '#', '*', '?', '!', '(', ')', - ',', '=', '@', ';', '$', '''}. - :type device_id: str - :param module_id: The unique identifier of the module in the identity - registry of the IoT Hub. It is a case-sensitive string (up to 128 char - long) of ASCII 7-bit alphanumeric chars, and the following special - characters {'-', ':', '.', '+', '%', '_', '#', '*', '?', '!', '(', ')', - ',', '=', '@', ';', '$', '''}. - :type module_id: str - :param tags: The collection of key-value pairs read and written by the - solution back end. They are not visible to device apps. They keys are - UTF-8 encoded, case-sensitive and up-to 1KB in length. Allowed characters - exclude UNICODE control characters (segments C0 and C1), '.', '$' and - space. The values are JSON objects, up-to 4KB in length. - :type tags: dict[str, object] - :param properties: The desired and reported properties of the twin. - :type properties: ~protocol.models.TwinProperties - :param etag: The string representing a ETag for the device twin, as per - RFC7232. - :type etag: str - :param version: The version for the device twin including tags and desired - properties - :type version: long - :param device_etag: The string representing a ETag for the device, as per - RFC7232. - :type device_etag: str - :param status: The enabled status of the device. If disabled, the device - cannot connect to the service. Possible values include: 'enabled', - 'disabled' - :type status: str or ~protocol.models.enum - :param status_reason: The reason for the current status of the device, if - any. - :type status_reason: str - :param status_update_time: The date and time when the status of the device - was last updated. - :type status_update_time: datetime - :param connection_state: The connection state of the device. Possible - values include: 'Disconnected', 'Connected' - :type connection_state: str or ~protocol.models.enum - :param last_activity_time: The date and time when the device last - connected or received or sent a message. The date and time is sepecified - in ISO8601 datetime format in UTC, for example, 2015-01-28T16:24:48.789Z. - This value is not updated if the device uses the HTTP/1 protocol to - perform messaging operations. - :type last_activity_time: datetime - :param cloud_to_device_message_count: The number of cloud-to-device - messages sent. - :type cloud_to_device_message_count: int - :param authentication_type: The authentication type used by the device. - Possible values include: 'sas', 'selfSigned', 'certificateAuthority', - 'none' - :type authentication_type: str or ~protocol.models.enum - :param x509_thumbprint: The X509 thumbprint of the device. - :type x509_thumbprint: ~protocol.models.X509Thumbprint - :param capabilities: - :type capabilities: ~protocol.models.DeviceCapabilities - :param device_scope: The scope of the device. - :type device_scope: str - :param parent_scopes: The scopes of the upper level edge devices if - applicable. Only available for edge devices. - :type parent_scopes: list[str] - """ - - _attribute_map = { - "device_id": {"key": "deviceId", "type": "str"}, - "module_id": {"key": "moduleId", "type": "str"}, - "tags": {"key": "tags", "type": "{object}"}, - "properties": {"key": "properties", "type": "TwinProperties"}, - "etag": {"key": "etag", "type": "str"}, - "version": {"key": "version", "type": "long"}, - "device_etag": {"key": "deviceEtag", "type": "str"}, - "status": {"key": "status", "type": "str"}, - "status_reason": {"key": "statusReason", "type": "str"}, - "status_update_time": {"key": "statusUpdateTime", "type": "iso-8601"}, - "connection_state": {"key": "connectionState", "type": "str"}, - "last_activity_time": {"key": "lastActivityTime", "type": "iso-8601"}, - "cloud_to_device_message_count": {"key": "cloudToDeviceMessageCount", "type": "int"}, - "authentication_type": {"key": "authenticationType", "type": "str"}, - "x509_thumbprint": {"key": "x509Thumbprint", "type": "X509Thumbprint"}, - "capabilities": {"key": "capabilities", "type": "DeviceCapabilities"}, - "device_scope": {"key": "deviceScope", "type": "str"}, - "parent_scopes": {"key": "parentScopes", "type": "[str]"}, - } - - def __init__( - self, - *, - device_id: str = None, - module_id: str = None, - tags=None, - properties=None, - etag: str = None, - version: int = None, - device_etag: str = None, - status=None, - status_reason: str = None, - status_update_time=None, - connection_state=None, - last_activity_time=None, - cloud_to_device_message_count: int = None, - authentication_type=None, - x509_thumbprint=None, - capabilities=None, - device_scope: str = None, - parent_scopes=None, - **kwargs - ) -> None: - super(Twin, self).__init__(**kwargs) - self.device_id = device_id - self.module_id = module_id - self.tags = tags - self.properties = properties - self.etag = etag - self.version = version - self.device_etag = device_etag - self.status = status - self.status_reason = status_reason - self.status_update_time = status_update_time - self.connection_state = connection_state - self.last_activity_time = last_activity_time - self.cloud_to_device_message_count = cloud_to_device_message_count - self.authentication_type = authentication_type - self.x509_thumbprint = x509_thumbprint - self.capabilities = capabilities - self.device_scope = device_scope - self.parent_scopes = parent_scopes diff --git a/src/azure/iot/hub/protocol/models/x509_thumbprint.py b/src/azure/iot/hub/protocol/models/x509_thumbprint.py deleted file mode 100644 index f02200b..0000000 --- a/src/azure/iot/hub/protocol/models/x509_thumbprint.py +++ /dev/null @@ -1,29 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is -# regenerated. -# -------------------------------------------------------------------------- - -from msrest.serialization import Model - - -class X509Thumbprint(Model): - """X509Thumbprint. - - :param primary_thumbprint: The X509 client certificate primary thumbprint. - :type primary_thumbprint: str - :param secondary_thumbprint: The X509 client certificate secondary - thumbprint. - :type secondary_thumbprint: str - """ - - _attribute_map = { - "primary_thumbprint": {"key": "primaryThumbprint", "type": "str"}, - "secondary_thumbprint": {"key": "secondaryThumbprint", "type": "str"}, - } - - def __init__(self, **kwargs): - super(X509Thumbprint, self).__init__(**kwargs) - self.primary_thumbprint = kwargs.get("primary_thumbprint", None) - self.secondary_thumbprint = kwargs.get("secondary_thumbprint", None) diff --git a/src/azure/iot/hub/protocol/models/x509_thumbprint_py3.py b/src/azure/iot/hub/protocol/models/x509_thumbprint_py3.py deleted file mode 100644 index c3f3c93..0000000 --- a/src/azure/iot/hub/protocol/models/x509_thumbprint_py3.py +++ /dev/null @@ -1,31 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is -# regenerated. -# -------------------------------------------------------------------------- - -from msrest.serialization import Model - - -class X509Thumbprint(Model): - """X509Thumbprint. - - :param primary_thumbprint: The X509 client certificate primary thumbprint. - :type primary_thumbprint: str - :param secondary_thumbprint: The X509 client certificate secondary - thumbprint. - :type secondary_thumbprint: str - """ - - _attribute_map = { - "primary_thumbprint": {"key": "primaryThumbprint", "type": "str"}, - "secondary_thumbprint": {"key": "secondaryThumbprint", "type": "str"}, - } - - def __init__( - self, *, primary_thumbprint: str = None, secondary_thumbprint: str = None, **kwargs - ) -> None: - super(X509Thumbprint, self).__init__(**kwargs) - self.primary_thumbprint = primary_thumbprint - self.secondary_thumbprint = secondary_thumbprint diff --git a/src/azure/iot/hub/protocol/operations/__init__.py b/src/azure/iot/hub/protocol/operations/__init__.py index 100a105..d05751c 100644 --- a/src/azure/iot/hub/protocol/operations/__init__.py +++ b/src/azure/iot/hub/protocol/operations/__init__.py @@ -1,19 +1,30 @@ # coding=utf-8 # -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is -# regenerated. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position -from .configuration_operations import ConfigurationOperations -from .statistics_operations import StatisticsOperations -from .devices_operations import DevicesOperations -from .bulk_registry_operations import BulkRegistryOperations -from .query_operations import QueryOperations -from .jobs_operations import JobsOperations -from .cloud_to_device_messages_operations import CloudToDeviceMessagesOperations -from .modules_operations import ModulesOperations -from .digital_twin_operations import DigitalTwinOperations +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._configuration_operations import ConfigurationOperations # type: ignore +from ._statistics_operations import StatisticsOperations # type: ignore +from ._devices_operations import DevicesOperations # type: ignore +from ._bulk_registry_operations import BulkRegistryOperations # type: ignore +from ._query_operations import QueryOperations # type: ignore +from ._jobs_operations import JobsOperations # type: ignore +from ._cloud_to_device_messages_operations import CloudToDeviceMessagesOperations # type: ignore +from ._modules_operations import ModulesOperations # type: ignore +from ._digital_twin_operations import DigitalTwinOperations # type: ignore + +from ._patch import __all__ as _patch_all +from ._patch import * +from ._patch import patch_sdk as _patch_sdk __all__ = [ "ConfigurationOperations", @@ -26,3 +37,5 @@ "ModulesOperations", "DigitalTwinOperations", ] +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore +_patch_sdk() diff --git a/src/azure/iot/hub/protocol/operations/_bulk_registry_operations.py b/src/azure/iot/hub/protocol/operations/_bulk_registry_operations.py new file mode 100644 index 0000000..18d9734 --- /dev/null +++ b/src/azure/iot/hub/protocol/operations/_bulk_registry_operations.py @@ -0,0 +1,185 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from collections.abc import MutableMapping +from io import IOBase +from typing import Any, Callable, IO, Optional, TypeVar, Union, overload + +from azure.core import PipelineClient +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.rest import HttpRequest, HttpResponse +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict + +from .. import models as _models +from .._configuration import IotHubGatewayServiceAPIsConfiguration +from .._utils.serialization import Deserializer, Serializer + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_update_registry_request(**kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-04-12")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/devices") + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +class BulkRegistryOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.iot.hub.protocol.IotHubGatewayServiceAPIs`'s + :attr:`bulk_registry` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: IotHubGatewayServiceAPIsConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @overload + def update_registry( + self, devices: list[_models.ExportImportDevice], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.BulkRegistryOperationResult: + """Creates, updates, or deletes the identities of multiple devices from the IoT Hub identity + registry. A device identity can be specified only once in the list. Different operations + (create, update, delete) on different devices are allowed. A maximum of 100 devices can be + specified per invocation. For large scale operations, use the import feature using blob storage + (https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-identity-registry#import-and-export-device-identities). + + :param devices: The registry operations to perform. Required. + :type devices: list[~azure.iot.hub.protocol.models.ExportImportDevice] + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: BulkRegistryOperationResult or the result of cls(response) + :rtype: ~azure.iot.hub.protocol.models.BulkRegistryOperationResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def update_registry( + self, devices: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.BulkRegistryOperationResult: + """Creates, updates, or deletes the identities of multiple devices from the IoT Hub identity + registry. A device identity can be specified only once in the list. Different operations + (create, update, delete) on different devices are allowed. A maximum of 100 devices can be + specified per invocation. For large scale operations, use the import feature using blob storage + (https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-identity-registry#import-and-export-device-identities). + + :param devices: The registry operations to perform. Required. + :type devices: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: BulkRegistryOperationResult or the result of cls(response) + :rtype: ~azure.iot.hub.protocol.models.BulkRegistryOperationResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def update_registry( + self, devices: Union[list[_models.ExportImportDevice], IO[bytes]], **kwargs: Any + ) -> _models.BulkRegistryOperationResult: + """Creates, updates, or deletes the identities of multiple devices from the IoT Hub identity + registry. A device identity can be specified only once in the list. Different operations + (create, update, delete) on different devices are allowed. A maximum of 100 devices can be + specified per invocation. For large scale operations, use the import feature using blob storage + (https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-identity-registry#import-and-export-device-identities). + + :param devices: The registry operations to perform. Is either a [ExportImportDevice] type or a + IO[bytes] type. Required. + :type devices: list[~azure.iot.hub.protocol.models.ExportImportDevice] or IO[bytes] + :return: BulkRegistryOperationResult or the result of cls(response) + :rtype: ~azure.iot.hub.protocol.models.BulkRegistryOperationResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.BulkRegistryOperationResult] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(devices, (IOBase, bytes)): + _content = devices + else: + _json = self._serialize.body(devices, "[ExportImportDevice]") + + _request = build_update_registry_request( + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 400]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + deserialized = self._deserialize("BulkRegistryOperationResult", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore diff --git a/src/azure/iot/hub/protocol/operations/_cloud_to_device_messages_operations.py b/src/azure/iot/hub/protocol/operations/_cloud_to_device_messages_operations.py new file mode 100644 index 0000000..f3ec6bd --- /dev/null +++ b/src/azure/iot/hub/protocol/operations/_cloud_to_device_messages_operations.py @@ -0,0 +1,329 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from collections.abc import MutableMapping +from typing import Any, Callable, Optional, TypeVar + +from azure.core import PipelineClient +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.rest import HttpRequest, HttpResponse +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict + +from .. import models as _models +from .._configuration import IotHubGatewayServiceAPIsConfiguration +from .._utils.serialization import Deserializer, Serializer + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_purge_cloud_to_device_message_queue_request( # pylint: disable=name-too-long + id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-04-12")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/devices/{id}/commands") + path_format_arguments = { + "id": _SERIALIZER.url("id", id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_receive_feedback_notification_request(**kwargs: Any) -> HttpRequest: # pylint: disable=name-too-long + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-04-12")) + # Construct URL + _url = kwargs.pop("template_url", "/messages/serviceBound/feedback") + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + return HttpRequest(method="GET", url=_url, params=_params, **kwargs) + + +def build_complete_feedback_notification_request( # pylint: disable=name-too-long + lock_token: str, **kwargs: Any +) -> HttpRequest: + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-04-12")) + # Construct URL + _url = kwargs.pop("template_url", "/messages/serviceBound/feedback/{lockToken}") + path_format_arguments = { + "lockToken": _SERIALIZER.url("lock_token", lock_token, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, **kwargs) + + +def build_abandon_feedback_notification_request( # pylint: disable=name-too-long + lock_token: str, **kwargs: Any +) -> HttpRequest: + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-04-12")) + # Construct URL + _url = kwargs.pop("template_url", "/messages/serviceBound/feedback/{lockToken}/abandon") + path_format_arguments = { + "lockToken": _SERIALIZER.url("lock_token", lock_token, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + return HttpRequest(method="POST", url=_url, params=_params, **kwargs) + + +class CloudToDeviceMessagesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.iot.hub.protocol.IotHubGatewayServiceAPIs`'s + :attr:`cloud_to_device_messages` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: IotHubGatewayServiceAPIsConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def purge_cloud_to_device_message_queue(self, id: str, **kwargs: Any) -> _models.PurgeMessageQueueResult: + """Deletes all the pending commands for a device in the IoT Hub. + + :param id: The unique identifier of the device. Required. + :type id: str + :return: PurgeMessageQueueResult or the result of cls(response) + :rtype: ~azure.iot.hub.protocol.models.PurgeMessageQueueResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.PurgeMessageQueueResult] = kwargs.pop("cls", None) + + _request = build_purge_cloud_to_device_message_queue_request( + id=id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + deserialized = self._deserialize("PurgeMessageQueueResult", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def receive_feedback_notification(self, **kwargs: Any) -> None: # pylint: disable=inconsistent-return-statements + """Gets the feedback for cloud-to-device messages. See + https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-messaging for more information. This + capability is only available in the standard tier IoT Hub. For more information, see `Choose + the right IoT Hub tier `_. + + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_receive_feedback_notification_request( + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @distributed_trace + def complete_feedback_notification( # pylint: disable=inconsistent-return-statements + self, lock_token: str, **kwargs: Any + ) -> None: + """Completes the cloud-to-device feedback message. A completed message is deleted from the + feedback queue of the service. See + https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-messaging for more information. + + :param lock_token: The lock token obtained when the cloud-to-device message is received. This + is used to resolve race conditions when completing a feedback message. Required. + :type lock_token: str + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_complete_feedback_notification_request( + lock_token=lock_token, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @distributed_trace + def abandon_feedback_notification( # pylint: disable=inconsistent-return-statements + self, lock_token: str, **kwargs: Any + ) -> None: + """Abandons the lock on a cloud-to-device feedback message. See + https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-messaging for more information. + + :param lock_token: The lock token obtained when the cloud-to-device message is received. + Required. + :type lock_token: str + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_abandon_feedback_notification_request( + lock_token=lock_token, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore diff --git a/src/azure/iot/hub/protocol/operations/_configuration_operations.py b/src/azure/iot/hub/protocol/operations/_configuration_operations.py new file mode 100644 index 0000000..f6a8caf --- /dev/null +++ b/src/azure/iot/hub/protocol/operations/_configuration_operations.py @@ -0,0 +1,683 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from collections.abc import MutableMapping +from io import IOBase +from typing import Any, Callable, IO, Optional, TypeVar, Union, overload + +from azure.core import PipelineClient +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.rest import HttpRequest, HttpResponse +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict + +from .. import models as _models +from .._configuration import IotHubGatewayServiceAPIsConfiguration +from .._utils.serialization import Deserializer, Serializer + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_get_request(id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-04-12")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/configurations/{id}") + path_format_arguments = { + "id": _SERIALIZER.url("id", id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_create_or_update_request(id: str, *, if_match: Optional[str] = None, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-04-12")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/configurations/{id}") + path_format_arguments = { + "id": _SERIALIZER.url("id", id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if if_match is not None: + _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_delete_request(id: str, *, if_match: Optional[str] = None, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-04-12")) + # Construct URL + _url = kwargs.pop("template_url", "/configurations/{id}") + path_format_arguments = { + "id": _SERIALIZER.url("id", id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if if_match is not None: + _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_get_configurations_request(*, top: Optional[int] = None, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-04-12")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/configurations") + + # Construct parameters + if top is not None: + _params["top"] = _SERIALIZER.query("top", top, "int") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_test_queries_request(**kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-04-12")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/configurations/testQueries") + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_apply_on_edge_device_request(id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-04-12")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + # Construct URL + _url = kwargs.pop("template_url", "/devices/{id}/applyConfigurationContent") + path_format_arguments = { + "id": _SERIALIZER.url("id", id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +class ConfigurationOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.iot.hub.protocol.IotHubGatewayServiceAPIs`'s + :attr:`configuration` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: IotHubGatewayServiceAPIsConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def get(self, id: str, **kwargs: Any) -> _models.Configuration: + """Gets a configuration on the IoT Hub for automatic device/module management. + + :param id: The unique identifier of the configuration. Required. + :type id: str + :return: Configuration or the result of cls(response) + :rtype: ~azure.iot.hub.protocol.models.Configuration + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.Configuration] = kwargs.pop("cls", None) + + _request = build_get_request( + id=id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + deserialized = self._deserialize("Configuration", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def create_or_update( + self, + id: str, + configuration: _models.Configuration, + if_match: Optional[str] = None, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Configuration: + """Creates or updates a configuration on the IoT Hub for automatic device/module management. + Configuration identifier and Content cannot be updated. + + :param id: The unique identifier of the configuration. Required. + :type id: str + :param configuration: The configuration to be created or updated. Required. + :type configuration: ~azure.iot.hub.protocol.models.Configuration + :param if_match: The string representing a weak ETag for the configuration, as per RFC7232. + This should not be set when creating a configuration, but may be set when updating a + configuration. Default value is None. + :type if_match: str + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: Configuration or the result of cls(response) + :rtype: ~azure.iot.hub.protocol.models.Configuration + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_or_update( + self, + id: str, + configuration: IO[bytes], + if_match: Optional[str] = None, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Configuration: + """Creates or updates a configuration on the IoT Hub for automatic device/module management. + Configuration identifier and Content cannot be updated. + + :param id: The unique identifier of the configuration. Required. + :type id: str + :param configuration: The configuration to be created or updated. Required. + :type configuration: IO[bytes] + :param if_match: The string representing a weak ETag for the configuration, as per RFC7232. + This should not be set when creating a configuration, but may be set when updating a + configuration. Default value is None. + :type if_match: str + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: Configuration or the result of cls(response) + :rtype: ~azure.iot.hub.protocol.models.Configuration + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create_or_update( + self, + id: str, + configuration: Union[_models.Configuration, IO[bytes]], + if_match: Optional[str] = None, + **kwargs: Any + ) -> _models.Configuration: + """Creates or updates a configuration on the IoT Hub for automatic device/module management. + Configuration identifier and Content cannot be updated. + + :param id: The unique identifier of the configuration. Required. + :type id: str + :param configuration: The configuration to be created or updated. Is either a Configuration + type or a IO[bytes] type. Required. + :type configuration: ~azure.iot.hub.protocol.models.Configuration or IO[bytes] + :param if_match: The string representing a weak ETag for the configuration, as per RFC7232. + This should not be set when creating a configuration, but may be set when updating a + configuration. Default value is None. + :type if_match: str + :return: Configuration or the result of cls(response) + :rtype: ~azure.iot.hub.protocol.models.Configuration + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.Configuration] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(configuration, (IOBase, bytes)): + _content = configuration + else: + _json = self._serialize.body(configuration, "Configuration") + + _request = build_create_or_update_request( + id=id, + if_match=if_match, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + deserialized = self._deserialize("Configuration", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def delete( # pylint: disable=inconsistent-return-statements + self, id: str, if_match: Optional[str] = None, **kwargs: Any + ) -> None: + """Deletes a configuration on the IoT Hub for automatic device/module management. + + :param id: The unique identifier of the configuration. Required. + :type id: str + :param if_match: The string representing a weak ETag for the configuration, as per RFC7232. The + delete operation is performed only if this ETag matches the value maintained by the server, + indicating that the configuration has not been modified since it was last retrieved. To force + an unconditional delete, set If-Match to the wildcard character (*). Default value is None. + :type if_match: str + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_delete_request( + id=id, + if_match=if_match, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @distributed_trace + def get_configurations(self, top: Optional[int] = None, **kwargs: Any) -> list[_models.Configuration]: + """Gets configurations on the IoT Hub for automatic device/module management. Pagination is not + supported. + + :param top: The number of configurations to retrieve. Value will be overridden if greater than + the maximum deployment count for the IoT Hub. Default value is None. + :type top: int + :return: list of Configuration or the result of cls(response) + :rtype: list[~azure.iot.hub.protocol.models.Configuration] + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[list[_models.Configuration]] = kwargs.pop("cls", None) + + _request = build_get_configurations_request( + top=top, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + deserialized = self._deserialize("[Configuration]", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def test_queries( + self, input: _models.ConfigurationQueriesTestInput, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.ConfigurationQueriesTestResponse: + """Validates target condition and custom metric queries for a configuration on the IoT Hub. + + :param input: The configuration for target condition and custom metric queries. Required. + :type input: ~azure.iot.hub.protocol.models.ConfigurationQueriesTestInput + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: ConfigurationQueriesTestResponse or the result of cls(response) + :rtype: ~azure.iot.hub.protocol.models.ConfigurationQueriesTestResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def test_queries( + self, input: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.ConfigurationQueriesTestResponse: + """Validates target condition and custom metric queries for a configuration on the IoT Hub. + + :param input: The configuration for target condition and custom metric queries. Required. + :type input: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: ConfigurationQueriesTestResponse or the result of cls(response) + :rtype: ~azure.iot.hub.protocol.models.ConfigurationQueriesTestResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def test_queries( + self, input: Union[_models.ConfigurationQueriesTestInput, IO[bytes]], **kwargs: Any + ) -> _models.ConfigurationQueriesTestResponse: + """Validates target condition and custom metric queries for a configuration on the IoT Hub. + + :param input: The configuration for target condition and custom metric queries. Is either a + ConfigurationQueriesTestInput type or a IO[bytes] type. Required. + :type input: ~azure.iot.hub.protocol.models.ConfigurationQueriesTestInput or IO[bytes] + :return: ConfigurationQueriesTestResponse or the result of cls(response) + :rtype: ~azure.iot.hub.protocol.models.ConfigurationQueriesTestResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.ConfigurationQueriesTestResponse] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(input, (IOBase, bytes)): + _content = input + else: + _json = self._serialize.body(input, "ConfigurationQueriesTestInput") + + _request = build_test_queries_request( + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + deserialized = self._deserialize("ConfigurationQueriesTestResponse", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def apply_on_edge_device( + self, id: str, content: _models.ConfigurationContent, *, content_type: str = "application/json", **kwargs: Any + ) -> None: + """Applies the configuration content to an edge device. + + :param id: The unique identifier of the edge device. Required. + :type id: str + :param content: The configuration content. Required. + :type content: ~azure.iot.hub.protocol.models.ConfigurationContent + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def apply_on_edge_device( + self, id: str, content: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> None: + """Applies the configuration content to an edge device. + + :param id: The unique identifier of the edge device. Required. + :type id: str + :param content: The configuration content. Required. + :type content: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def apply_on_edge_device( # pylint: disable=inconsistent-return-statements + self, id: str, content: Union[_models.ConfigurationContent, IO[bytes]], **kwargs: Any + ) -> None: + """Applies the configuration content to an edge device. + + :param id: The unique identifier of the edge device. Required. + :type id: str + :param content: The configuration content. Is either a ConfigurationContent type or a IO[bytes] + type. Required. + :type content: ~azure.iot.hub.protocol.models.ConfigurationContent or IO[bytes] + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[None] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(content, (IOBase, bytes)): + _content = content + else: + _json = self._serialize.body(content, "ConfigurationContent") + + _request = build_apply_on_edge_device_request( + id=id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore diff --git a/src/azure/iot/hub/protocol/operations/_devices_operations.py b/src/azure/iot/hub/protocol/operations/_devices_operations.py new file mode 100644 index 0000000..f36adba --- /dev/null +++ b/src/azure/iot/hub/protocol/operations/_devices_operations.py @@ -0,0 +1,969 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from collections.abc import MutableMapping +from io import IOBase +from typing import Any, Callable, IO, Optional, TypeVar, Union, overload + +from azure.core import PipelineClient +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.rest import HttpRequest, HttpResponse +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict + +from .. import models as _models +from .._configuration import IotHubGatewayServiceAPIsConfiguration +from .._utils.serialization import Deserializer, Serializer + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_get_devices_request(*, top: Optional[int] = None, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-04-12")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/devices") + + # Construct parameters + if top is not None: + _params["top"] = _SERIALIZER.query("top", top, "int") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_get_identity_request(id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-04-12")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/devices/{id}") + path_format_arguments = { + "id": _SERIALIZER.url("id", id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_create_or_update_identity_request(id: str, *, if_match: Optional[str] = None, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-04-12")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/devices/{id}") + path_format_arguments = { + "id": _SERIALIZER.url("id", id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if if_match is not None: + _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_delete_identity_request(id: str, *, if_match: Optional[str] = None, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-04-12")) + # Construct URL + _url = kwargs.pop("template_url", "/devices/{id}") + path_format_arguments = { + "id": _SERIALIZER.url("id", id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if if_match is not None: + _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_get_twin_request(id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-04-12")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/twins/{id}") + path_format_arguments = { + "id": _SERIALIZER.url("id", id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_replace_twin_request(id: str, *, if_match: Optional[str] = None, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-04-12")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/twins/{id}") + path_format_arguments = { + "id": _SERIALIZER.url("id", id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if if_match is not None: + _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_update_twin_request(id: str, *, if_match: Optional[str] = None, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-04-12")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/twins/{id}") + path_format_arguments = { + "id": _SERIALIZER.url("id", id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if if_match is not None: + _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_invoke_method_request(device_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-04-12")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/twins/{deviceId}/methods") + path_format_arguments = { + "deviceId": _SERIALIZER.url("device_id", device_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +class DevicesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.iot.hub.protocol.IotHubGatewayServiceAPIs`'s + :attr:`devices` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: IotHubGatewayServiceAPIsConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def get_devices(self, top: Optional[int] = None, **kwargs: Any) -> list[_models.Device]: + """Gets the identities of multiple devices from the IoT Hub identity registry. Not recommended. + Use the IoT Hub query API to retrieve device twin and device identity information. See + https://docs.microsoft.com/en-us/rest/api/iothub/service/queryiothub and + https://docs.microsoft.com/en-us/azure/iot-hub/iot-hub-devguide-query-language for more + information. + + :param top: The maximum number of device identities returned by the query. Any value outside + the range of 1-1000 is considered to be 1000. Default value is None. + :type top: int + :return: list of Device or the result of cls(response) + :rtype: list[~azure.iot.hub.protocol.models.Device] + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[list[_models.Device]] = kwargs.pop("cls", None) + + _request = build_get_devices_request( + top=top, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + deserialized = self._deserialize("[Device]", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def get_identity(self, id: str, **kwargs: Any) -> _models.Device: + """Gets a device from the identity registry of the IoT Hub. + + :param id: The unique identifier of the device. Required. + :type id: str + :return: Device or the result of cls(response) + :rtype: ~azure.iot.hub.protocol.models.Device + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.Device] = kwargs.pop("cls", None) + + _request = build_get_identity_request( + id=id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + deserialized = self._deserialize("Device", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def create_or_update_identity( + self, + id: str, + device: _models.Device, + if_match: Optional[str] = None, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Device: + """Creates or updates the identity of a device in the identity registry of the IoT Hub. + + :param id: The unique identifier of the device. Required. + :type id: str + :param device: The contents of the device identity. Required. + :type device: ~azure.iot.hub.protocol.models.Device + :param if_match: The string representing a weak ETag for the device identity, as per RFC7232. + This should not be set when creating a device, but may be set when updating a device. Default + value is None. + :type if_match: str + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: Device or the result of cls(response) + :rtype: ~azure.iot.hub.protocol.models.Device + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_or_update_identity( + self, + id: str, + device: IO[bytes], + if_match: Optional[str] = None, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Device: + """Creates or updates the identity of a device in the identity registry of the IoT Hub. + + :param id: The unique identifier of the device. Required. + :type id: str + :param device: The contents of the device identity. Required. + :type device: IO[bytes] + :param if_match: The string representing a weak ETag for the device identity, as per RFC7232. + This should not be set when creating a device, but may be set when updating a device. Default + value is None. + :type if_match: str + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: Device or the result of cls(response) + :rtype: ~azure.iot.hub.protocol.models.Device + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create_or_update_identity( + self, id: str, device: Union[_models.Device, IO[bytes]], if_match: Optional[str] = None, **kwargs: Any + ) -> _models.Device: + """Creates or updates the identity of a device in the identity registry of the IoT Hub. + + :param id: The unique identifier of the device. Required. + :type id: str + :param device: The contents of the device identity. Is either a Device type or a IO[bytes] + type. Required. + :type device: ~azure.iot.hub.protocol.models.Device or IO[bytes] + :param if_match: The string representing a weak ETag for the device identity, as per RFC7232. + This should not be set when creating a device, but may be set when updating a device. Default + value is None. + :type if_match: str + :return: Device or the result of cls(response) + :rtype: ~azure.iot.hub.protocol.models.Device + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.Device] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(device, (IOBase, bytes)): + _content = device + else: + _json = self._serialize.body(device, "Device") + + _request = build_create_or_update_identity_request( + id=id, + if_match=if_match, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + deserialized = self._deserialize("Device", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def delete_identity( # pylint: disable=inconsistent-return-statements + self, id: str, if_match: Optional[str] = None, **kwargs: Any + ) -> None: + """Deletes the identity of a device from the identity registry of the IoT Hub. + + :param id: The unique identifier of the device. Required. + :type id: str + :param if_match: The string representing a weak ETag for the device identity, as per RFC7232. + The delete operation is performed only if this ETag matches the value maintained by the server, + indicating that the device identity has not been modified since it was last retrieved. To force + an unconditional delete, set If-Match to the wildcard character (*). Default value is None. + :type if_match: str + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_delete_identity_request( + id=id, + if_match=if_match, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @distributed_trace + def get_twin(self, id: str, **kwargs: Any) -> _models.Twin: + """Gets the device twin. See + https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-device-twins for more information. + + :param id: The unique identifier of the device. Required. + :type id: str + :return: Twin or the result of cls(response) + :rtype: ~azure.iot.hub.protocol.models.Twin + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.Twin] = kwargs.pop("cls", None) + + _request = build_get_twin_request( + id=id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + deserialized = self._deserialize("Twin", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def replace_twin( + self, + id: str, + device_twin_info: _models.Twin, + if_match: Optional[str] = None, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Twin: + """Replaces the tags and desired properties of a device twin. See + https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-device-twins for more information. + + :param id: The unique identifier of the device. Required. + :type id: str + :param device_twin_info: The device twin info that will replace the existing info. Required. + :type device_twin_info: ~azure.iot.hub.protocol.models.Twin + :param if_match: The string representing a weak ETag for the device twin, as per RFC7232. It + determines if the replace operation should be carried out. Default value is None. + :type if_match: str + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: Twin or the result of cls(response) + :rtype: ~azure.iot.hub.protocol.models.Twin + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def replace_twin( + self, + id: str, + device_twin_info: IO[bytes], + if_match: Optional[str] = None, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Twin: + """Replaces the tags and desired properties of a device twin. See + https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-device-twins for more information. + + :param id: The unique identifier of the device. Required. + :type id: str + :param device_twin_info: The device twin info that will replace the existing info. Required. + :type device_twin_info: IO[bytes] + :param if_match: The string representing a weak ETag for the device twin, as per RFC7232. It + determines if the replace operation should be carried out. Default value is None. + :type if_match: str + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: Twin or the result of cls(response) + :rtype: ~azure.iot.hub.protocol.models.Twin + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def replace_twin( + self, id: str, device_twin_info: Union[_models.Twin, IO[bytes]], if_match: Optional[str] = None, **kwargs: Any + ) -> _models.Twin: + """Replaces the tags and desired properties of a device twin. See + https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-device-twins for more information. + + :param id: The unique identifier of the device. Required. + :type id: str + :param device_twin_info: The device twin info that will replace the existing info. Is either a + Twin type or a IO[bytes] type. Required. + :type device_twin_info: ~azure.iot.hub.protocol.models.Twin or IO[bytes] + :param if_match: The string representing a weak ETag for the device twin, as per RFC7232. It + determines if the replace operation should be carried out. Default value is None. + :type if_match: str + :return: Twin or the result of cls(response) + :rtype: ~azure.iot.hub.protocol.models.Twin + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.Twin] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(device_twin_info, (IOBase, bytes)): + _content = device_twin_info + else: + _json = self._serialize.body(device_twin_info, "Twin") + + _request = build_replace_twin_request( + id=id, + if_match=if_match, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + deserialized = self._deserialize("Twin", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def update_twin( + self, + id: str, + device_twin_info: _models.Twin, + if_match: Optional[str] = None, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Twin: + """Updates the tags and desired properties of a device twin. See + https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-device-twins for more information. + + :param id: The unique identifier of the device. Required. + :type id: str + :param device_twin_info: The device twin info containing the tags and desired properties to be + updated. Required. + :type device_twin_info: ~azure.iot.hub.protocol.models.Twin + :param if_match: The string representing a weak ETag for the device twin, as per RFC7232. It + determines if the update operation should be carried out. Default value is None. + :type if_match: str + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: Twin or the result of cls(response) + :rtype: ~azure.iot.hub.protocol.models.Twin + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def update_twin( + self, + id: str, + device_twin_info: IO[bytes], + if_match: Optional[str] = None, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Twin: + """Updates the tags and desired properties of a device twin. See + https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-device-twins for more information. + + :param id: The unique identifier of the device. Required. + :type id: str + :param device_twin_info: The device twin info containing the tags and desired properties to be + updated. Required. + :type device_twin_info: IO[bytes] + :param if_match: The string representing a weak ETag for the device twin, as per RFC7232. It + determines if the update operation should be carried out. Default value is None. + :type if_match: str + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: Twin or the result of cls(response) + :rtype: ~azure.iot.hub.protocol.models.Twin + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def update_twin( + self, id: str, device_twin_info: Union[_models.Twin, IO[bytes]], if_match: Optional[str] = None, **kwargs: Any + ) -> _models.Twin: + """Updates the tags and desired properties of a device twin. See + https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-device-twins for more information. + + :param id: The unique identifier of the device. Required. + :type id: str + :param device_twin_info: The device twin info containing the tags and desired properties to be + updated. Is either a Twin type or a IO[bytes] type. Required. + :type device_twin_info: ~azure.iot.hub.protocol.models.Twin or IO[bytes] + :param if_match: The string representing a weak ETag for the device twin, as per RFC7232. It + determines if the update operation should be carried out. Default value is None. + :type if_match: str + :return: Twin or the result of cls(response) + :rtype: ~azure.iot.hub.protocol.models.Twin + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.Twin] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(device_twin_info, (IOBase, bytes)): + _content = device_twin_info + else: + _json = self._serialize.body(device_twin_info, "Twin") + + _request = build_update_twin_request( + id=id, + if_match=if_match, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + deserialized = self._deserialize("Twin", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def invoke_method( + self, + device_id: str, + direct_method_request: _models.CloudToDeviceMethod, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.CloudToDeviceMethodResult: + """Invokes a direct method on a device. See + https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-direct-methods for more information. + + :param device_id: The unique identifier of the device. Required. + :type device_id: str + :param direct_method_request: The parameters to execute a direct method on the device. + Required. + :type direct_method_request: ~azure.iot.hub.protocol.models.CloudToDeviceMethod + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: CloudToDeviceMethodResult or the result of cls(response) + :rtype: ~azure.iot.hub.protocol.models.CloudToDeviceMethodResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def invoke_method( + self, device_id: str, direct_method_request: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.CloudToDeviceMethodResult: + """Invokes a direct method on a device. See + https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-direct-methods for more information. + + :param device_id: The unique identifier of the device. Required. + :type device_id: str + :param direct_method_request: The parameters to execute a direct method on the device. + Required. + :type direct_method_request: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: CloudToDeviceMethodResult or the result of cls(response) + :rtype: ~azure.iot.hub.protocol.models.CloudToDeviceMethodResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def invoke_method( + self, device_id: str, direct_method_request: Union[_models.CloudToDeviceMethod, IO[bytes]], **kwargs: Any + ) -> _models.CloudToDeviceMethodResult: + """Invokes a direct method on a device. See + https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-direct-methods for more information. + + :param device_id: The unique identifier of the device. Required. + :type device_id: str + :param direct_method_request: The parameters to execute a direct method on the device. Is + either a CloudToDeviceMethod type or a IO[bytes] type. Required. + :type direct_method_request: ~azure.iot.hub.protocol.models.CloudToDeviceMethod or IO[bytes] + :return: CloudToDeviceMethodResult or the result of cls(response) + :rtype: ~azure.iot.hub.protocol.models.CloudToDeviceMethodResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.CloudToDeviceMethodResult] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(direct_method_request, (IOBase, bytes)): + _content = direct_method_request + else: + _json = self._serialize.body(direct_method_request, "CloudToDeviceMethod") + + _request = build_invoke_method_request( + device_id=device_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + deserialized = self._deserialize("CloudToDeviceMethodResult", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore diff --git a/src/azure/iot/hub/protocol/operations/_digital_twin_operations.py b/src/azure/iot/hub/protocol/operations/_digital_twin_operations.py new file mode 100644 index 0000000..06fd874 --- /dev/null +++ b/src/azure/iot/hub/protocol/operations/_digital_twin_operations.py @@ -0,0 +1,550 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from collections.abc import MutableMapping +from io import IOBase +from typing import Any, Callable, IO, Optional, TypeVar, Union, overload + +from azure.core import PipelineClient +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.rest import HttpRequest, HttpResponse +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict + +from .. import models as _models +from .._configuration import IotHubGatewayServiceAPIsConfiguration +from .._utils.serialization import Deserializer, Serializer + +JSON = MutableMapping[str, Any] +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_get_digital_twin_request(id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-04-12")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/digitaltwins/{id}") + path_format_arguments = { + "id": _SERIALIZER.url("id", id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_update_digital_twin_request(id: str, *, if_match: Optional[str] = None, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-04-12")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + # Construct URL + _url = kwargs.pop("template_url", "/digitaltwins/{id}") + path_format_arguments = { + "id": _SERIALIZER.url("id", id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if if_match is not None: + _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + + return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_invoke_root_level_command_request( + id: str, + command_name: str, + *, + json: JSON, + connect_timeout_in_seconds: Optional[int] = None, + response_timeout_in_seconds: Optional[int] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-04-12")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/digitaltwins/{id}/commands/{commandName}") + path_format_arguments = { + "id": _SERIALIZER.url("id", id, "str"), + "commandName": _SERIALIZER.url("command_name", command_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if connect_timeout_in_seconds is not None: + _params["connectTimeoutInSeconds"] = _SERIALIZER.query( + "connect_timeout_in_seconds", connect_timeout_in_seconds, "int" + ) + if response_timeout_in_seconds is not None: + _params["responseTimeoutInSeconds"] = _SERIALIZER.query( + "response_timeout_in_seconds", response_timeout_in_seconds, "int" + ) + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, json=json, **kwargs) + + +def build_invoke_component_command_request( + id: str, + component_path: str, + command_name: str, + *, + json: JSON, + connect_timeout_in_seconds: Optional[int] = None, + response_timeout_in_seconds: Optional[int] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-04-12")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/digitaltwins/{id}/components/{componentPath}/commands/{commandName}") + path_format_arguments = { + "id": _SERIALIZER.url("id", id, "str"), + "componentPath": _SERIALIZER.url("component_path", component_path, "str"), + "commandName": _SERIALIZER.url("command_name", command_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if connect_timeout_in_seconds is not None: + _params["connectTimeoutInSeconds"] = _SERIALIZER.query( + "connect_timeout_in_seconds", connect_timeout_in_seconds, "int" + ) + if response_timeout_in_seconds is not None: + _params["responseTimeoutInSeconds"] = _SERIALIZER.query( + "response_timeout_in_seconds", response_timeout_in_seconds, "int" + ) + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, json=json, **kwargs) + + +class DigitalTwinOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.iot.hub.protocol.IotHubGatewayServiceAPIs`'s + :attr:`digital_twin` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: IotHubGatewayServiceAPIsConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def get_digital_twin(self, id: str, **kwargs: Any) -> JSON: + """Gets a digital twin. + + Gets a digital twin. + + :param id: Digital Twin ID. Required. + :type id: str + :return: JSON or the result of cls(response) + :rtype: JSON + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[JSON] = kwargs.pop("cls", None) + + _request = build_get_digital_twin_request( + id=id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + response_headers = {} + response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) + + deserialized = self._deserialize("object", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @overload + def update_digital_twin( + self, + id: str, + digital_twin_patch: list[JSON], + if_match: Optional[str] = None, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> None: + """Updates a digital twin. + + Updates a digital twin. + + :param id: Digital Twin ID. Required. + :type id: str + :param digital_twin_patch: json-patch contents to update. Required. + :type digital_twin_patch: list[JSON] + :param if_match: Default value is None. + :type if_match: str + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def update_digital_twin( + self, + id: str, + digital_twin_patch: IO[bytes], + if_match: Optional[str] = None, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> None: + """Updates a digital twin. + + Updates a digital twin. + + :param id: Digital Twin ID. Required. + :type id: str + :param digital_twin_patch: json-patch contents to update. Required. + :type digital_twin_patch: IO[bytes] + :param if_match: Default value is None. + :type if_match: str + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def update_digital_twin( # pylint: disable=inconsistent-return-statements + self, id: str, digital_twin_patch: Union[list[JSON], IO[bytes]], if_match: Optional[str] = None, **kwargs: Any + ) -> None: + """Updates a digital twin. + + Updates a digital twin. + + :param id: Digital Twin ID. Required. + :type id: str + :param digital_twin_patch: json-patch contents to update. Is either a [JSON] type or a + IO[bytes] type. Required. + :type digital_twin_patch: list[JSON] or IO[bytes] + :param if_match: Default value is None. + :type if_match: str + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[None] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(digital_twin_patch, (IOBase, bytes)): + _content = digital_twin_patch + else: + _json = self._serialize.body(digital_twin_patch, "[object]") + + _request = build_update_digital_twin_request( + id=id, + if_match=if_match, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + response_headers = {} + response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + + if cls: + return cls(pipeline_response, None, response_headers) # type: ignore + + @distributed_trace + def invoke_root_level_command( + self, + id: str, + command_name: str, + payload: JSON, + connect_timeout_in_seconds: Optional[int] = None, + response_timeout_in_seconds: Optional[int] = None, + **kwargs: Any + ) -> JSON: + """Invoke a digital twin root level command. + + Invoke a digital twin root level command. + + :param id: Required. + :type id: str + :param command_name: Required. + :type command_name: str + :param payload: Required. + :type payload: JSON + :param connect_timeout_in_seconds: Maximum interval of time, in seconds, that the digital twin + command will wait for the answer. Default value is None. + :type connect_timeout_in_seconds: int + :param response_timeout_in_seconds: Maximum interval of time, in seconds, that the digital twin + command will wait for the answer. Default value is None. + :type response_timeout_in_seconds: int + :return: JSON or the result of cls(response) + :rtype: JSON + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: str = kwargs.pop("content_type", _headers.pop("Content-Type", "application/json")) + cls: ClsType[JSON] = kwargs.pop("cls", None) + + _json = self._serialize.body(payload, "object") + + _request = build_invoke_root_level_command_request( + id=id, + command_name=command_name, + connect_timeout_in_seconds=connect_timeout_in_seconds, + response_timeout_in_seconds=response_timeout_in_seconds, + api_version=api_version, + content_type=content_type, + json=_json, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + response_headers = {} + response_headers["x-ms-command-statuscode"] = self._deserialize( + "int", response.headers.get("x-ms-command-statuscode") + ) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + + deserialized = self._deserialize("object", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def invoke_component_command( + self, + id: str, + component_path: str, + command_name: str, + payload: JSON, + connect_timeout_in_seconds: Optional[int] = None, + response_timeout_in_seconds: Optional[int] = None, + **kwargs: Any + ) -> JSON: + """Invoke a digital twin command. + + Invoke a digital twin command. + + :param id: Required. + :type id: str + :param component_path: Required. + :type component_path: str + :param command_name: Required. + :type command_name: str + :param payload: Required. + :type payload: JSON + :param connect_timeout_in_seconds: Maximum interval of time, in seconds, that the digital twin + command will wait for the answer. Default value is None. + :type connect_timeout_in_seconds: int + :param response_timeout_in_seconds: Maximum interval of time, in seconds, that the digital twin + command will wait for the answer. Default value is None. + :type response_timeout_in_seconds: int + :return: JSON or the result of cls(response) + :rtype: JSON + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: str = kwargs.pop("content_type", _headers.pop("Content-Type", "application/json")) + cls: ClsType[JSON] = kwargs.pop("cls", None) + + _json = self._serialize.body(payload, "object") + + _request = build_invoke_component_command_request( + id=id, + component_path=component_path, + command_name=command_name, + connect_timeout_in_seconds=connect_timeout_in_seconds, + response_timeout_in_seconds=response_timeout_in_seconds, + api_version=api_version, + content_type=content_type, + json=_json, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + response_headers = {} + response_headers["x-ms-command-statuscode"] = self._deserialize( + "int", response.headers.get("x-ms-command-statuscode") + ) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + + deserialized = self._deserialize("object", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore diff --git a/src/azure/iot/hub/protocol/operations/_jobs_operations.py b/src/azure/iot/hub/protocol/operations/_jobs_operations.py new file mode 100644 index 0000000..06f7f47 --- /dev/null +++ b/src/azure/iot/hub/protocol/operations/_jobs_operations.py @@ -0,0 +1,771 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from collections.abc import MutableMapping +from io import IOBase +from typing import Any, Callable, IO, Optional, TypeVar, Union, overload + +from azure.core import PipelineClient +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.rest import HttpRequest, HttpResponse +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict + +from .. import models as _models +from .._configuration import IotHubGatewayServiceAPIsConfiguration +from .._utils.serialization import Deserializer, Serializer + +JSON = MutableMapping[str, Any] +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_create_import_export_job_request(**kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-04-12")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/jobs/create") + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_get_import_export_jobs_request(**kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-04-12")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/jobs") + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_get_import_export_job_request(id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-04-12")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/jobs/{id}") + path_format_arguments = { + "id": _SERIALIZER.url("id", id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_cancel_import_export_job_request(id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-04-12")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/jobs/{id}") + path_format_arguments = { + "id": _SERIALIZER.url("id", id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_get_scheduled_job_request(id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-04-12")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/jobs/v2/{id}") + path_format_arguments = { + "id": _SERIALIZER.url("id", id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_create_scheduled_job_request(id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-04-12")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/jobs/v2/{id}") + path_format_arguments = { + "id": _SERIALIZER.url("id", id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_cancel_scheduled_job_request(id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-04-12")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/jobs/v2/{id}/cancel") + path_format_arguments = { + "id": _SERIALIZER.url("id", id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_query_scheduled_jobs_request( + *, job_type: Optional[str] = None, job_status: Optional[str] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-04-12")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/jobs/v2/query") + + # Construct parameters + if job_type is not None: + _params["jobType"] = _SERIALIZER.query("job_type", job_type, "str") + if job_status is not None: + _params["jobStatus"] = _SERIALIZER.query("job_status", job_status, "str") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class JobsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.iot.hub.protocol.IotHubGatewayServiceAPIs`'s + :attr:`jobs` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: IotHubGatewayServiceAPIsConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @overload + def create_import_export_job( + self, job_properties: _models.JobProperties, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.JobProperties: + """Creates a new import or export job on the IoT Hub. See + https://docs.microsoft.com/en-us/azure/iot-hub/iot-hub-devguide-identity-registry#import-and-export-device-identities + for more information. + + :param job_properties: The job specifications. Required. + :type job_properties: ~azure.iot.hub.protocol.models.JobProperties + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: JobProperties or the result of cls(response) + :rtype: ~azure.iot.hub.protocol.models.JobProperties + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_import_export_job( + self, job_properties: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.JobProperties: + """Creates a new import or export job on the IoT Hub. See + https://docs.microsoft.com/en-us/azure/iot-hub/iot-hub-devguide-identity-registry#import-and-export-device-identities + for more information. + + :param job_properties: The job specifications. Required. + :type job_properties: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: JobProperties or the result of cls(response) + :rtype: ~azure.iot.hub.protocol.models.JobProperties + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create_import_export_job( + self, job_properties: Union[_models.JobProperties, IO[bytes]], **kwargs: Any + ) -> _models.JobProperties: + """Creates a new import or export job on the IoT Hub. See + https://docs.microsoft.com/en-us/azure/iot-hub/iot-hub-devguide-identity-registry#import-and-export-device-identities + for more information. + + :param job_properties: The job specifications. Is either a JobProperties type or a IO[bytes] + type. Required. + :type job_properties: ~azure.iot.hub.protocol.models.JobProperties or IO[bytes] + :return: JobProperties or the result of cls(response) + :rtype: ~azure.iot.hub.protocol.models.JobProperties + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.JobProperties] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(job_properties, (IOBase, bytes)): + _content = job_properties + else: + _json = self._serialize.body(job_properties, "JobProperties") + + _request = build_create_import_export_job_request( + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + deserialized = self._deserialize("JobProperties", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def get_import_export_jobs(self, **kwargs: Any) -> list[_models.JobProperties]: + """Gets the status of all import and export jobs in the IoT Hub. See + https://docs.microsoft.com/en-us/azure/iot-hub/iot-hub-devguide-identity-registry#import-and-export-device-identities + for more information. + + :return: list of JobProperties or the result of cls(response) + :rtype: list[~azure.iot.hub.protocol.models.JobProperties] + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[list[_models.JobProperties]] = kwargs.pop("cls", None) + + _request = build_get_import_export_jobs_request( + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + deserialized = self._deserialize("[JobProperties]", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def get_import_export_job(self, id: str, **kwargs: Any) -> _models.JobProperties: + """Gets the status of an import or export job in the IoT Hub. See + https://docs.microsoft.com/en-us/azure/iot-hub/iot-hub-devguide-identity-registry#import-and-export-device-identities + for more information. + + :param id: The unique identifier of the job. Required. + :type id: str + :return: JobProperties or the result of cls(response) + :rtype: ~azure.iot.hub.protocol.models.JobProperties + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.JobProperties] = kwargs.pop("cls", None) + + _request = build_get_import_export_job_request( + id=id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + deserialized = self._deserialize("JobProperties", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def cancel_import_export_job(self, id: str, **kwargs: Any) -> Optional[JSON]: + """Cancels an import or export job in the IoT Hub. + + :param id: The unique identifier of the job. Required. + :type id: str + :return: JSON or None or the result of cls(response) + :rtype: JSON or None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[Optional[JSON]] = kwargs.pop("cls", None) + + _request = build_cancel_import_export_job_request( + id=id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + deserialized = None + if response.status_code == 200: + deserialized = self._deserialize("object", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def get_scheduled_job(self, id: str, **kwargs: Any) -> _models.JobResponse: + """Gets details of a scheduled job from the IoT Hub. See + https://docs.microsoft.com/en-us/azure/iot-hub/iot-hub-devguide-jobs for more information. + + :param id: The unique identifier of the job. Required. + :type id: str + :return: JobResponse or the result of cls(response) + :rtype: ~azure.iot.hub.protocol.models.JobResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.JobResponse] = kwargs.pop("cls", None) + + _request = build_get_scheduled_job_request( + id=id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + deserialized = self._deserialize("JobResponse", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def create_scheduled_job( + self, id: str, job_request: _models.JobRequest, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.JobResponse: + """Creates a new job to schedule twin updates or direct methods on the IoT Hub at a scheduled + time. See https://docs.microsoft.com/en-us/azure/iot-hub/iot-hub-devguide-jobs for more + information. + + :param id: The unique identifier of the job. Required. + :type id: str + :param job_request: The job request info. Required. + :type job_request: ~azure.iot.hub.protocol.models.JobRequest + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: JobResponse or the result of cls(response) + :rtype: ~azure.iot.hub.protocol.models.JobResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_scheduled_job( + self, id: str, job_request: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.JobResponse: + """Creates a new job to schedule twin updates or direct methods on the IoT Hub at a scheduled + time. See https://docs.microsoft.com/en-us/azure/iot-hub/iot-hub-devguide-jobs for more + information. + + :param id: The unique identifier of the job. Required. + :type id: str + :param job_request: The job request info. Required. + :type job_request: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: JobResponse or the result of cls(response) + :rtype: ~azure.iot.hub.protocol.models.JobResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create_scheduled_job( + self, id: str, job_request: Union[_models.JobRequest, IO[bytes]], **kwargs: Any + ) -> _models.JobResponse: + """Creates a new job to schedule twin updates or direct methods on the IoT Hub at a scheduled + time. See https://docs.microsoft.com/en-us/azure/iot-hub/iot-hub-devguide-jobs for more + information. + + :param id: The unique identifier of the job. Required. + :type id: str + :param job_request: The job request info. Is either a JobRequest type or a IO[bytes] type. + Required. + :type job_request: ~azure.iot.hub.protocol.models.JobRequest or IO[bytes] + :return: JobResponse or the result of cls(response) + :rtype: ~azure.iot.hub.protocol.models.JobResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.JobResponse] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(job_request, (IOBase, bytes)): + _content = job_request + else: + _json = self._serialize.body(job_request, "JobRequest") + + _request = build_create_scheduled_job_request( + id=id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + deserialized = self._deserialize("JobResponse", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def cancel_scheduled_job(self, id: str, **kwargs: Any) -> _models.JobResponse: + """Cancels a scheduled job on the IoT Hub. See + https://docs.microsoft.com/en-us/azure/iot-hub/iot-hub-devguide-jobs for more information. + + :param id: The unique identifier of the job. Required. + :type id: str + :return: JobResponse or the result of cls(response) + :rtype: ~azure.iot.hub.protocol.models.JobResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.JobResponse] = kwargs.pop("cls", None) + + _request = build_cancel_scheduled_job_request( + id=id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + deserialized = self._deserialize("JobResponse", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def query_scheduled_jobs( + self, job_type: Optional[str] = None, job_status: Optional[str] = None, **kwargs: Any + ) -> _models.QueryResult: + """Gets the information about jobs using an IoT Hub query. See + https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-query-language for more information. + + :param job_type: The job type. See + https://docs.microsoft.com/en-us/azure/iot-hub/iot-hub-devguide-jobs#querying-for-progress-on-jobs + for a list of possible job types. Default value is None. + :type job_type: str + :param job_status: The job status. See + https://docs.microsoft.com/en-us/azure/iot-hub/iot-hub-devguide-jobs#querying-for-progress-on-jobs + for a list of possible statuses. Default value is None. + :type job_status: str + :return: QueryResult or the result of cls(response) + :rtype: ~azure.iot.hub.protocol.models.QueryResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.QueryResult] = kwargs.pop("cls", None) + + _request = build_query_scheduled_jobs_request( + job_type=job_type, + job_status=job_status, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + deserialized = self._deserialize("QueryResult", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore diff --git a/src/azure/iot/hub/protocol/operations/_modules_operations.py b/src/azure/iot/hub/protocol/operations/_modules_operations.py new file mode 100644 index 0000000..fa903c8 --- /dev/null +++ b/src/azure/iot/hub/protocol/operations/_modules_operations.py @@ -0,0 +1,1043 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from collections.abc import MutableMapping +from io import IOBase +from typing import Any, Callable, IO, Optional, TypeVar, Union, overload + +from azure.core import PipelineClient +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.rest import HttpRequest, HttpResponse +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict + +from .. import models as _models +from .._configuration import IotHubGatewayServiceAPIsConfiguration +from .._utils.serialization import Deserializer, Serializer + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_get_twin_request(id: str, mid: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-04-12")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/twins/{id}/modules/{mid}") + path_format_arguments = { + "id": _SERIALIZER.url("id", id, "str"), + "mid": _SERIALIZER.url("mid", mid, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_replace_twin_request(id: str, mid: str, *, if_match: Optional[str] = None, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-04-12")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/twins/{id}/modules/{mid}") + path_format_arguments = { + "id": _SERIALIZER.url("id", id, "str"), + "mid": _SERIALIZER.url("mid", mid, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if if_match is not None: + _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_update_twin_request(id: str, mid: str, *, if_match: Optional[str] = None, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-04-12")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/twins/{id}/modules/{mid}") + path_format_arguments = { + "id": _SERIALIZER.url("id", id, "str"), + "mid": _SERIALIZER.url("mid", mid, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if if_match is not None: + _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_get_modules_on_device_request(id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-04-12")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/devices/{id}/modules") + path_format_arguments = { + "id": _SERIALIZER.url("id", id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_get_identity_request(id: str, mid: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-04-12")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/devices/{id}/modules/{mid}") + path_format_arguments = { + "id": _SERIALIZER.url("id", id, "str"), + "mid": _SERIALIZER.url("mid", mid, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_create_or_update_identity_request( + id: str, mid: str, *, if_match: Optional[str] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-04-12")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/devices/{id}/modules/{mid}") + path_format_arguments = { + "id": _SERIALIZER.url("id", id, "str"), + "mid": _SERIALIZER.url("mid", mid, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if if_match is not None: + _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_delete_identity_request(id: str, mid: str, *, if_match: Optional[str] = None, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-04-12")) + # Construct URL + _url = kwargs.pop("template_url", "/devices/{id}/modules/{mid}") + path_format_arguments = { + "id": _SERIALIZER.url("id", id, "str"), + "mid": _SERIALIZER.url("mid", mid, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if if_match is not None: + _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_invoke_method_request(device_id: str, module_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-04-12")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/twins/{deviceId}/modules/{moduleId}/methods") + path_format_arguments = { + "deviceId": _SERIALIZER.url("device_id", device_id, "str"), + "moduleId": _SERIALIZER.url("module_id", module_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +class ModulesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.iot.hub.protocol.IotHubGatewayServiceAPIs`'s + :attr:`modules` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: IotHubGatewayServiceAPIsConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def get_twin(self, id: str, mid: str, **kwargs: Any) -> _models.Twin: + """Gets the module twin. See + https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-device-twins for more information. + + :param id: The unique identifier of the device. Required. + :type id: str + :param mid: The unique identifier of the module. Required. + :type mid: str + :return: Twin or the result of cls(response) + :rtype: ~azure.iot.hub.protocol.models.Twin + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.Twin] = kwargs.pop("cls", None) + + _request = build_get_twin_request( + id=id, + mid=mid, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + deserialized = self._deserialize("Twin", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def replace_twin( + self, + id: str, + mid: str, + device_twin_info: _models.Twin, + if_match: Optional[str] = None, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Twin: + """Replaces the tags and desired properties of a module twin. See + https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-device-twins for more information. + + :param id: The unique identifier of the device. Required. + :type id: str + :param mid: The unique identifier of the module. Required. + :type mid: str + :param device_twin_info: The module twin info that will replace the existing info. Required. + :type device_twin_info: ~azure.iot.hub.protocol.models.Twin + :param if_match: The string representing a weak ETag for the device twin, as per RFC7232. It + determines if the replace operation should be carried out. Default value is None. + :type if_match: str + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: Twin or the result of cls(response) + :rtype: ~azure.iot.hub.protocol.models.Twin + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def replace_twin( + self, + id: str, + mid: str, + device_twin_info: IO[bytes], + if_match: Optional[str] = None, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Twin: + """Replaces the tags and desired properties of a module twin. See + https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-device-twins for more information. + + :param id: The unique identifier of the device. Required. + :type id: str + :param mid: The unique identifier of the module. Required. + :type mid: str + :param device_twin_info: The module twin info that will replace the existing info. Required. + :type device_twin_info: IO[bytes] + :param if_match: The string representing a weak ETag for the device twin, as per RFC7232. It + determines if the replace operation should be carried out. Default value is None. + :type if_match: str + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: Twin or the result of cls(response) + :rtype: ~azure.iot.hub.protocol.models.Twin + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def replace_twin( + self, + id: str, + mid: str, + device_twin_info: Union[_models.Twin, IO[bytes]], + if_match: Optional[str] = None, + **kwargs: Any + ) -> _models.Twin: + """Replaces the tags and desired properties of a module twin. See + https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-device-twins for more information. + + :param id: The unique identifier of the device. Required. + :type id: str + :param mid: The unique identifier of the module. Required. + :type mid: str + :param device_twin_info: The module twin info that will replace the existing info. Is either a + Twin type or a IO[bytes] type. Required. + :type device_twin_info: ~azure.iot.hub.protocol.models.Twin or IO[bytes] + :param if_match: The string representing a weak ETag for the device twin, as per RFC7232. It + determines if the replace operation should be carried out. Default value is None. + :type if_match: str + :return: Twin or the result of cls(response) + :rtype: ~azure.iot.hub.protocol.models.Twin + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.Twin] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(device_twin_info, (IOBase, bytes)): + _content = device_twin_info + else: + _json = self._serialize.body(device_twin_info, "Twin") + + _request = build_replace_twin_request( + id=id, + mid=mid, + if_match=if_match, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + deserialized = self._deserialize("Twin", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def update_twin( + self, + id: str, + mid: str, + device_twin_info: _models.Twin, + if_match: Optional[str] = None, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Twin: + """Updates the tags and desired properties of a module twin. See + https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-device-twins for more information. + + :param id: The unique identifier of the device. Required. + :type id: str + :param mid: The unique identifier of the module. Required. + :type mid: str + :param device_twin_info: The module twin info containing the tags and desired properties to be + updated. Required. + :type device_twin_info: ~azure.iot.hub.protocol.models.Twin + :param if_match: The string representing a weak ETag for the device twin, as per RFC7232. It + determines if the update operation should be carried out. Default value is None. + :type if_match: str + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: Twin or the result of cls(response) + :rtype: ~azure.iot.hub.protocol.models.Twin + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def update_twin( + self, + id: str, + mid: str, + device_twin_info: IO[bytes], + if_match: Optional[str] = None, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Twin: + """Updates the tags and desired properties of a module twin. See + https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-device-twins for more information. + + :param id: The unique identifier of the device. Required. + :type id: str + :param mid: The unique identifier of the module. Required. + :type mid: str + :param device_twin_info: The module twin info containing the tags and desired properties to be + updated. Required. + :type device_twin_info: IO[bytes] + :param if_match: The string representing a weak ETag for the device twin, as per RFC7232. It + determines if the update operation should be carried out. Default value is None. + :type if_match: str + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: Twin or the result of cls(response) + :rtype: ~azure.iot.hub.protocol.models.Twin + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def update_twin( + self, + id: str, + mid: str, + device_twin_info: Union[_models.Twin, IO[bytes]], + if_match: Optional[str] = None, + **kwargs: Any + ) -> _models.Twin: + """Updates the tags and desired properties of a module twin. See + https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-device-twins for more information. + + :param id: The unique identifier of the device. Required. + :type id: str + :param mid: The unique identifier of the module. Required. + :type mid: str + :param device_twin_info: The module twin info containing the tags and desired properties to be + updated. Is either a Twin type or a IO[bytes] type. Required. + :type device_twin_info: ~azure.iot.hub.protocol.models.Twin or IO[bytes] + :param if_match: The string representing a weak ETag for the device twin, as per RFC7232. It + determines if the update operation should be carried out. Default value is None. + :type if_match: str + :return: Twin or the result of cls(response) + :rtype: ~azure.iot.hub.protocol.models.Twin + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.Twin] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(device_twin_info, (IOBase, bytes)): + _content = device_twin_info + else: + _json = self._serialize.body(device_twin_info, "Twin") + + _request = build_update_twin_request( + id=id, + mid=mid, + if_match=if_match, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + deserialized = self._deserialize("Twin", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def get_modules_on_device(self, id: str, **kwargs: Any) -> list[_models.Module]: + """Gets all the module identities on the device. + + :param id: The unique identifier of the device. Required. + :type id: str + :return: list of Module or the result of cls(response) + :rtype: list[~azure.iot.hub.protocol.models.Module] + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[list[_models.Module]] = kwargs.pop("cls", None) + + _request = build_get_modules_on_device_request( + id=id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + deserialized = self._deserialize("[Module]", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def get_identity(self, id: str, mid: str, **kwargs: Any) -> _models.Module: + """Gets a module identity on the device. + + :param id: The unique identifier of the device. Required. + :type id: str + :param mid: The unique identifier of the module. Required. + :type mid: str + :return: Module or the result of cls(response) + :rtype: ~azure.iot.hub.protocol.models.Module + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.Module] = kwargs.pop("cls", None) + + _request = build_get_identity_request( + id=id, + mid=mid, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + deserialized = self._deserialize("Module", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def create_or_update_identity( + self, + id: str, + mid: str, + module: _models.Module, + if_match: Optional[str] = None, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Module: + """Creates or updates the module identity for a device in the IoT Hub. The moduleId and + generationId cannot be updated by the user. + + :param id: The unique identifier of the device. Required. + :type id: str + :param mid: The unique identifier of the module. Required. + :type mid: str + :param module: The module identity. Required. + :type module: ~azure.iot.hub.protocol.models.Module + :param if_match: The string representing a weak ETag for the module, as per RFC7232. This + should not be set when creating a module, but may be set when updating a module. Default value + is None. + :type if_match: str + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: Module or the result of cls(response) + :rtype: ~azure.iot.hub.protocol.models.Module + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_or_update_identity( + self, + id: str, + mid: str, + module: IO[bytes], + if_match: Optional[str] = None, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Module: + """Creates or updates the module identity for a device in the IoT Hub. The moduleId and + generationId cannot be updated by the user. + + :param id: The unique identifier of the device. Required. + :type id: str + :param mid: The unique identifier of the module. Required. + :type mid: str + :param module: The module identity. Required. + :type module: IO[bytes] + :param if_match: The string representing a weak ETag for the module, as per RFC7232. This + should not be set when creating a module, but may be set when updating a module. Default value + is None. + :type if_match: str + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: Module or the result of cls(response) + :rtype: ~azure.iot.hub.protocol.models.Module + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create_or_update_identity( + self, id: str, mid: str, module: Union[_models.Module, IO[bytes]], if_match: Optional[str] = None, **kwargs: Any + ) -> _models.Module: + """Creates or updates the module identity for a device in the IoT Hub. The moduleId and + generationId cannot be updated by the user. + + :param id: The unique identifier of the device. Required. + :type id: str + :param mid: The unique identifier of the module. Required. + :type mid: str + :param module: The module identity. Is either a Module type or a IO[bytes] type. Required. + :type module: ~azure.iot.hub.protocol.models.Module or IO[bytes] + :param if_match: The string representing a weak ETag for the module, as per RFC7232. This + should not be set when creating a module, but may be set when updating a module. Default value + is None. + :type if_match: str + :return: Module or the result of cls(response) + :rtype: ~azure.iot.hub.protocol.models.Module + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.Module] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(module, (IOBase, bytes)): + _content = module + else: + _json = self._serialize.body(module, "Module") + + _request = build_create_or_update_identity_request( + id=id, + mid=mid, + if_match=if_match, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + deserialized = self._deserialize("Module", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def delete_identity( # pylint: disable=inconsistent-return-statements + self, id: str, mid: str, if_match: Optional[str] = None, **kwargs: Any + ) -> None: + """Deletes the module identity for a device in the IoT Hub. + + :param id: The unique identifier of the deivce. Required. + :type id: str + :param mid: The unique identifier of the module. Required. + :type mid: str + :param if_match: The string representing a weak ETag for the module, as per RFC7232. The delete + operation is performed only if this ETag matches the value maintained by the server, indicating + that the module has not been modified since it was last retrieved. To force an unconditional + delete, set If-Match to the wildcard character (*). Default value is None. + :type if_match: str + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_delete_identity_request( + id=id, + mid=mid, + if_match=if_match, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @overload + def invoke_method( + self, + device_id: str, + module_id: str, + direct_method_request: _models.CloudToDeviceMethod, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.CloudToDeviceMethodResult: + """Invokes a direct method on a module of a device. See + https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-direct-methods for more information. + + :param device_id: The unique identifier of the device. Required. + :type device_id: str + :param module_id: The unique identifier of the module. Required. + :type module_id: str + :param direct_method_request: The parameters to execute a direct method on the module. + Required. + :type direct_method_request: ~azure.iot.hub.protocol.models.CloudToDeviceMethod + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: CloudToDeviceMethodResult or the result of cls(response) + :rtype: ~azure.iot.hub.protocol.models.CloudToDeviceMethodResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def invoke_method( + self, + device_id: str, + module_id: str, + direct_method_request: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.CloudToDeviceMethodResult: + """Invokes a direct method on a module of a device. See + https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-direct-methods for more information. + + :param device_id: The unique identifier of the device. Required. + :type device_id: str + :param module_id: The unique identifier of the module. Required. + :type module_id: str + :param direct_method_request: The parameters to execute a direct method on the module. + Required. + :type direct_method_request: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: CloudToDeviceMethodResult or the result of cls(response) + :rtype: ~azure.iot.hub.protocol.models.CloudToDeviceMethodResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def invoke_method( + self, + device_id: str, + module_id: str, + direct_method_request: Union[_models.CloudToDeviceMethod, IO[bytes]], + **kwargs: Any + ) -> _models.CloudToDeviceMethodResult: + """Invokes a direct method on a module of a device. See + https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-direct-methods for more information. + + :param device_id: The unique identifier of the device. Required. + :type device_id: str + :param module_id: The unique identifier of the module. Required. + :type module_id: str + :param direct_method_request: The parameters to execute a direct method on the module. Is + either a CloudToDeviceMethod type or a IO[bytes] type. Required. + :type direct_method_request: ~azure.iot.hub.protocol.models.CloudToDeviceMethod or IO[bytes] + :return: CloudToDeviceMethodResult or the result of cls(response) + :rtype: ~azure.iot.hub.protocol.models.CloudToDeviceMethodResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.CloudToDeviceMethodResult] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(direct_method_request, (IOBase, bytes)): + _content = direct_method_request + else: + _json = self._serialize.body(direct_method_request, "CloudToDeviceMethod") + + _request = build_invoke_method_request( + device_id=device_id, + module_id=module_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + deserialized = self._deserialize("CloudToDeviceMethodResult", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore diff --git a/src/azure/iot/hub/protocol/operations/_patch.py b/src/azure/iot/hub/protocol/operations/_patch.py new file mode 100644 index 0000000..87676c6 --- /dev/null +++ b/src/azure/iot/hub/protocol/operations/_patch.py @@ -0,0 +1,21 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------- +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" + + +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/src/azure/iot/hub/protocol/operations/_query_operations.py b/src/azure/iot/hub/protocol/operations/_query_operations.py new file mode 100644 index 0000000..6dac891 --- /dev/null +++ b/src/azure/iot/hub/protocol/operations/_query_operations.py @@ -0,0 +1,229 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from collections.abc import MutableMapping +from io import IOBase +from typing import Any, Callable, IO, Optional, TypeVar, Union, overload + +from azure.core import PipelineClient +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.rest import HttpRequest, HttpResponse +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict + +from .. import models as _models +from .._configuration import IotHubGatewayServiceAPIsConfiguration +from .._utils.serialization import Deserializer, Serializer + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_get_twins_request( + *, x_ms_continuation: Optional[str] = None, x_ms_max_item_count: Optional[str] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-04-12")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/devices/query") + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if x_ms_continuation is not None: + _headers["x-ms-continuation"] = _SERIALIZER.header("x_ms_continuation", x_ms_continuation, "str") + if x_ms_max_item_count is not None: + _headers["x-ms-max-item-count"] = _SERIALIZER.header("x_ms_max_item_count", x_ms_max_item_count, "str") + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +class QueryOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.iot.hub.protocol.IotHubGatewayServiceAPIs`'s + :attr:`query` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: IotHubGatewayServiceAPIsConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @overload + def get_twins( + self, + query_specification: _models.QuerySpecification, + x_ms_continuation: Optional[str] = None, + x_ms_max_item_count: Optional[str] = None, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> list[_models.Twin]: + """Query an IoT Hub to retrieve information regarding device twins using a SQL-like language. See + https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-query-language for more information. + Pagination is supported. This returns information about device twins only. + + :param query_specification: The query string. See + https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-query-language for more information. + Required. + :type query_specification: ~azure.iot.hub.protocol.models.QuerySpecification + :param x_ms_continuation: The continuation token used to get the next page of results. Default + value is None. + :type x_ms_continuation: str + :param x_ms_max_item_count: The maximum number of items returned per page. The service may use + a different value if the value specified is not acceptable. Default value is None. + :type x_ms_max_item_count: str + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: list of Twin or the result of cls(response) + :rtype: list[~azure.iot.hub.protocol.models.Twin] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def get_twins( + self, + query_specification: IO[bytes], + x_ms_continuation: Optional[str] = None, + x_ms_max_item_count: Optional[str] = None, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> list[_models.Twin]: + """Query an IoT Hub to retrieve information regarding device twins using a SQL-like language. See + https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-query-language for more information. + Pagination is supported. This returns information about device twins only. + + :param query_specification: The query string. See + https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-query-language for more information. + Required. + :type query_specification: IO[bytes] + :param x_ms_continuation: The continuation token used to get the next page of results. Default + value is None. + :type x_ms_continuation: str + :param x_ms_max_item_count: The maximum number of items returned per page. The service may use + a different value if the value specified is not acceptable. Default value is None. + :type x_ms_max_item_count: str + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: list of Twin or the result of cls(response) + :rtype: list[~azure.iot.hub.protocol.models.Twin] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def get_twins( + self, + query_specification: Union[_models.QuerySpecification, IO[bytes]], + x_ms_continuation: Optional[str] = None, + x_ms_max_item_count: Optional[str] = None, + **kwargs: Any + ) -> list[_models.Twin]: + """Query an IoT Hub to retrieve information regarding device twins using a SQL-like language. See + https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-query-language for more information. + Pagination is supported. This returns information about device twins only. + + :param query_specification: The query string. See + https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-query-language for more information. + Is either a QuerySpecification type or a IO[bytes] type. Required. + :type query_specification: ~azure.iot.hub.protocol.models.QuerySpecification or IO[bytes] + :param x_ms_continuation: The continuation token used to get the next page of results. Default + value is None. + :type x_ms_continuation: str + :param x_ms_max_item_count: The maximum number of items returned per page. The service may use + a different value if the value specified is not acceptable. Default value is None. + :type x_ms_max_item_count: str + :return: list of Twin or the result of cls(response) + :rtype: list[~azure.iot.hub.protocol.models.Twin] + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[list[_models.Twin]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(query_specification, (IOBase, bytes)): + _content = query_specification + else: + _json = self._serialize.body(query_specification, "QuerySpecification") + + _request = build_get_twins_request( + x_ms_continuation=x_ms_continuation, + x_ms_max_item_count=x_ms_max_item_count, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + response_headers = {} + response_headers["x-ms-item-type"] = self._deserialize("str", response.headers.get("x-ms-item-type")) + response_headers["x-ms-continuation"] = self._deserialize("str", response.headers.get("x-ms-continuation")) + + deserialized = self._deserialize("[Twin]", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore diff --git a/src/azure/iot/hub/protocol/operations/_statistics_operations.py b/src/azure/iot/hub/protocol/operations/_statistics_operations.py new file mode 100644 index 0000000..64eeb38 --- /dev/null +++ b/src/azure/iot/hub/protocol/operations/_statistics_operations.py @@ -0,0 +1,185 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from collections.abc import MutableMapping +from typing import Any, Callable, Optional, TypeVar + +from azure.core import PipelineClient +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.rest import HttpRequest, HttpResponse +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict + +from .. import models as _models +from .._configuration import IotHubGatewayServiceAPIsConfiguration +from .._utils.serialization import Deserializer, Serializer + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_get_device_statistics_request(**kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-04-12")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/statistics/devices") + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_get_service_statistics_request(**kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-04-12")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/statistics/service") + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class StatisticsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.iot.hub.protocol.IotHubGatewayServiceAPIs`'s + :attr:`statistics` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: IotHubGatewayServiceAPIsConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def get_device_statistics(self, **kwargs: Any) -> _models.RegistryStatistics: + """Gets device statistics of the IoT Hub identity registry, such as total device count. + + :return: RegistryStatistics or the result of cls(response) + :rtype: ~azure.iot.hub.protocol.models.RegistryStatistics + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.RegistryStatistics] = kwargs.pop("cls", None) + + _request = build_get_device_statistics_request( + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + deserialized = self._deserialize("RegistryStatistics", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def get_service_statistics(self, **kwargs: Any) -> _models.ServiceStatistics: + """Gets service statistics of the IoT Hub identity registry, such as connected device count. + + :return: ServiceStatistics or the result of cls(response) + :rtype: ~azure.iot.hub.protocol.models.ServiceStatistics + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ServiceStatistics] = kwargs.pop("cls", None) + + _request = build_get_service_statistics_request( + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + deserialized = self._deserialize("ServiceStatistics", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore diff --git a/src/azure/iot/hub/protocol/operations/bulk_registry_operations.py b/src/azure/iot/hub/protocol/operations/bulk_registry_operations.py deleted file mode 100644 index d637139..0000000 --- a/src/azure/iot/hub/protocol/operations/bulk_registry_operations.py +++ /dev/null @@ -1,96 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is -# regenerated. -# -------------------------------------------------------------------------- - -from msrest.pipeline import ClientRawResponse -from msrest.exceptions import HttpOperationError - -from .. import models - - -class BulkRegistryOperations(object): - """BulkRegistryOperations operations. - - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. - :ivar api_version: Version of the Api. Constant value: "2021-04-12". - """ - - models = models - - def __init__(self, client, config, serializer, deserializer): - - self._client = client - self._serialize = serializer - self._deserialize = deserializer - - self.config = config - self.api_version = "2021-04-12" - - def update_registry(self, devices, custom_headers=None, raw=False, **operation_config): - """Creates, updates, or deletes the identities of multiple devices from - the IoT Hub identity registry. A device identity can be specified only - once in the list. Different operations (create, update, delete) on - different devices are allowed. A maximum of 100 devices can be - specified per invocation. For large scale operations, use the import - feature using blob storage - (https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-identity-registry#import-and-export-device-identities). - - :param devices: The registry operations to perform. - :type devices: list[~protocol.models.ExportImportDevice] - :param dict custom_headers: headers that will be added to the request - :param bool raw: returns the direct response alongside the - deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. - :return: BulkRegistryOperationResult or ClientRawResponse if raw=true - :rtype: ~protocol.models.BulkRegistryOperationResult or - ~msrest.pipeline.ClientRawResponse - :raises: - :class:`HttpOperationError` - """ - # Construct URL - url = self.update_registry.metadata["url"] - - # Construct parameters - query_parameters = {} - query_parameters["api-version"] = self._serialize.query( - "self.api_version", self.api_version, "str" - ) - - # Construct headers - header_parameters = {} - header_parameters["Accept"] = "application/json" - header_parameters["Content-Type"] = "application/json; charset=utf-8" - if custom_headers: - header_parameters.update(custom_headers) - - # Construct body - body_content = self._serialize.body(devices, "[ExportImportDevice]") - - # Construct and send request - request = self._client.post(url, query_parameters, header_parameters, body_content) - response = self._client.send(request, stream=False, **operation_config) - - if response.status_code not in [200, 400]: - raise HttpOperationError(self._deserialize, response) - - deserialized = None - - if response.status_code == 200: - deserialized = self._deserialize("BulkRegistryOperationResult", response) - if response.status_code == 400: - deserialized = self._deserialize("BulkRegistryOperationResult", response) - - if raw: - client_raw_response = ClientRawResponse(deserialized, response) - return client_raw_response - - return deserialized - - update_registry.metadata = {"url": "/devices"} diff --git a/src/azure/iot/hub/protocol/operations/cloud_to_device_messages_operations.py b/src/azure/iot/hub/protocol/operations/cloud_to_device_messages_operations.py deleted file mode 100644 index aaec891..0000000 --- a/src/azure/iot/hub/protocol/operations/cloud_to_device_messages_operations.py +++ /dev/null @@ -1,234 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is -# regenerated. -# -------------------------------------------------------------------------- - -from msrest.pipeline import ClientRawResponse -from msrest.exceptions import HttpOperationError - -from .. import models - - -class CloudToDeviceMessagesOperations(object): - """CloudToDeviceMessagesOperations operations. - - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. - :ivar api_version: Version of the Api. Constant value: "2021-04-12". - """ - - models = models - - def __init__(self, client, config, serializer, deserializer): - - self._client = client - self._serialize = serializer - self._deserialize = deserializer - - self.config = config - self.api_version = "2021-04-12" - - def purge_cloud_to_device_message_queue( - self, id, custom_headers=None, raw=False, **operation_config - ): - """Deletes all the pending commands for a device in the IoT Hub. - - :param id: The unique identifier of the device. - :type id: str - :param dict custom_headers: headers that will be added to the request - :param bool raw: returns the direct response alongside the - deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. - :return: PurgeMessageQueueResult or ClientRawResponse if raw=true - :rtype: ~protocol.models.PurgeMessageQueueResult or - ~msrest.pipeline.ClientRawResponse - :raises: - :class:`HttpOperationError` - """ - # Construct URL - url = self.purge_cloud_to_device_message_queue.metadata["url"] - path_format_arguments = {"id": self._serialize.url("id", id, "str")} - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} - query_parameters["api-version"] = self._serialize.query( - "self.api_version", self.api_version, "str" - ) - - # Construct headers - header_parameters = {} - header_parameters["Accept"] = "application/json" - if custom_headers: - header_parameters.update(custom_headers) - - # Construct and send request - request = self._client.delete(url, query_parameters, header_parameters) - response = self._client.send(request, stream=False, **operation_config) - - if response.status_code not in [200]: - raise HttpOperationError(self._deserialize, response) - - deserialized = None - - if response.status_code == 200: - deserialized = self._deserialize("PurgeMessageQueueResult", response) - - if raw: - client_raw_response = ClientRawResponse(deserialized, response) - return client_raw_response - - return deserialized - - purge_cloud_to_device_message_queue.metadata = {"url": "/devices/{id}/commands"} - - def receive_feedback_notification(self, custom_headers=None, raw=False, **operation_config): - """Gets the feedback for cloud-to-device messages. See - https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-messaging for - more information. This capability is only available in the standard - tier IoT Hub. For more information, see [Choose the right IoT Hub - tier](https://aka.ms/scaleyouriotsolution). - - :param dict custom_headers: headers that will be added to the request - :param bool raw: returns the direct response alongside the - deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. - :return: None or ClientRawResponse if raw=true - :rtype: None or ~msrest.pipeline.ClientRawResponse - :raises: - :class:`HttpOperationError` - """ - # Construct URL - url = self.receive_feedback_notification.metadata["url"] - - # Construct parameters - query_parameters = {} - query_parameters["api-version"] = self._serialize.query( - "self.api_version", self.api_version, "str" - ) - - # Construct headers - header_parameters = {} - if custom_headers: - header_parameters.update(custom_headers) - - # Construct and send request - request = self._client.get(url, query_parameters, header_parameters) - response = self._client.send(request, stream=False, **operation_config) - - if response.status_code not in [200, 204]: - raise HttpOperationError(self._deserialize, response) - - if raw: - client_raw_response = ClientRawResponse(None, response) - return client_raw_response - - receive_feedback_notification.metadata = {"url": "/messages/serviceBound/feedback"} - - def complete_feedback_notification( - self, lock_token, custom_headers=None, raw=False, **operation_config - ): - """Completes the cloud-to-device feedback message. A completed message is - deleted from the feedback queue of the service. See - https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-messaging for - more information. - - :param lock_token: The lock token obtained when the cloud-to-device - message is received. This is used to resolve race conditions when - completing a feedback message. - :type lock_token: str - :param dict custom_headers: headers that will be added to the request - :param bool raw: returns the direct response alongside the - deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. - :return: None or ClientRawResponse if raw=true - :rtype: None or ~msrest.pipeline.ClientRawResponse - :raises: - :class:`HttpOperationError` - """ - # Construct URL - url = self.complete_feedback_notification.metadata["url"] - path_format_arguments = {"lockToken": self._serialize.url("lock_token", lock_token, "str")} - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} - query_parameters["api-version"] = self._serialize.query( - "self.api_version", self.api_version, "str" - ) - - # Construct headers - header_parameters = {} - if custom_headers: - header_parameters.update(custom_headers) - - # Construct and send request - request = self._client.delete(url, query_parameters, header_parameters) - response = self._client.send(request, stream=False, **operation_config) - - if response.status_code not in [204]: - raise HttpOperationError(self._deserialize, response) - - if raw: - client_raw_response = ClientRawResponse(None, response) - return client_raw_response - - complete_feedback_notification.metadata = {"url": "/messages/serviceBound/feedback/{lockToken}"} - - def abandon_feedback_notification( - self, lock_token, custom_headers=None, raw=False, **operation_config - ): - """Abandons the lock on a cloud-to-device feedback message. See - https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-messaging for - more information. - - :param lock_token: The lock token obtained when the cloud-to-device - message is received. - :type lock_token: str - :param dict custom_headers: headers that will be added to the request - :param bool raw: returns the direct response alongside the - deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. - :return: None or ClientRawResponse if raw=true - :rtype: None or ~msrest.pipeline.ClientRawResponse - :raises: - :class:`HttpOperationError` - """ - # Construct URL - url = self.abandon_feedback_notification.metadata["url"] - path_format_arguments = {"lockToken": self._serialize.url("lock_token", lock_token, "str")} - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} - query_parameters["api-version"] = self._serialize.query( - "self.api_version", self.api_version, "str" - ) - - # Construct headers - header_parameters = {} - if custom_headers: - header_parameters.update(custom_headers) - - # Construct and send request - request = self._client.post(url, query_parameters, header_parameters) - response = self._client.send(request, stream=False, **operation_config) - - if response.status_code not in [204]: - raise HttpOperationError(self._deserialize, response) - - if raw: - client_raw_response = ClientRawResponse(None, response) - return client_raw_response - - abandon_feedback_notification.metadata = { - "url": "/messages/serviceBound/feedback/{lockToken}/abandon" - } diff --git a/src/azure/iot/hub/protocol/operations/configuration_operations.py b/src/azure/iot/hub/protocol/operations/configuration_operations.py deleted file mode 100644 index 3254173..0000000 --- a/src/azure/iot/hub/protocol/operations/configuration_operations.py +++ /dev/null @@ -1,376 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is -# regenerated. -# -------------------------------------------------------------------------- - -from msrest.pipeline import ClientRawResponse -from msrest.exceptions import HttpOperationError - -from .. import models - - -class ConfigurationOperations(object): - """ConfigurationOperations operations. - - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. - :ivar api_version: Version of the Api. Constant value: "2021-04-12". - """ - - models = models - - def __init__(self, client, config, serializer, deserializer): - - self._client = client - self._serialize = serializer - self._deserialize = deserializer - - self.config = config - self.api_version = "2021-04-12" - - def get(self, id, custom_headers=None, raw=False, **operation_config): - """Gets a configuration on the IoT Hub for automatic device/module - management. - - :param id: The unique identifier of the configuration. - :type id: str - :param dict custom_headers: headers that will be added to the request - :param bool raw: returns the direct response alongside the - deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. - :return: Configuration or ClientRawResponse if raw=true - :rtype: ~protocol.models.Configuration or - ~msrest.pipeline.ClientRawResponse - :raises: - :class:`HttpOperationError` - """ - # Construct URL - url = self.get.metadata["url"] - path_format_arguments = {"id": self._serialize.url("id", id, "str")} - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} - query_parameters["api-version"] = self._serialize.query( - "self.api_version", self.api_version, "str" - ) - - # Construct headers - header_parameters = {} - header_parameters["Accept"] = "application/json" - if custom_headers: - header_parameters.update(custom_headers) - - # Construct and send request - request = self._client.get(url, query_parameters, header_parameters) - response = self._client.send(request, stream=False, **operation_config) - - if response.status_code not in [200]: - raise HttpOperationError(self._deserialize, response) - - deserialized = None - - if response.status_code == 200: - deserialized = self._deserialize("Configuration", response) - - if raw: - client_raw_response = ClientRawResponse(deserialized, response) - return client_raw_response - - return deserialized - - get.metadata = {"url": "/configurations/{id}"} - - def create_or_update( - self, id, configuration, if_match=None, custom_headers=None, raw=False, **operation_config - ): - """Creates or updates a configuration on the IoT Hub for automatic - device/module management. Configuration identifier and Content cannot - be updated. - - :param id: The unique identifier of the configuration. - :type id: str - :param configuration: The configuration to be created or updated. - :type configuration: ~protocol.models.Configuration - :param if_match: The string representing a weak ETag for the - configuration, as per RFC7232. This should not be set when creating a - configuration, but may be set when updating a configuration. - :type if_match: str - :param dict custom_headers: headers that will be added to the request - :param bool raw: returns the direct response alongside the - deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. - :return: Configuration or ClientRawResponse if raw=true - :rtype: ~protocol.models.Configuration or - ~msrest.pipeline.ClientRawResponse - :raises: - :class:`HttpOperationError` - """ - # Construct URL - url = self.create_or_update.metadata["url"] - path_format_arguments = {"id": self._serialize.url("id", id, "str")} - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} - query_parameters["api-version"] = self._serialize.query( - "self.api_version", self.api_version, "str" - ) - - # Construct headers - header_parameters = {} - header_parameters["Accept"] = "application/json" - header_parameters["Content-Type"] = "application/json; charset=utf-8" - if custom_headers: - header_parameters.update(custom_headers) - if if_match is not None: - header_parameters["If-Match"] = self._serialize.header("if_match", if_match, "str") - - # Construct body - body_content = self._serialize.body(configuration, "Configuration") - - # Construct and send request - request = self._client.put(url, query_parameters, header_parameters, body_content) - response = self._client.send(request, stream=False, **operation_config) - - if response.status_code not in [200, 201]: - raise HttpOperationError(self._deserialize, response) - - deserialized = None - - if response.status_code == 200: - deserialized = self._deserialize("Configuration", response) - if response.status_code == 201: - deserialized = self._deserialize("Configuration", response) - - if raw: - client_raw_response = ClientRawResponse(deserialized, response) - return client_raw_response - - return deserialized - - create_or_update.metadata = {"url": "/configurations/{id}"} - - def delete(self, id, if_match=None, custom_headers=None, raw=False, **operation_config): - """Deletes a configuration on the IoT Hub for automatic device/module - management. - - :param id: The unique identifier of the configuration. - :type id: str - :param if_match: The string representing a weak ETag for the - configuration, as per RFC7232. The delete operation is performed only - if this ETag matches the value maintained by the server, indicating - that the configuration has not been modified since it was last - retrieved. To force an unconditional delete, set If-Match to the - wildcard character (*). - :type if_match: str - :param dict custom_headers: headers that will be added to the request - :param bool raw: returns the direct response alongside the - deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. - :return: None or ClientRawResponse if raw=true - :rtype: None or ~msrest.pipeline.ClientRawResponse - :raises: - :class:`HttpOperationError` - """ - # Construct URL - url = self.delete.metadata["url"] - path_format_arguments = {"id": self._serialize.url("id", id, "str")} - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} - query_parameters["api-version"] = self._serialize.query( - "self.api_version", self.api_version, "str" - ) - - # Construct headers - header_parameters = {} - if custom_headers: - header_parameters.update(custom_headers) - if if_match is not None: - header_parameters["If-Match"] = self._serialize.header("if_match", if_match, "str") - - # Construct and send request - request = self._client.delete(url, query_parameters, header_parameters) - response = self._client.send(request, stream=False, **operation_config) - - if response.status_code not in [204]: - raise HttpOperationError(self._deserialize, response) - - if raw: - client_raw_response = ClientRawResponse(None, response) - return client_raw_response - - delete.metadata = {"url": "/configurations/{id}"} - - def get_configurations(self, top=None, custom_headers=None, raw=False, **operation_config): - """Gets configurations on the IoT Hub for automatic device/module - management. Pagination is not supported. - - :param top: The number of configurations to retrieve. Value will be - overridden if greater than the maximum deployment count for the IoT - Hub. - :type top: int - :param dict custom_headers: headers that will be added to the request - :param bool raw: returns the direct response alongside the - deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. - :return: list or ClientRawResponse if raw=true - :rtype: list[~protocol.models.Configuration] or - ~msrest.pipeline.ClientRawResponse - :raises: - :class:`HttpOperationError` - """ - # Construct URL - url = self.get_configurations.metadata["url"] - - # Construct parameters - query_parameters = {} - if top is not None: - query_parameters["top"] = self._serialize.query("top", top, "int") - query_parameters["api-version"] = self._serialize.query( - "self.api_version", self.api_version, "str" - ) - - # Construct headers - header_parameters = {} - header_parameters["Accept"] = "application/json" - if custom_headers: - header_parameters.update(custom_headers) - - # Construct and send request - request = self._client.get(url, query_parameters, header_parameters) - response = self._client.send(request, stream=False, **operation_config) - - if response.status_code not in [200]: - raise HttpOperationError(self._deserialize, response) - - deserialized = None - - if response.status_code == 200: - deserialized = self._deserialize("[Configuration]", response) - - if raw: - client_raw_response = ClientRawResponse(deserialized, response) - return client_raw_response - - return deserialized - - get_configurations.metadata = {"url": "/configurations"} - - def test_queries(self, input, custom_headers=None, raw=False, **operation_config): - """Validates target condition and custom metric queries for a - configuration on the IoT Hub. - - :param input: The configuration for target condition and custom metric - queries. - :type input: ~protocol.models.ConfigurationQueriesTestInput - :param dict custom_headers: headers that will be added to the request - :param bool raw: returns the direct response alongside the - deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. - :return: ConfigurationQueriesTestResponse or ClientRawResponse if - raw=true - :rtype: ~protocol.models.ConfigurationQueriesTestResponse or - ~msrest.pipeline.ClientRawResponse - :raises: - :class:`HttpOperationError` - """ - # Construct URL - url = self.test_queries.metadata["url"] - - # Construct parameters - query_parameters = {} - query_parameters["api-version"] = self._serialize.query( - "self.api_version", self.api_version, "str" - ) - - # Construct headers - header_parameters = {} - header_parameters["Accept"] = "application/json" - header_parameters["Content-Type"] = "application/json; charset=utf-8" - if custom_headers: - header_parameters.update(custom_headers) - - # Construct body - body_content = self._serialize.body(input, "ConfigurationQueriesTestInput") - - # Construct and send request - request = self._client.post(url, query_parameters, header_parameters, body_content) - response = self._client.send(request, stream=False, **operation_config) - - if response.status_code not in [200]: - raise HttpOperationError(self._deserialize, response) - - deserialized = None - - if response.status_code == 200: - deserialized = self._deserialize("ConfigurationQueriesTestResponse", response) - - if raw: - client_raw_response = ClientRawResponse(deserialized, response) - return client_raw_response - - return deserialized - - test_queries.metadata = {"url": "/configurations/testQueries"} - - def apply_on_edge_device(self, id, content, custom_headers=None, raw=False, **operation_config): - """Applies the configuration content to an edge device. - - :param id: The unique identifier of the edge device. - :type id: str - :param content: The configuration content. - :type content: ~protocol.models.ConfigurationContent - :param dict custom_headers: headers that will be added to the request - :param bool raw: returns the direct response alongside the - deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. - :return: None or ClientRawResponse if raw=true - :rtype: None or ~msrest.pipeline.ClientRawResponse - :raises: - :class:`HttpOperationError` - """ - # Construct URL - url = self.apply_on_edge_device.metadata["url"] - path_format_arguments = {"id": self._serialize.url("id", id, "str")} - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} - query_parameters["api-version"] = self._serialize.query( - "self.api_version", self.api_version, "str" - ) - - # Construct headers - header_parameters = {} - header_parameters["Content-Type"] = "application/json; charset=utf-8" - if custom_headers: - header_parameters.update(custom_headers) - - # Construct body - body_content = self._serialize.body(content, "ConfigurationContent") - - # Construct and send request - request = self._client.post(url, query_parameters, header_parameters, body_content) - response = self._client.send(request, stream=False, **operation_config) - - if response.status_code not in [204]: - raise HttpOperationError(self._deserialize, response) - - if raw: - client_raw_response = ClientRawResponse(None, response) - return client_raw_response - - apply_on_edge_device.metadata = {"url": "/devices/{id}/applyConfigurationContent"} diff --git a/src/azure/iot/hub/protocol/operations/devices_operations.py b/src/azure/iot/hub/protocol/operations/devices_operations.py deleted file mode 100644 index bbad062..0000000 --- a/src/azure/iot/hub/protocol/operations/devices_operations.py +++ /dev/null @@ -1,536 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is -# regenerated. -# -------------------------------------------------------------------------- - -from msrest.pipeline import ClientRawResponse -from msrest.exceptions import HttpOperationError - -from .. import models - - -class DevicesOperations(object): - """DevicesOperations operations. - - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. - :ivar api_version: Version of the Api. Constant value: "2021-04-12". - """ - - models = models - - def __init__(self, client, config, serializer, deserializer): - - self._client = client - self._serialize = serializer - self._deserialize = deserializer - - self.config = config - self.api_version = "2021-04-12" - - def get_devices(self, top=None, custom_headers=None, raw=False, **operation_config): - """Gets the identities of multiple devices from the IoT Hub identity - registry. Not recommended. Use the IoT Hub query API to retrieve device - twin and device identity information. See - https://docs.microsoft.com/en-us/rest/api/iothub/service/queryiothub - and - https://docs.microsoft.com/en-us/azure/iot-hub/iot-hub-devguide-query-language - for more information. - - :param top: The maximum number of device identities returned by the - query. Any value outside the range of 1-1000 is considered to be 1000. - :type top: int - :param dict custom_headers: headers that will be added to the request - :param bool raw: returns the direct response alongside the - deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. - :return: list or ClientRawResponse if raw=true - :rtype: list[~protocol.models.Device] or - ~msrest.pipeline.ClientRawResponse - :raises: - :class:`HttpOperationError` - """ - # Construct URL - url = self.get_devices.metadata["url"] - - # Construct parameters - query_parameters = {} - if top is not None: - query_parameters["top"] = self._serialize.query("top", top, "int") - query_parameters["api-version"] = self._serialize.query( - "self.api_version", self.api_version, "str" - ) - - # Construct headers - header_parameters = {} - header_parameters["Accept"] = "application/json" - if custom_headers: - header_parameters.update(custom_headers) - - # Construct and send request - request = self._client.get(url, query_parameters, header_parameters) - response = self._client.send(request, stream=False, **operation_config) - - if response.status_code not in [200]: - raise HttpOperationError(self._deserialize, response) - - deserialized = None - - if response.status_code == 200: - deserialized = self._deserialize("[Device]", response) - - if raw: - client_raw_response = ClientRawResponse(deserialized, response) - return client_raw_response - - return deserialized - - get_devices.metadata = {"url": "/devices"} - - def get_identity(self, id, custom_headers=None, raw=False, **operation_config): - """Gets a device from the identity registry of the IoT Hub. - - :param id: The unique identifier of the device. - :type id: str - :param dict custom_headers: headers that will be added to the request - :param bool raw: returns the direct response alongside the - deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. - :return: Device or ClientRawResponse if raw=true - :rtype: ~protocol.models.Device or ~msrest.pipeline.ClientRawResponse - :raises: - :class:`HttpOperationError` - """ - # Construct URL - url = self.get_identity.metadata["url"] - path_format_arguments = {"id": self._serialize.url("id", id, "str")} - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} - query_parameters["api-version"] = self._serialize.query( - "self.api_version", self.api_version, "str" - ) - - # Construct headers - header_parameters = {} - header_parameters["Accept"] = "application/json" - if custom_headers: - header_parameters.update(custom_headers) - - # Construct and send request - request = self._client.get(url, query_parameters, header_parameters) - response = self._client.send(request, stream=False, **operation_config) - - if response.status_code not in [200]: - raise HttpOperationError(self._deserialize, response) - - deserialized = None - - if response.status_code == 200: - deserialized = self._deserialize("Device", response) - - if raw: - client_raw_response = ClientRawResponse(deserialized, response) - return client_raw_response - - return deserialized - - get_identity.metadata = {"url": "/devices/{id}"} - - def create_or_update_identity( - self, id, device, if_match=None, custom_headers=None, raw=False, **operation_config - ): - """Creates or updates the identity of a device in the identity registry of - the IoT Hub. - - :param id: The unique identifier of the device. - :type id: str - :param device: The contents of the device identity. - :type device: ~protocol.models.Device - :param if_match: The string representing a weak ETag for the device - identity, as per RFC7232. This should not be set when creating a - device, but may be set when updating a device. - :type if_match: str - :param dict custom_headers: headers that will be added to the request - :param bool raw: returns the direct response alongside the - deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. - :return: Device or ClientRawResponse if raw=true - :rtype: ~protocol.models.Device or ~msrest.pipeline.ClientRawResponse - :raises: - :class:`HttpOperationError` - """ - # Construct URL - url = self.create_or_update_identity.metadata["url"] - path_format_arguments = {"id": self._serialize.url("id", id, "str")} - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} - query_parameters["api-version"] = self._serialize.query( - "self.api_version", self.api_version, "str" - ) - - # Construct headers - header_parameters = {} - header_parameters["Accept"] = "application/json" - header_parameters["Content-Type"] = "application/json; charset=utf-8" - if custom_headers: - header_parameters.update(custom_headers) - if if_match is not None: - header_parameters["If-Match"] = self._serialize.header("if_match", if_match, "str") - - # Construct body - body_content = self._serialize.body(device, "Device") - - # Construct and send request - request = self._client.put(url, query_parameters, header_parameters, body_content) - response = self._client.send(request, stream=False, **operation_config) - - if response.status_code not in [200]: - raise HttpOperationError(self._deserialize, response) - - deserialized = None - - if response.status_code == 200: - deserialized = self._deserialize("Device", response) - - if raw: - client_raw_response = ClientRawResponse(deserialized, response) - return client_raw_response - - return deserialized - - create_or_update_identity.metadata = {"url": "/devices/{id}"} - - def delete_identity( - self, id, if_match=None, custom_headers=None, raw=False, **operation_config - ): - """Deletes the identity of a device from the identity registry of the IoT - Hub. - - :param id: The unique identifier of the device. - :type id: str - :param if_match: The string representing a weak ETag for the device - identity, as per RFC7232. The delete operation is performed only if - this ETag matches the value maintained by the server, indicating that - the device identity has not been modified since it was last retrieved. - To force an unconditional delete, set If-Match to the wildcard - character (*). - :type if_match: str - :param dict custom_headers: headers that will be added to the request - :param bool raw: returns the direct response alongside the - deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. - :return: None or ClientRawResponse if raw=true - :rtype: None or ~msrest.pipeline.ClientRawResponse - :raises: - :class:`HttpOperationError` - """ - # Construct URL - url = self.delete_identity.metadata["url"] - path_format_arguments = {"id": self._serialize.url("id", id, "str")} - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} - query_parameters["api-version"] = self._serialize.query( - "self.api_version", self.api_version, "str" - ) - - # Construct headers - header_parameters = {} - if custom_headers: - header_parameters.update(custom_headers) - if if_match is not None: - header_parameters["If-Match"] = self._serialize.header("if_match", if_match, "str") - - # Construct and send request - request = self._client.delete(url, query_parameters, header_parameters) - response = self._client.send(request, stream=False, **operation_config) - - if response.status_code not in [204]: - raise HttpOperationError(self._deserialize, response) - - if raw: - client_raw_response = ClientRawResponse(None, response) - return client_raw_response - - delete_identity.metadata = {"url": "/devices/{id}"} - - def get_twin(self, id, custom_headers=None, raw=False, **operation_config): - """Gets the device twin. See - https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-device-twins - for more information. - - :param id: The unique identifier of the device. - :type id: str - :param dict custom_headers: headers that will be added to the request - :param bool raw: returns the direct response alongside the - deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. - :return: Twin or ClientRawResponse if raw=true - :rtype: ~protocol.models.Twin or ~msrest.pipeline.ClientRawResponse - :raises: - :class:`HttpOperationError` - """ - # Construct URL - url = self.get_twin.metadata["url"] - path_format_arguments = {"id": self._serialize.url("id", id, "str")} - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} - query_parameters["api-version"] = self._serialize.query( - "self.api_version", self.api_version, "str" - ) - - # Construct headers - header_parameters = {} - header_parameters["Accept"] = "application/json" - if custom_headers: - header_parameters.update(custom_headers) - - # Construct and send request - request = self._client.get(url, query_parameters, header_parameters) - response = self._client.send(request, stream=False, **operation_config) - - if response.status_code not in [200]: - raise HttpOperationError(self._deserialize, response) - - deserialized = None - - if response.status_code == 200: - deserialized = self._deserialize("Twin", response) - - if raw: - client_raw_response = ClientRawResponse(deserialized, response) - return client_raw_response - - return deserialized - - get_twin.metadata = {"url": "/twins/{id}"} - - def replace_twin( - self, - id, - device_twin_info, - if_match=None, - custom_headers=None, - raw=False, - **operation_config - ): - """Replaces the tags and desired properties of a device twin. See - https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-device-twins - for more information. - - :param id: The unique identifier of the device. - :type id: str - :param device_twin_info: The device twin info that will replace the - existing info. - :type device_twin_info: ~protocol.models.Twin - :param if_match: The string representing a weak ETag for the device - twin, as per RFC7232. It determines if the replace operation should be - carried out. - :type if_match: str - :param dict custom_headers: headers that will be added to the request - :param bool raw: returns the direct response alongside the - deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. - :return: Twin or ClientRawResponse if raw=true - :rtype: ~protocol.models.Twin or ~msrest.pipeline.ClientRawResponse - :raises: - :class:`HttpOperationError` - """ - # Construct URL - url = self.replace_twin.metadata["url"] - path_format_arguments = {"id": self._serialize.url("id", id, "str")} - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} - query_parameters["api-version"] = self._serialize.query( - "self.api_version", self.api_version, "str" - ) - - # Construct headers - header_parameters = {} - header_parameters["Accept"] = "application/json" - header_parameters["Content-Type"] = "application/json; charset=utf-8" - if custom_headers: - header_parameters.update(custom_headers) - if if_match is not None: - header_parameters["If-Match"] = self._serialize.header("if_match", if_match, "str") - - # Construct body - body_content = self._serialize.body(device_twin_info, "Twin") - - # Construct and send request - request = self._client.put(url, query_parameters, header_parameters, body_content) - response = self._client.send(request, stream=False, **operation_config) - - if response.status_code not in [200]: - raise HttpOperationError(self._deserialize, response) - - deserialized = None - - if response.status_code == 200: - deserialized = self._deserialize("Twin", response) - - if raw: - client_raw_response = ClientRawResponse(deserialized, response) - return client_raw_response - - return deserialized - - replace_twin.metadata = {"url": "/twins/{id}"} - - def update_twin( - self, - id, - device_twin_info, - if_match=None, - custom_headers=None, - raw=False, - **operation_config - ): - """Updates the tags and desired properties of a device twin. See - https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-device-twins - for more information. - - :param id: The unique identifier of the device. - :type id: str - :param device_twin_info: The device twin info containing the tags and - desired properties to be updated. - :type device_twin_info: ~protocol.models.Twin - :param if_match: The string representing a weak ETag for the device - twin, as per RFC7232. It determines if the update operation should be - carried out. - :type if_match: str - :param dict custom_headers: headers that will be added to the request - :param bool raw: returns the direct response alongside the - deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. - :return: Twin or ClientRawResponse if raw=true - :rtype: ~protocol.models.Twin or ~msrest.pipeline.ClientRawResponse - :raises: - :class:`HttpOperationError` - """ - # Construct URL - url = self.update_twin.metadata["url"] - path_format_arguments = {"id": self._serialize.url("id", id, "str")} - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} - query_parameters["api-version"] = self._serialize.query( - "self.api_version", self.api_version, "str" - ) - - # Construct headers - header_parameters = {} - header_parameters["Accept"] = "application/json" - header_parameters["Content-Type"] = "application/json; charset=utf-8" - if custom_headers: - header_parameters.update(custom_headers) - if if_match is not None: - header_parameters["If-Match"] = self._serialize.header("if_match", if_match, "str") - - # Construct body - body_content = self._serialize.body(device_twin_info, "Twin") - - # Construct and send request - request = self._client.patch(url, query_parameters, header_parameters, body_content) - response = self._client.send(request, stream=False, **operation_config) - - if response.status_code not in [200]: - raise HttpOperationError(self._deserialize, response) - - deserialized = None - - if response.status_code == 200: - deserialized = self._deserialize("Twin", response) - - if raw: - client_raw_response = ClientRawResponse(deserialized, response) - return client_raw_response - - return deserialized - - update_twin.metadata = {"url": "/twins/{id}"} - - def invoke_method( - self, device_id, direct_method_request, custom_headers=None, raw=False, **operation_config - ): - """Invokes a direct method on a device. See - https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-direct-methods - for more information. - - :param device_id: The unique identifier of the device. - :type device_id: str - :param direct_method_request: The parameters to execute a direct - method on the device. - :type direct_method_request: ~protocol.models.CloudToDeviceMethod - :param dict custom_headers: headers that will be added to the request - :param bool raw: returns the direct response alongside the - deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. - :return: CloudToDeviceMethodResult or ClientRawResponse if raw=true - :rtype: ~protocol.models.CloudToDeviceMethodResult or - ~msrest.pipeline.ClientRawResponse - :raises: - :class:`HttpOperationError` - """ - # Construct URL - url = self.invoke_method.metadata["url"] - path_format_arguments = {"deviceId": self._serialize.url("device_id", device_id, "str")} - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} - query_parameters["api-version"] = self._serialize.query( - "self.api_version", self.api_version, "str" - ) - - # Construct headers - header_parameters = {} - header_parameters["Accept"] = "application/json" - header_parameters["Content-Type"] = "application/json; charset=utf-8" - if custom_headers: - header_parameters.update(custom_headers) - - # Construct body - body_content = self._serialize.body(direct_method_request, "CloudToDeviceMethod") - - # Construct and send request - request = self._client.post(url, query_parameters, header_parameters, body_content) - response = self._client.send(request, stream=False, **operation_config) - - if response.status_code not in [200]: - raise HttpOperationError(self._deserialize, response) - - deserialized = None - - if response.status_code == 200: - deserialized = self._deserialize("CloudToDeviceMethodResult", response) - - if raw: - client_raw_response = ClientRawResponse(deserialized, response) - return client_raw_response - - return deserialized - - invoke_method.metadata = {"url": "/twins/{deviceId}/methods"} diff --git a/src/azure/iot/hub/protocol/operations/digital_twin_operations.py b/src/azure/iot/hub/protocol/operations/digital_twin_operations.py deleted file mode 100644 index eb8429b..0000000 --- a/src/azure/iot/hub/protocol/operations/digital_twin_operations.py +++ /dev/null @@ -1,341 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is -# regenerated. -# -------------------------------------------------------------------------- - -from msrest.pipeline import ClientRawResponse -from msrest.exceptions import HttpOperationError - -from .. import models - - -class DigitalTwinOperations(object): - """DigitalTwinOperations operations. - - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. - :ivar api_version: Version of the Api. Constant value: "2021-04-12". - """ - - models = models - - def __init__(self, client, config, serializer, deserializer): - - self._client = client - self._serialize = serializer - self._deserialize = deserializer - - self.config = config - self.api_version = "2021-04-12" - - def get_digital_twin(self, id, custom_headers=None, raw=False, **operation_config): - """Gets a digital twin. - - :param id: Digital Twin ID. - :type id: str - :param dict custom_headers: headers that will be added to the request - :param bool raw: returns the direct response alongside the - deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. - :return: object or ClientRawResponse if raw=true - :rtype: object or ~msrest.pipeline.ClientRawResponse - :raises: - :class:`HttpOperationError` - """ - # Construct URL - url = self.get_digital_twin.metadata["url"] - path_format_arguments = {"id": self._serialize.url("id", id, "str")} - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} - query_parameters["api-version"] = self._serialize.query( - "self.api_version", self.api_version, "str" - ) - - # Construct headers - header_parameters = {} - header_parameters["Accept"] = "application/json" - if custom_headers: - header_parameters.update(custom_headers) - - # Construct and send request - request = self._client.get(url, query_parameters, header_parameters) - response = self._client.send(request, stream=False, **operation_config) - - if response.status_code not in [200]: - raise HttpOperationError(self._deserialize, response) - - deserialized = None - header_dict = {} - - if response.status_code == 200: - deserialized = self._deserialize("object", response) - header_dict = {"ETag": "str"} - - if raw: - client_raw_response = ClientRawResponse(deserialized, response) - client_raw_response.add_headers(header_dict) - return client_raw_response - - return deserialized - - get_digital_twin.metadata = {"url": "/digitaltwins/{id}"} - - def update_digital_twin( - self, - id, - digital_twin_patch, - if_match=None, - custom_headers=None, - raw=False, - **operation_config - ): - """Updates a digital twin. - - :param id: Digital Twin ID. - :type id: str - :param digital_twin_patch: json-patch contents to update. - :type digital_twin_patch: list[object] - :param if_match: - :type if_match: str - :param dict custom_headers: headers that will be added to the request - :param bool raw: returns the direct response alongside the - deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. - :return: None or ClientRawResponse if raw=true - :rtype: None or ~msrest.pipeline.ClientRawResponse - :raises: - :class:`HttpOperationError` - """ - # Construct URL - url = self.update_digital_twin.metadata["url"] - path_format_arguments = {"id": self._serialize.url("id", id, "str")} - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} - query_parameters["api-version"] = self._serialize.query( - "self.api_version", self.api_version, "str" - ) - - # Construct headers - header_parameters = {} - header_parameters["Content-Type"] = "application/json; charset=utf-8" - if custom_headers: - header_parameters.update(custom_headers) - if if_match is not None: - header_parameters["If-Match"] = self._serialize.header("if_match", if_match, "str") - - # Construct body - body_content = self._serialize.body(digital_twin_patch, "[object]") - - # Construct and send request - request = self._client.patch(url, query_parameters, header_parameters, body_content) - response = self._client.send(request, stream=False, **operation_config) - - if response.status_code not in [202]: - raise HttpOperationError(self._deserialize, response) - - if raw: - client_raw_response = ClientRawResponse(None, response) - client_raw_response.add_headers({"ETag": "str", "Location": "str"}) - return client_raw_response - - update_digital_twin.metadata = {"url": "/digitaltwins/{id}"} - - def invoke_root_level_command( - self, - id, - command_name, - payload, - connect_timeout_in_seconds=None, - response_timeout_in_seconds=None, - custom_headers=None, - raw=False, - **operation_config - ): - """Invoke a digital twin root level command. - - Invoke a digital twin root level command. - - :param id: - :type id: str - :param command_name: - :type command_name: str - :param payload: - :type payload: object - :param connect_timeout_in_seconds: Maximum interval of time, in - seconds, that the digital twin command will wait for the answer. - :type connect_timeout_in_seconds: int - :param response_timeout_in_seconds: Maximum interval of time, in - seconds, that the digital twin command will wait for the answer. - :type response_timeout_in_seconds: int - :param dict custom_headers: headers that will be added to the request - :param bool raw: returns the direct response alongside the - deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. - :return: object or ClientRawResponse if raw=true - :rtype: object or ~msrest.pipeline.ClientRawResponse - :raises: - :class:`HttpOperationError` - """ - # Construct URL - url = self.invoke_root_level_command.metadata["url"] - path_format_arguments = { - "id": self._serialize.url("id", id, "str"), - "commandName": self._serialize.url("command_name", command_name, "str"), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} - query_parameters["api-version"] = self._serialize.query( - "self.api_version", self.api_version, "str" - ) - if connect_timeout_in_seconds is not None: - query_parameters["connectTimeoutInSeconds"] = self._serialize.query( - "connect_timeout_in_seconds", connect_timeout_in_seconds, "int" - ) - if response_timeout_in_seconds is not None: - query_parameters["responseTimeoutInSeconds"] = self._serialize.query( - "response_timeout_in_seconds", response_timeout_in_seconds, "int" - ) - - # Construct headers - header_parameters = {} - header_parameters["Accept"] = "application/json" - header_parameters["Content-Type"] = "application/json; charset=utf-8" - if custom_headers: - header_parameters.update(custom_headers) - - # Construct body - body_content = self._serialize.body(payload, "object") - - # Construct and send request - request = self._client.post(url, query_parameters, header_parameters, body_content) - response = self._client.send(request, stream=False, **operation_config) - - if response.status_code not in [200]: - raise HttpOperationError(self._deserialize, response) - - deserialized = None - header_dict = {} - - if response.status_code == 200: - deserialized = self._deserialize("object", response) - header_dict = {"x-ms-command-statuscode": "int", "x-ms-request-id": "str"} - - if raw: - client_raw_response = ClientRawResponse(deserialized, response) - client_raw_response.add_headers(header_dict) - return client_raw_response - - return deserialized - - invoke_root_level_command.metadata = {"url": "/digitaltwins/{id}/commands/{commandName}"} - - def invoke_component_command( - self, - id, - component_path, - command_name, - payload, - connect_timeout_in_seconds=None, - response_timeout_in_seconds=None, - custom_headers=None, - raw=False, - **operation_config - ): - """Invoke a digital twin command. - - Invoke a digital twin command. - - :param id: - :type id: str - :param component_path: - :type component_path: str - :param command_name: - :type command_name: str - :param payload: - :type payload: object - :param connect_timeout_in_seconds: Maximum interval of time, in - seconds, that the digital twin command will wait for the answer. - :type connect_timeout_in_seconds: int - :param response_timeout_in_seconds: Maximum interval of time, in - seconds, that the digital twin command will wait for the answer. - :type response_timeout_in_seconds: int - :param dict custom_headers: headers that will be added to the request - :param bool raw: returns the direct response alongside the - deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. - :return: object or ClientRawResponse if raw=true - :rtype: object or ~msrest.pipeline.ClientRawResponse - :raises: - :class:`HttpOperationError` - """ - # Construct URL - url = self.invoke_component_command.metadata["url"] - path_format_arguments = { - "id": self._serialize.url("id", id, "str"), - "componentPath": self._serialize.url("component_path", component_path, "str"), - "commandName": self._serialize.url("command_name", command_name, "str"), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} - query_parameters["api-version"] = self._serialize.query( - "self.api_version", self.api_version, "str" - ) - if connect_timeout_in_seconds is not None: - query_parameters["connectTimeoutInSeconds"] = self._serialize.query( - "connect_timeout_in_seconds", connect_timeout_in_seconds, "int" - ) - if response_timeout_in_seconds is not None: - query_parameters["responseTimeoutInSeconds"] = self._serialize.query( - "response_timeout_in_seconds", response_timeout_in_seconds, "int" - ) - - # Construct headers - header_parameters = {} - header_parameters["Accept"] = "application/json" - header_parameters["Content-Type"] = "application/json; charset=utf-8" - if custom_headers: - header_parameters.update(custom_headers) - - # Construct body - body_content = self._serialize.body(payload, "object") - - # Construct and send request - request = self._client.post(url, query_parameters, header_parameters, body_content) - response = self._client.send(request, stream=False, **operation_config) - - if response.status_code not in [200]: - raise HttpOperationError(self._deserialize, response) - - deserialized = None - header_dict = {} - - if response.status_code == 200: - deserialized = self._deserialize("object", response) - header_dict = {"x-ms-command-statuscode": "int", "x-ms-request-id": "str"} - - if raw: - client_raw_response = ClientRawResponse(deserialized, response) - client_raw_response.add_headers(header_dict) - return client_raw_response - - return deserialized - - invoke_component_command.metadata = { - "url": "/digitaltwins/{id}/components/{componentPath}/commands/{commandName}" - } diff --git a/src/azure/iot/hub/protocol/operations/jobs_operations.py b/src/azure/iot/hub/protocol/operations/jobs_operations.py deleted file mode 100644 index 3226867..0000000 --- a/src/azure/iot/hub/protocol/operations/jobs_operations.py +++ /dev/null @@ -1,489 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is -# regenerated. -# -------------------------------------------------------------------------- - -from msrest.pipeline import ClientRawResponse -from msrest.exceptions import HttpOperationError - -from .. import models - - -class JobsOperations(object): - """JobsOperations operations. - - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. - :ivar api_version: Version of the Api. Constant value: "2021-04-12". - """ - - models = models - - def __init__(self, client, config, serializer, deserializer): - - self._client = client - self._serialize = serializer - self._deserialize = deserializer - - self.config = config - self.api_version = "2021-04-12" - - def create_import_export_job( - self, job_properties, custom_headers=None, raw=False, **operation_config - ): - """Creates a new import or export job on the IoT Hub. See - https://docs.microsoft.com/en-us/azure/iot-hub/iot-hub-devguide-identity-registry#import-and-export-device-identities - for more information. - - :param job_properties: The job specifications. - :type job_properties: ~protocol.models.JobProperties - :param dict custom_headers: headers that will be added to the request - :param bool raw: returns the direct response alongside the - deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. - :return: JobProperties or ClientRawResponse if raw=true - :rtype: ~protocol.models.JobProperties or - ~msrest.pipeline.ClientRawResponse - :raises: - :class:`HttpOperationError` - """ - # Construct URL - url = self.create_import_export_job.metadata["url"] - - # Construct parameters - query_parameters = {} - query_parameters["api-version"] = self._serialize.query( - "self.api_version", self.api_version, "str" - ) - - # Construct headers - header_parameters = {} - header_parameters["Accept"] = "application/json" - header_parameters["Content-Type"] = "application/json; charset=utf-8" - if custom_headers: - header_parameters.update(custom_headers) - - # Construct body - body_content = self._serialize.body(job_properties, "JobProperties") - - # Construct and send request - request = self._client.post(url, query_parameters, header_parameters, body_content) - response = self._client.send(request, stream=False, **operation_config) - - if response.status_code not in [200]: - raise HttpOperationError(self._deserialize, response) - - deserialized = None - - if response.status_code == 200: - deserialized = self._deserialize("JobProperties", response) - - if raw: - client_raw_response = ClientRawResponse(deserialized, response) - return client_raw_response - - return deserialized - - create_import_export_job.metadata = {"url": "/jobs/create"} - - def get_import_export_jobs(self, custom_headers=None, raw=False, **operation_config): - """Gets the status of all import and export jobs in the IoT Hub. See - https://docs.microsoft.com/en-us/azure/iot-hub/iot-hub-devguide-identity-registry#import-and-export-device-identities - for more information. - - :param dict custom_headers: headers that will be added to the request - :param bool raw: returns the direct response alongside the - deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. - :return: list or ClientRawResponse if raw=true - :rtype: list[~protocol.models.JobProperties] or - ~msrest.pipeline.ClientRawResponse - :raises: - :class:`HttpOperationError` - """ - # Construct URL - url = self.get_import_export_jobs.metadata["url"] - - # Construct parameters - query_parameters = {} - query_parameters["api-version"] = self._serialize.query( - "self.api_version", self.api_version, "str" - ) - - # Construct headers - header_parameters = {} - header_parameters["Accept"] = "application/json" - if custom_headers: - header_parameters.update(custom_headers) - - # Construct and send request - request = self._client.get(url, query_parameters, header_parameters) - response = self._client.send(request, stream=False, **operation_config) - - if response.status_code not in [200]: - raise HttpOperationError(self._deserialize, response) - - deserialized = None - - if response.status_code == 200: - deserialized = self._deserialize("[JobProperties]", response) - - if raw: - client_raw_response = ClientRawResponse(deserialized, response) - return client_raw_response - - return deserialized - - get_import_export_jobs.metadata = {"url": "/jobs"} - - def get_import_export_job(self, id, custom_headers=None, raw=False, **operation_config): - """Gets the status of an import or export job in the IoT Hub. See - https://docs.microsoft.com/en-us/azure/iot-hub/iot-hub-devguide-identity-registry#import-and-export-device-identities - for more information. - - :param id: The unique identifier of the job. - :type id: str - :param dict custom_headers: headers that will be added to the request - :param bool raw: returns the direct response alongside the - deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. - :return: JobProperties or ClientRawResponse if raw=true - :rtype: ~protocol.models.JobProperties or - ~msrest.pipeline.ClientRawResponse - :raises: - :class:`HttpOperationError` - """ - # Construct URL - url = self.get_import_export_job.metadata["url"] - path_format_arguments = {"id": self._serialize.url("id", id, "str")} - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} - query_parameters["api-version"] = self._serialize.query( - "self.api_version", self.api_version, "str" - ) - - # Construct headers - header_parameters = {} - header_parameters["Accept"] = "application/json" - if custom_headers: - header_parameters.update(custom_headers) - - # Construct and send request - request = self._client.get(url, query_parameters, header_parameters) - response = self._client.send(request, stream=False, **operation_config) - - if response.status_code not in [200]: - raise HttpOperationError(self._deserialize, response) - - deserialized = None - - if response.status_code == 200: - deserialized = self._deserialize("JobProperties", response) - - if raw: - client_raw_response = ClientRawResponse(deserialized, response) - return client_raw_response - - return deserialized - - get_import_export_job.metadata = {"url": "/jobs/{id}"} - - def cancel_import_export_job(self, id, custom_headers=None, raw=False, **operation_config): - """Cancels an import or export job in the IoT Hub. - - :param id: The unique identifier of the job. - :type id: str - :param dict custom_headers: headers that will be added to the request - :param bool raw: returns the direct response alongside the - deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. - :return: object or ClientRawResponse if raw=true - :rtype: object or ~msrest.pipeline.ClientRawResponse - :raises: - :class:`HttpOperationError` - """ - # Construct URL - url = self.cancel_import_export_job.metadata["url"] - path_format_arguments = {"id": self._serialize.url("id", id, "str")} - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} - query_parameters["api-version"] = self._serialize.query( - "self.api_version", self.api_version, "str" - ) - - # Construct headers - header_parameters = {} - header_parameters["Accept"] = "application/json" - if custom_headers: - header_parameters.update(custom_headers) - - # Construct and send request - request = self._client.delete(url, query_parameters, header_parameters) - response = self._client.send(request, stream=False, **operation_config) - - if response.status_code not in [200, 204]: - raise HttpOperationError(self._deserialize, response) - - deserialized = None - - if response.status_code == 200: - deserialized = self._deserialize("object", response) - - if raw: - client_raw_response = ClientRawResponse(deserialized, response) - return client_raw_response - - return deserialized - - cancel_import_export_job.metadata = {"url": "/jobs/{id}"} - - def get_scheduled_job(self, id, custom_headers=None, raw=False, **operation_config): - """Gets details of a scheduled job from the IoT Hub. See - https://docs.microsoft.com/en-us/azure/iot-hub/iot-hub-devguide-jobs - for more information. - - :param id: The unique identifier of the job. - :type id: str - :param dict custom_headers: headers that will be added to the request - :param bool raw: returns the direct response alongside the - deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. - :return: JobResponse or ClientRawResponse if raw=true - :rtype: ~protocol.models.JobResponse or - ~msrest.pipeline.ClientRawResponse - :raises: - :class:`HttpOperationError` - """ - # Construct URL - url = self.get_scheduled_job.metadata["url"] - path_format_arguments = {"id": self._serialize.url("id", id, "str")} - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} - query_parameters["api-version"] = self._serialize.query( - "self.api_version", self.api_version, "str" - ) - - # Construct headers - header_parameters = {} - header_parameters["Accept"] = "application/json" - if custom_headers: - header_parameters.update(custom_headers) - - # Construct and send request - request = self._client.get(url, query_parameters, header_parameters) - response = self._client.send(request, stream=False, **operation_config) - - if response.status_code not in [200]: - raise HttpOperationError(self._deserialize, response) - - deserialized = None - - if response.status_code == 200: - deserialized = self._deserialize("JobResponse", response) - - if raw: - client_raw_response = ClientRawResponse(deserialized, response) - return client_raw_response - - return deserialized - - get_scheduled_job.metadata = {"url": "/jobs/v2/{id}"} - - def create_scheduled_job( - self, id, job_request, custom_headers=None, raw=False, **operation_config - ): - """Creates a new job to schedule twin updates or direct methods on the IoT - Hub at a scheduled time. See - https://docs.microsoft.com/en-us/azure/iot-hub/iot-hub-devguide-jobs - for more information. - - :param id: The unique identifier of the job. - :type id: str - :param job_request: The job request info. - :type job_request: ~protocol.models.JobRequest - :param dict custom_headers: headers that will be added to the request - :param bool raw: returns the direct response alongside the - deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. - :return: JobResponse or ClientRawResponse if raw=true - :rtype: ~protocol.models.JobResponse or - ~msrest.pipeline.ClientRawResponse - :raises: - :class:`HttpOperationError` - """ - # Construct URL - url = self.create_scheduled_job.metadata["url"] - path_format_arguments = {"id": self._serialize.url("id", id, "str")} - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} - query_parameters["api-version"] = self._serialize.query( - "self.api_version", self.api_version, "str" - ) - - # Construct headers - header_parameters = {} - header_parameters["Accept"] = "application/json" - header_parameters["Content-Type"] = "application/json; charset=utf-8" - if custom_headers: - header_parameters.update(custom_headers) - - # Construct body - body_content = self._serialize.body(job_request, "JobRequest") - - # Construct and send request - request = self._client.put(url, query_parameters, header_parameters, body_content) - response = self._client.send(request, stream=False, **operation_config) - - if response.status_code not in [200]: - raise HttpOperationError(self._deserialize, response) - - deserialized = None - - if response.status_code == 200: - deserialized = self._deserialize("JobResponse", response) - - if raw: - client_raw_response = ClientRawResponse(deserialized, response) - return client_raw_response - - return deserialized - - create_scheduled_job.metadata = {"url": "/jobs/v2/{id}"} - - def cancel_scheduled_job(self, id, custom_headers=None, raw=False, **operation_config): - """Cancels a scheduled job on the IoT Hub. See - https://docs.microsoft.com/en-us/azure/iot-hub/iot-hub-devguide-jobs - for more information. - - :param id: The unique identifier of the job. - :type id: str - :param dict custom_headers: headers that will be added to the request - :param bool raw: returns the direct response alongside the - deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. - :return: JobResponse or ClientRawResponse if raw=true - :rtype: ~protocol.models.JobResponse or - ~msrest.pipeline.ClientRawResponse - :raises: - :class:`HttpOperationError` - """ - # Construct URL - url = self.cancel_scheduled_job.metadata["url"] - path_format_arguments = {"id": self._serialize.url("id", id, "str")} - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} - query_parameters["api-version"] = self._serialize.query( - "self.api_version", self.api_version, "str" - ) - - # Construct headers - header_parameters = {} - header_parameters["Accept"] = "application/json" - if custom_headers: - header_parameters.update(custom_headers) - - # Construct and send request - request = self._client.post(url, query_parameters, header_parameters) - response = self._client.send(request, stream=False, **operation_config) - - if response.status_code not in [200]: - raise HttpOperationError(self._deserialize, response) - - deserialized = None - - if response.status_code == 200: - deserialized = self._deserialize("JobResponse", response) - - if raw: - client_raw_response = ClientRawResponse(deserialized, response) - return client_raw_response - - return deserialized - - cancel_scheduled_job.metadata = {"url": "/jobs/v2/{id}/cancel"} - - def query_scheduled_jobs( - self, job_type=None, job_status=None, custom_headers=None, raw=False, **operation_config - ): - """Gets the information about jobs using an IoT Hub query. See - https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-query-language - for more information. - - :param job_type: The job type. See - https://docs.microsoft.com/en-us/azure/iot-hub/iot-hub-devguide-jobs#querying-for-progress-on-jobs - for a list of possible job types. - :type job_type: str - :param job_status: The job status. See - https://docs.microsoft.com/en-us/azure/iot-hub/iot-hub-devguide-jobs#querying-for-progress-on-jobs - for a list of possible statuses. - :type job_status: str - :param dict custom_headers: headers that will be added to the request - :param bool raw: returns the direct response alongside the - deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. - :return: QueryResult or ClientRawResponse if raw=true - :rtype: ~protocol.models.QueryResult or - ~msrest.pipeline.ClientRawResponse - :raises: - :class:`HttpOperationError` - """ - # Construct URL - url = self.query_scheduled_jobs.metadata["url"] - - # Construct parameters - query_parameters = {} - if job_type is not None: - query_parameters["jobType"] = self._serialize.query("job_type", job_type, "str") - if job_status is not None: - query_parameters["jobStatus"] = self._serialize.query("job_status", job_status, "str") - query_parameters["api-version"] = self._serialize.query( - "self.api_version", self.api_version, "str" - ) - - # Construct headers - header_parameters = {} - header_parameters["Accept"] = "application/json" - if custom_headers: - header_parameters.update(custom_headers) - - # Construct and send request - request = self._client.get(url, query_parameters, header_parameters) - response = self._client.send(request, stream=False, **operation_config) - - if response.status_code not in [200]: - raise HttpOperationError(self._deserialize, response) - - deserialized = None - - if response.status_code == 200: - deserialized = self._deserialize("QueryResult", response) - - if raw: - client_raw_response = ClientRawResponse(deserialized, response) - return client_raw_response - - return deserialized - - query_scheduled_jobs.metadata = {"url": "/jobs/v2/query"} diff --git a/src/azure/iot/hub/protocol/operations/modules_operations.py b/src/azure/iot/hub/protocol/operations/modules_operations.py deleted file mode 100644 index d1a4777..0000000 --- a/src/azure/iot/hub/protocol/operations/modules_operations.py +++ /dev/null @@ -1,572 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is -# regenerated. -# -------------------------------------------------------------------------- - -from msrest.pipeline import ClientRawResponse -from msrest.exceptions import HttpOperationError - -from .. import models - - -class ModulesOperations(object): - """ModulesOperations operations. - - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. - :ivar api_version: Version of the Api. Constant value: "2021-04-12". - """ - - models = models - - def __init__(self, client, config, serializer, deserializer): - - self._client = client - self._serialize = serializer - self._deserialize = deserializer - - self.config = config - self.api_version = "2021-04-12" - - def get_twin(self, id, mid, custom_headers=None, raw=False, **operation_config): - """Gets the module twin. See - https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-device-twins - for more information. - - :param id: The unique identifier of the device. - :type id: str - :param mid: The unique identifier of the module. - :type mid: str - :param dict custom_headers: headers that will be added to the request - :param bool raw: returns the direct response alongside the - deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. - :return: Twin or ClientRawResponse if raw=true - :rtype: ~protocol.models.Twin or ~msrest.pipeline.ClientRawResponse - :raises: - :class:`HttpOperationError` - """ - # Construct URL - url = self.get_twin.metadata["url"] - path_format_arguments = { - "id": self._serialize.url("id", id, "str"), - "mid": self._serialize.url("mid", mid, "str"), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} - query_parameters["api-version"] = self._serialize.query( - "self.api_version", self.api_version, "str" - ) - - # Construct headers - header_parameters = {} - header_parameters["Accept"] = "application/json" - if custom_headers: - header_parameters.update(custom_headers) - - # Construct and send request - request = self._client.get(url, query_parameters, header_parameters) - response = self._client.send(request, stream=False, **operation_config) - - if response.status_code not in [200]: - raise HttpOperationError(self._deserialize, response) - - deserialized = None - - if response.status_code == 200: - deserialized = self._deserialize("Twin", response) - - if raw: - client_raw_response = ClientRawResponse(deserialized, response) - return client_raw_response - - return deserialized - - get_twin.metadata = {"url": "/twins/{id}/modules/{mid}"} - - def replace_twin( - self, - id, - mid, - device_twin_info, - if_match=None, - custom_headers=None, - raw=False, - **operation_config - ): - """Replaces the tags and desired properties of a module twin. See - https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-device-twins - for more information. - - :param id: The unique identifier of the device. - :type id: str - :param mid: The unique identifier of the module. - :type mid: str - :param device_twin_info: The module twin info that will replace the - existing info. - :type device_twin_info: ~protocol.models.Twin - :param if_match: The string representing a weak ETag for the device - twin, as per RFC7232. It determines if the replace operation should be - carried out. - :type if_match: str - :param dict custom_headers: headers that will be added to the request - :param bool raw: returns the direct response alongside the - deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. - :return: Twin or ClientRawResponse if raw=true - :rtype: ~protocol.models.Twin or ~msrest.pipeline.ClientRawResponse - :raises: - :class:`HttpOperationError` - """ - # Construct URL - url = self.replace_twin.metadata["url"] - path_format_arguments = { - "id": self._serialize.url("id", id, "str"), - "mid": self._serialize.url("mid", mid, "str"), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} - query_parameters["api-version"] = self._serialize.query( - "self.api_version", self.api_version, "str" - ) - - # Construct headers - header_parameters = {} - header_parameters["Accept"] = "application/json" - header_parameters["Content-Type"] = "application/json; charset=utf-8" - if custom_headers: - header_parameters.update(custom_headers) - if if_match is not None: - header_parameters["If-Match"] = self._serialize.header("if_match", if_match, "str") - - # Construct body - body_content = self._serialize.body(device_twin_info, "Twin") - - # Construct and send request - request = self._client.put(url, query_parameters, header_parameters, body_content) - response = self._client.send(request, stream=False, **operation_config) - - if response.status_code not in [200]: - raise HttpOperationError(self._deserialize, response) - - deserialized = None - - if response.status_code == 200: - deserialized = self._deserialize("Twin", response) - - if raw: - client_raw_response = ClientRawResponse(deserialized, response) - return client_raw_response - - return deserialized - - replace_twin.metadata = {"url": "/twins/{id}/modules/{mid}"} - - def update_twin( - self, - id, - mid, - device_twin_info, - if_match=None, - custom_headers=None, - raw=False, - **operation_config - ): - """Updates the tags and desired properties of a module twin. See - https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-device-twins - for more information. - - :param id: The unique identifier of the device. - :type id: str - :param mid: The unique identifier of the module. - :type mid: str - :param device_twin_info: The module twin info containing the tags and - desired properties to be updated. - :type device_twin_info: ~protocol.models.Twin - :param if_match: The string representing a weak ETag for the device - twin, as per RFC7232. It determines if the update operation should be - carried out. - :type if_match: str - :param dict custom_headers: headers that will be added to the request - :param bool raw: returns the direct response alongside the - deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. - :return: Twin or ClientRawResponse if raw=true - :rtype: ~protocol.models.Twin or ~msrest.pipeline.ClientRawResponse - :raises: - :class:`HttpOperationError` - """ - # Construct URL - url = self.update_twin.metadata["url"] - path_format_arguments = { - "id": self._serialize.url("id", id, "str"), - "mid": self._serialize.url("mid", mid, "str"), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} - query_parameters["api-version"] = self._serialize.query( - "self.api_version", self.api_version, "str" - ) - - # Construct headers - header_parameters = {} - header_parameters["Accept"] = "application/json" - header_parameters["Content-Type"] = "application/json; charset=utf-8" - if custom_headers: - header_parameters.update(custom_headers) - if if_match is not None: - header_parameters["If-Match"] = self._serialize.header("if_match", if_match, "str") - - # Construct body - body_content = self._serialize.body(device_twin_info, "Twin") - - # Construct and send request - request = self._client.patch(url, query_parameters, header_parameters, body_content) - response = self._client.send(request, stream=False, **operation_config) - - if response.status_code not in [200]: - raise HttpOperationError(self._deserialize, response) - - deserialized = None - - if response.status_code == 200: - deserialized = self._deserialize("Twin", response) - - if raw: - client_raw_response = ClientRawResponse(deserialized, response) - return client_raw_response - - return deserialized - - update_twin.metadata = {"url": "/twins/{id}/modules/{mid}"} - - def get_modules_on_device(self, id, custom_headers=None, raw=False, **operation_config): - """Gets all the module identities on the device. - - :param id: The unique identifier of the device. - :type id: str - :param dict custom_headers: headers that will be added to the request - :param bool raw: returns the direct response alongside the - deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. - :return: list or ClientRawResponse if raw=true - :rtype: list[~protocol.models.Module] or - ~msrest.pipeline.ClientRawResponse - :raises: - :class:`HttpOperationError` - """ - # Construct URL - url = self.get_modules_on_device.metadata["url"] - path_format_arguments = {"id": self._serialize.url("id", id, "str")} - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} - query_parameters["api-version"] = self._serialize.query( - "self.api_version", self.api_version, "str" - ) - - # Construct headers - header_parameters = {} - header_parameters["Accept"] = "application/json" - if custom_headers: - header_parameters.update(custom_headers) - - # Construct and send request - request = self._client.get(url, query_parameters, header_parameters) - response = self._client.send(request, stream=False, **operation_config) - - if response.status_code not in [200]: - raise HttpOperationError(self._deserialize, response) - - deserialized = None - - if response.status_code == 200: - deserialized = self._deserialize("[Module]", response) - - if raw: - client_raw_response = ClientRawResponse(deserialized, response) - return client_raw_response - - return deserialized - - get_modules_on_device.metadata = {"url": "/devices/{id}/modules"} - - def get_identity(self, id, mid, custom_headers=None, raw=False, **operation_config): - """Gets a module identity on the device. - - :param id: The unique identifier of the device. - :type id: str - :param mid: The unique identifier of the module. - :type mid: str - :param dict custom_headers: headers that will be added to the request - :param bool raw: returns the direct response alongside the - deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. - :return: Module or ClientRawResponse if raw=true - :rtype: ~protocol.models.Module or ~msrest.pipeline.ClientRawResponse - :raises: - :class:`HttpOperationError` - """ - # Construct URL - url = self.get_identity.metadata["url"] - path_format_arguments = { - "id": self._serialize.url("id", id, "str"), - "mid": self._serialize.url("mid", mid, "str"), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} - query_parameters["api-version"] = self._serialize.query( - "self.api_version", self.api_version, "str" - ) - - # Construct headers - header_parameters = {} - header_parameters["Accept"] = "application/json" - if custom_headers: - header_parameters.update(custom_headers) - - # Construct and send request - request = self._client.get(url, query_parameters, header_parameters) - response = self._client.send(request, stream=False, **operation_config) - - if response.status_code not in [200]: - raise HttpOperationError(self._deserialize, response) - - deserialized = None - - if response.status_code == 200: - deserialized = self._deserialize("Module", response) - - if raw: - client_raw_response = ClientRawResponse(deserialized, response) - return client_raw_response - - return deserialized - - get_identity.metadata = {"url": "/devices/{id}/modules/{mid}"} - - def create_or_update_identity( - self, id, mid, module, if_match=None, custom_headers=None, raw=False, **operation_config - ): - """Creates or updates the module identity for a device in the IoT Hub. The - moduleId and generationId cannot be updated by the user. - - :param id: The unique identifier of the device. - :type id: str - :param mid: The unique identifier of the module. - :type mid: str - :param module: The module identity. - :type module: ~protocol.models.Module - :param if_match: The string representing a weak ETag for the module, - as per RFC7232. This should not be set when creating a module, but may - be set when updating a module. - :type if_match: str - :param dict custom_headers: headers that will be added to the request - :param bool raw: returns the direct response alongside the - deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. - :return: Module or ClientRawResponse if raw=true - :rtype: ~protocol.models.Module or ~msrest.pipeline.ClientRawResponse - :raises: - :class:`HttpOperationError` - """ - # Construct URL - url = self.create_or_update_identity.metadata["url"] - path_format_arguments = { - "id": self._serialize.url("id", id, "str"), - "mid": self._serialize.url("mid", mid, "str"), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} - query_parameters["api-version"] = self._serialize.query( - "self.api_version", self.api_version, "str" - ) - - # Construct headers - header_parameters = {} - header_parameters["Accept"] = "application/json" - header_parameters["Content-Type"] = "application/json; charset=utf-8" - if custom_headers: - header_parameters.update(custom_headers) - if if_match is not None: - header_parameters["If-Match"] = self._serialize.header("if_match", if_match, "str") - - # Construct body - body_content = self._serialize.body(module, "Module") - - # Construct and send request - request = self._client.put(url, query_parameters, header_parameters, body_content) - response = self._client.send(request, stream=False, **operation_config) - - if response.status_code not in [200, 201]: - raise HttpOperationError(self._deserialize, response) - - deserialized = None - - if response.status_code == 200: - deserialized = self._deserialize("Module", response) - if response.status_code == 201: - deserialized = self._deserialize("Module", response) - - if raw: - client_raw_response = ClientRawResponse(deserialized, response) - return client_raw_response - - return deserialized - - create_or_update_identity.metadata = {"url": "/devices/{id}/modules/{mid}"} - - def delete_identity( - self, id, mid, if_match=None, custom_headers=None, raw=False, **operation_config - ): - """Deletes the module identity for a device in the IoT Hub. - - :param id: The unique identifier of the deivce. - :type id: str - :param mid: The unique identifier of the module. - :type mid: str - :param if_match: The string representing a weak ETag for the module, - as per RFC7232. The delete operation is performed only if this ETag - matches the value maintained by the server, indicating that the module - has not been modified since it was last retrieved. To force an - unconditional delete, set If-Match to the wildcard character (*). - :type if_match: str - :param dict custom_headers: headers that will be added to the request - :param bool raw: returns the direct response alongside the - deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. - :return: None or ClientRawResponse if raw=true - :rtype: None or ~msrest.pipeline.ClientRawResponse - :raises: - :class:`HttpOperationError` - """ - # Construct URL - url = self.delete_identity.metadata["url"] - path_format_arguments = { - "id": self._serialize.url("id", id, "str"), - "mid": self._serialize.url("mid", mid, "str"), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} - query_parameters["api-version"] = self._serialize.query( - "self.api_version", self.api_version, "str" - ) - - # Construct headers - header_parameters = {} - if custom_headers: - header_parameters.update(custom_headers) - if if_match is not None: - header_parameters["If-Match"] = self._serialize.header("if_match", if_match, "str") - - # Construct and send request - request = self._client.delete(url, query_parameters, header_parameters) - response = self._client.send(request, stream=False, **operation_config) - - if response.status_code not in [204]: - raise HttpOperationError(self._deserialize, response) - - if raw: - client_raw_response = ClientRawResponse(None, response) - return client_raw_response - - delete_identity.metadata = {"url": "/devices/{id}/modules/{mid}"} - - def invoke_method( - self, - device_id, - module_id, - direct_method_request, - custom_headers=None, - raw=False, - **operation_config - ): - """Invokes a direct method on a module of a device. See - https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-direct-methods - for more information. - - :param device_id: The unique identifier of the device. - :type device_id: str - :param module_id: The unique identifier of the module. - :type module_id: str - :param direct_method_request: The parameters to execute a direct - method on the module. - :type direct_method_request: ~protocol.models.CloudToDeviceMethod - :param dict custom_headers: headers that will be added to the request - :param bool raw: returns the direct response alongside the - deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. - :return: CloudToDeviceMethodResult or ClientRawResponse if raw=true - :rtype: ~protocol.models.CloudToDeviceMethodResult or - ~msrest.pipeline.ClientRawResponse - :raises: - :class:`HttpOperationError` - """ - # Construct URL - url = self.invoke_method.metadata["url"] - path_format_arguments = { - "deviceId": self._serialize.url("device_id", device_id, "str"), - "moduleId": self._serialize.url("module_id", module_id, "str"), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} - query_parameters["api-version"] = self._serialize.query( - "self.api_version", self.api_version, "str" - ) - - # Construct headers - header_parameters = {} - header_parameters["Accept"] = "application/json" - header_parameters["Content-Type"] = "application/json; charset=utf-8" - if custom_headers: - header_parameters.update(custom_headers) - - # Construct body - body_content = self._serialize.body(direct_method_request, "CloudToDeviceMethod") - - # Construct and send request - request = self._client.post(url, query_parameters, header_parameters, body_content) - response = self._client.send(request, stream=False, **operation_config) - - if response.status_code not in [200]: - raise HttpOperationError(self._deserialize, response) - - deserialized = None - - if response.status_code == 200: - deserialized = self._deserialize("CloudToDeviceMethodResult", response) - - if raw: - client_raw_response = ClientRawResponse(deserialized, response) - return client_raw_response - - return deserialized - - invoke_method.metadata = {"url": "/twins/{deviceId}/modules/{moduleId}/methods"} diff --git a/src/azure/iot/hub/protocol/operations/query_operations.py b/src/azure/iot/hub/protocol/operations/query_operations.py deleted file mode 100644 index d300f82..0000000 --- a/src/azure/iot/hub/protocol/operations/query_operations.py +++ /dev/null @@ -1,120 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is -# regenerated. -# -------------------------------------------------------------------------- - -from msrest.pipeline import ClientRawResponse -from msrest.exceptions import HttpOperationError - -from .. import models - - -class QueryOperations(object): - """QueryOperations operations. - - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. - :ivar api_version: Version of the Api. Constant value: "2021-04-12". - """ - - models = models - - def __init__(self, client, config, serializer, deserializer): - - self._client = client - self._serialize = serializer - self._deserialize = deserializer - - self.config = config - self.api_version = "2021-04-12" - - def get_twins( - self, - query_specification, - x_ms_continuation=None, - x_ms_max_item_count=None, - custom_headers=None, - raw=False, - **operation_config - ): - """Query an IoT Hub to retrieve information regarding device twins using a - SQL-like language. See - https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-query-language - for more information. Pagination is supported. This returns information - about device twins only. - - :param query_specification: The query string. See - https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-query-language - for more information. - :type query_specification: ~protocol.models.QuerySpecification - :param x_ms_continuation: The continuation token used to get the next - page of results. - :type x_ms_continuation: str - :param x_ms_max_item_count: The maximum number of items returned per - page. The service may use a different value if the value specified is - not acceptable. - :type x_ms_max_item_count: str - :param dict custom_headers: headers that will be added to the request - :param bool raw: returns the direct response alongside the - deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. - :return: list or ClientRawResponse if raw=true - :rtype: list[~protocol.models.Twin] or - ~msrest.pipeline.ClientRawResponse - :raises: - :class:`HttpOperationError` - """ - # Construct URL - url = self.get_twins.metadata["url"] - - # Construct parameters - query_parameters = {} - query_parameters["api-version"] = self._serialize.query( - "self.api_version", self.api_version, "str" - ) - - # Construct headers - header_parameters = {} - header_parameters["Accept"] = "application/json" - header_parameters["Content-Type"] = "application/json; charset=utf-8" - if custom_headers: - header_parameters.update(custom_headers) - if x_ms_continuation is not None: - header_parameters["x-ms-continuation"] = self._serialize.header( - "x_ms_continuation", x_ms_continuation, "str" - ) - if x_ms_max_item_count is not None: - header_parameters["x-ms-max-item-count"] = self._serialize.header( - "x_ms_max_item_count", x_ms_max_item_count, "str" - ) - - # Construct body - body_content = self._serialize.body(query_specification, "QuerySpecification") - - # Construct and send request - request = self._client.post(url, query_parameters, header_parameters, body_content) - response = self._client.send(request, stream=False, **operation_config) - - if response.status_code not in [200]: - raise HttpOperationError(self._deserialize, response) - - deserialized = None - header_dict = {} - - if response.status_code == 200: - deserialized = self._deserialize("[Twin]", response) - header_dict = {"x-ms-item-type": "str", "x-ms-continuation": "str"} - - if raw: - client_raw_response = ClientRawResponse(deserialized, response) - client_raw_response.add_headers(header_dict) - return client_raw_response - - return deserialized - - get_twins.metadata = {"url": "/devices/query"} diff --git a/src/azure/iot/hub/protocol/operations/statistics_operations.py b/src/azure/iot/hub/protocol/operations/statistics_operations.py deleted file mode 100644 index d996240..0000000 --- a/src/azure/iot/hub/protocol/operations/statistics_operations.py +++ /dev/null @@ -1,133 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is -# regenerated. -# -------------------------------------------------------------------------- - -from msrest.pipeline import ClientRawResponse -from msrest.exceptions import HttpOperationError - -from .. import models - - -class StatisticsOperations(object): - """StatisticsOperations operations. - - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. - :ivar api_version: Version of the Api. Constant value: "2021-04-12". - """ - - models = models - - def __init__(self, client, config, serializer, deserializer): - - self._client = client - self._serialize = serializer - self._deserialize = deserializer - - self.config = config - self.api_version = "2021-04-12" - - def get_device_statistics(self, custom_headers=None, raw=False, **operation_config): - """Gets device statistics of the IoT Hub identity registry, such as total - device count. - - :param dict custom_headers: headers that will be added to the request - :param bool raw: returns the direct response alongside the - deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. - :return: RegistryStatistics or ClientRawResponse if raw=true - :rtype: ~protocol.models.RegistryStatistics or - ~msrest.pipeline.ClientRawResponse - :raises: - :class:`HttpOperationError` - """ - # Construct URL - url = self.get_device_statistics.metadata["url"] - - # Construct parameters - query_parameters = {} - query_parameters["api-version"] = self._serialize.query( - "self.api_version", self.api_version, "str" - ) - - # Construct headers - header_parameters = {} - header_parameters["Accept"] = "application/json" - if custom_headers: - header_parameters.update(custom_headers) - - # Construct and send request - request = self._client.get(url, query_parameters, header_parameters) - response = self._client.send(request, stream=False, **operation_config) - - if response.status_code not in [200]: - raise HttpOperationError(self._deserialize, response) - - deserialized = None - - if response.status_code == 200: - deserialized = self._deserialize("RegistryStatistics", response) - - if raw: - client_raw_response = ClientRawResponse(deserialized, response) - return client_raw_response - - return deserialized - - get_device_statistics.metadata = {"url": "/statistics/devices"} - - def get_service_statistics(self, custom_headers=None, raw=False, **operation_config): - """Gets service statistics of the IoT Hub identity registry, such as - connected device count. - - :param dict custom_headers: headers that will be added to the request - :param bool raw: returns the direct response alongside the - deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. - :return: ServiceStatistics or ClientRawResponse if raw=true - :rtype: ~protocol.models.ServiceStatistics or - ~msrest.pipeline.ClientRawResponse - :raises: - :class:`HttpOperationError` - """ - # Construct URL - url = self.get_service_statistics.metadata["url"] - - # Construct parameters - query_parameters = {} - query_parameters["api-version"] = self._serialize.query( - "self.api_version", self.api_version, "str" - ) - - # Construct headers - header_parameters = {} - header_parameters["Accept"] = "application/json" - if custom_headers: - header_parameters.update(custom_headers) - - # Construct and send request - request = self._client.get(url, query_parameters, header_parameters) - response = self._client.send(request, stream=False, **operation_config) - - if response.status_code not in [200]: - raise HttpOperationError(self._deserialize, response) - - deserialized = None - - if response.status_code == 200: - deserialized = self._deserialize("ServiceStatistics", response) - - if raw: - client_raw_response = ClientRawResponse(deserialized, response) - return client_raw_response - - return deserialized - - get_service_statistics.metadata = {"url": "/statistics/service"} diff --git a/src/azure/iot/hub/protocol/py.typed b/src/azure/iot/hub/protocol/py.typed new file mode 100644 index 0000000..e5aff4f --- /dev/null +++ b/src/azure/iot/hub/protocol/py.typed @@ -0,0 +1 @@ +# Marker file for PEP 561. \ No newline at end of file diff --git a/swagger/README.md b/swagger/README.md new file mode 100644 index 0000000..f77a3a5 --- /dev/null +++ b/swagger/README.md @@ -0,0 +1,54 @@ +# Azure IoT Hub — Python SDK codegen + +This directory holds the AutoRest configuration used to (re)generate the +`azure.iot.hub.protocol` layer under `src/azure/iot/hub/protocol/` from the +service Swagger at `service.json` in the repository root. + +## Requirements + +- Node.js + npm (for `autorest`) +- `npm install -g autorest` (or invoke via `npx autorest`) + +## Regenerate + +From the repository root: + +```sh +autorest swagger/README.md --python --use=@autorest/python@6 +``` + +## Config + +```yaml +input-file: ../service.json +output-folder: ../src/azure/iot/hub/protocol +namespace: azure.iot.hub.protocol +package-name: azure-iot-hub +package-version: 3.0.0b1 +license-header: MICROSOFT_MIT_NO_VERSION +clear-output-folder: true +no-namespace-folders: true +python: true +version-tolerant: false +models-mode: msrest +client-side-validation: false +add-credential: false +``` + +### Why these flags + +- `models-mode: msrest` — emits legacy attribute-map `Model` classes so kwargs- + based constructors (`Device(**kwargs)`, `SymmetricKey(primary_key=...)`) keep + the exact call shape the manager classes rely on. The generated + `_serialization.py` vendors the msrest serializer so there is no runtime + `msrest` dependency. +- `version-tolerant: false` — version-tolerant mode drops `models.*` classes, + which we still expose publicly via `azure.iot.hub.models`. +- `add-credential: false` — this SDK constructs its own auth policy + (`ConnectionStringAuthentication` or `AzureIdentityCredentialAdapter`) and + passes it via `authentication_policy=...`; AutoRest must not inject one. +- `clear-output-folder: true` — wipes the previous generated tree so removed + operations/models are not left behind. +- `no-namespace-folders: true` — keeps `azure.iot.hub.protocol` as a leaf + package rather than nesting into folders that would break the + `from .protocol.models import Device, ...` imports in the manager files. diff --git a/tests/test_digital_twin_client.py b/tests/test_digital_twin_client.py index 0a09de4..d813f28 100644 --- a/tests/test_digital_twin_client.py +++ b/tests/test_digital_twin_client.py @@ -7,7 +7,7 @@ import pytest from azure.iot.hub.digital_twin_client import DigitalTwinClient from azure.iot.hub.auth import ConnectionStringAuthentication -from azure.iot.hub.protocol.iot_hub_gateway_service_ap_is import IotHubGatewayServiceAPIs +from azure.iot.hub.protocol._iot_hub_gateway_service_apis import IotHubGatewayServiceAPIs """---Constants---""" @@ -32,7 +32,7 @@ @pytest.fixture(scope="function", autouse=True) def mock_digital_twin_operations(mocker): mock_digital_twin_operations_init = mocker.patch( - "azure.iot.hub.protocol.iot_hub_gateway_service_ap_is.DigitalTwinOperations" + "azure.iot.hub.protocol._iot_hub_gateway_service_apis.DigitalTwinOperations" ) return mock_digital_twin_operations_init.return_value @@ -86,8 +86,8 @@ def test_connection_string_auth(self, connection_string): client = DigitalTwinClient.from_connection_string(connection_string=connection_string) assert repr(client.auth) == connection_string - assert client.protocol.config.base_url == "https://" + client.auth["HostName"] - assert client.protocol.config.credentials == client.auth + assert client.protocol._client._base_url == "https://" + client.auth["HostName"] + assert client.protocol._config.authentication_policy == client.auth @pytest.mark.it("Sets the auth and protocol attributes") def test_instantiates_auth_and_protocol_attributes(self, digital_twin_client): @@ -156,9 +156,9 @@ def test_token_credential_auth(self, mocker): fake_hostname, mock_azure_identity_TokenCredential ) - assert client.auth._policy._credential == mock_azure_identity_TokenCredential - assert client.protocol.config.base_url == "https://" + fake_hostname - assert client.protocol.config.credentials == client.auth + assert client.auth._credential == mock_azure_identity_TokenCredential + assert client.protocol._client._base_url == "https://" + fake_hostname + assert client.protocol._config.authentication_policy == client.auth @pytest.mark.describe("DigitalTwinClient - .get_digital_twin()") diff --git a/tests/test_iothub_configuration_manager.py b/tests/test_iothub_configuration_manager.py index 74992d2..debd4c1 100644 --- a/tests/test_iothub_configuration_manager.py +++ b/tests/test_iothub_configuration_manager.py @@ -7,7 +7,7 @@ import pytest from azure.iot.hub.iothub_configuration_manager import IoTHubConfigurationManager from azure.iot.hub.auth import ConnectionStringAuthentication -from azure.iot.hub.protocol.iot_hub_gateway_service_ap_is import IotHubGatewayServiceAPIs +from azure.iot.hub.protocol._iot_hub_gateway_service_apis import IotHubGatewayServiceAPIs """---Constants---""" @@ -35,7 +35,7 @@ class fake_configuration_object: @pytest.fixture(scope="function", autouse=True) def mock_configuration_operations(mocker): mock_configuration_operations_init = mocker.patch( - "azure.iot.hub.protocol.iot_hub_gateway_service_ap_is.ConfigurationOperations" + "azure.iot.hub.protocol._iot_hub_gateway_service_apis.ConfigurationOperations" ) return mock_configuration_operations_init.return_value @@ -93,8 +93,8 @@ def test_connection_string_auth(self, connection_string): ) assert repr(client.auth) == connection_string - assert client.protocol.config.base_url == "https://" + client.auth["HostName"] - assert client.protocol.config.credentials == client.auth + assert client.protocol._client._base_url == "https://" + client.auth["HostName"] + assert client.protocol._config.authentication_policy == client.auth @pytest.mark.it("Sets the auth and protocol attributes") def test_instantiates_auth_and_protocol_attributes(self, iothub_configuration_manager): @@ -163,9 +163,9 @@ def test_token_credential_auth(self, mocker): fake_hostname, mock_azure_identity_TokenCredential ) - assert client.auth._policy._credential == mock_azure_identity_TokenCredential - assert client.protocol.config.base_url == "https://" + fake_hostname - assert client.protocol.config.credentials == client.auth + assert client.auth._credential == mock_azure_identity_TokenCredential + assert client.protocol._client._base_url == "https://" + fake_hostname + assert client.protocol._config.authentication_policy == client.auth @pytest.mark.describe("IoTHubConfigurationManager - .get_configuration()") diff --git a/tests/test_iothub_http_runtime_manager.py b/tests/test_iothub_http_runtime_manager.py index 0194a56..ffa0cf0 100644 --- a/tests/test_iothub_http_runtime_manager.py +++ b/tests/test_iothub_http_runtime_manager.py @@ -7,7 +7,7 @@ import pytest from azure.iot.hub.iothub_http_runtime_manager import IoTHubHttpRuntimeManager from azure.iot.hub.auth import ConnectionStringAuthentication -from azure.iot.hub.protocol.iot_hub_gateway_service_ap_is import IotHubGatewayServiceAPIs +from azure.iot.hub.protocol._iot_hub_gateway_service_apis import IotHubGatewayServiceAPIs """---Constants---""" @@ -24,7 +24,7 @@ @pytest.fixture(scope="function", autouse=True) def mock_http_runtime_operations(mocker): mock_http_runtime_operations_init = mocker.patch( - "azure.iot.hub.protocol.iot_hub_gateway_service_ap_is.CloudToDeviceMessagesOperations" + "azure.iot.hub.protocol._iot_hub_gateway_service_apis.CloudToDeviceMessagesOperations" ) return mock_http_runtime_operations_init.return_value @@ -80,8 +80,8 @@ def test_connection_string_auth(self, connection_string): ) assert repr(client.auth) == connection_string - assert client.protocol.config.base_url == "https://" + client.auth["HostName"] - assert client.protocol.config.credentials == client.auth + assert client.protocol._client._base_url == "https://" + client.auth["HostName"] + assert client.protocol._config.authentication_policy == client.auth @pytest.mark.it("Sets the auth and protocol attributes") def test_instantiates_auth_and_protocol_attributes(self, iothub_http_runtime_manager): @@ -150,9 +150,9 @@ def test_token_credential_auth(self, mocker): fake_hostname, mock_azure_identity_TokenCredential ) - assert client.auth._policy._credential == mock_azure_identity_TokenCredential - assert client.protocol.config.base_url == "https://" + fake_hostname - assert client.protocol.config.credentials == client.auth + assert client.auth._credential == mock_azure_identity_TokenCredential + assert client.protocol._client._base_url == "https://" + fake_hostname + assert client.protocol._config.authentication_policy == client.auth @pytest.mark.describe("IoTHubHttpRuntimeManager - .receive_feedback_notification()") diff --git a/tests/test_iothub_registry_manager.py b/tests/test_iothub_registry_manager.py index 2104a0a..d858345 100644 --- a/tests/test_iothub_registry_manager.py +++ b/tests/test_iothub_registry_manager.py @@ -8,7 +8,7 @@ from azure.iot.hub.protocol.models import AuthenticationMechanism, DeviceCapabilities from azure.iot.hub.iothub_registry_manager import IoTHubRegistryManager from azure.iot.hub import iothub_amqp_client -from azure.iot.hub.protocol.iot_hub_gateway_service_ap_is import IotHubGatewayServiceAPIs +from azure.iot.hub.protocol._iot_hub_gateway_service_apis import IotHubGatewayServiceAPIs from azure.iot.hub import TransportType """---Constants---""" @@ -69,7 +69,7 @@ class Fake_direct_method_request_with_payload_none: @pytest.fixture(scope="function", autouse=True) def mock_devices_operations(mocker): mock_devices_operations_init = mocker.patch( - "azure.iot.hub.protocol.iot_hub_gateway_service_ap_is.DevicesOperations" + "azure.iot.hub.protocol._iot_hub_gateway_service_apis.DevicesOperations" ) return mock_devices_operations_init.return_value @@ -77,7 +77,7 @@ def mock_devices_operations(mocker): @pytest.fixture(scope="function", autouse=True) def mock_modules_operations(mocker): mock_modules_operations_init = mocker.patch( - "azure.iot.hub.protocol.iot_hub_gateway_service_ap_is.ModulesOperations" + "azure.iot.hub.protocol._iot_hub_gateway_service_apis.ModulesOperations" ) return mock_modules_operations_init.return_value @@ -85,7 +85,7 @@ def mock_modules_operations(mocker): @pytest.fixture(scope="function", autouse=True) def mock_statistics_operations(mocker): mock_statistics_operations_init = mocker.patch( - "azure.iot.hub.protocol.iot_hub_gateway_service_ap_is.StatisticsOperations" + "azure.iot.hub.protocol._iot_hub_gateway_service_apis.StatisticsOperations" ) return mock_statistics_operations_init.return_value @@ -93,7 +93,7 @@ def mock_statistics_operations(mocker): @pytest.fixture(scope="function", autouse=True) def mock_bulk_registry_operations(mocker): mock_bulk_registry_operations_init = mocker.patch( - "azure.iot.hub.protocol.iot_hub_gateway_service_ap_is.BulkRegistryOperations" + "azure.iot.hub.protocol._iot_hub_gateway_service_apis.BulkRegistryOperations" ) return mock_bulk_registry_operations_init.return_value @@ -101,7 +101,7 @@ def mock_bulk_registry_operations(mocker): @pytest.fixture(scope="function", autouse=True) def mock_query_operations(mocker): mock_query_operations_init = mocker.patch( - "azure.iot.hub.protocol.iot_hub_gateway_service_ap_is.QueryOperations" + "azure.iot.hub.protocol._iot_hub_gateway_service_apis.QueryOperations" ) return mock_query_operations_init.return_value @@ -171,15 +171,15 @@ def test_connection_string_auth(self, mocker, connection_string): client = IoTHubRegistryManager.from_connection_string(connection_string=connection_string) - assert repr(client.protocol.config.credentials) == connection_string + assert repr(client.protocol._config.authentication_policy) == connection_string assert ( - client.protocol.config.base_url - == "https://" + client.protocol.config.credentials["HostName"] + client.protocol._client._base_url + == "https://" + client.protocol._config.authentication_policy["HostName"] ) assert amqp_client_init_mock.call_args == mocker.call( - client.protocol.config.credentials["HostName"], - client.protocol.config.credentials["SharedAccessKeyName"], - client.protocol.config.credentials["SharedAccessKey"], + client.protocol._config.authentication_policy["HostName"], + client.protocol._config.authentication_policy["SharedAccessKeyName"], + client.protocol._config.authentication_policy["SharedAccessKey"], TransportType.Amqp, ) @@ -215,15 +215,15 @@ def test_connection_string_auth_amqp_over_websocket(self, mocker, connection_str client = IoTHubRegistryManager.from_connection_string(connection_string=connection_string, transport_type=TransportType.AmqpOverWebsocket) - assert repr(client.protocol.config.credentials) == connection_string + assert repr(client.protocol._config.authentication_policy) == connection_string assert ( - client.protocol.config.base_url - == "https://" + client.protocol.config.credentials["HostName"] + client.protocol._client._base_url + == "https://" + client.protocol._config.authentication_policy["HostName"] ) assert amqp_client_init_mock.call_args == mocker.call( - client.protocol.config.credentials["HostName"], - client.protocol.config.credentials["SharedAccessKeyName"], - client.protocol.config.credentials["SharedAccessKey"], + client.protocol._config.authentication_policy["HostName"], + client.protocol._config.authentication_policy["SharedAccessKeyName"], + client.protocol._config.authentication_policy["SharedAccessKey"], TransportType.AmqpOverWebsocket, ) @@ -287,10 +287,10 @@ def test_token_credential_auth(self, mocker): ) assert ( - client.protocol.config.credentials._policy._credential + client.protocol._config.authentication_policy._credential == mock_azure_identity_TokenCredential ) - assert client.protocol.config.base_url == "https://" + fake_hostname + assert client.protocol._client._base_url == "https://" + fake_hostname assert amqp_client_init_mock.call_args == mocker.call( fake_hostname, mock_azure_identity_TokenCredential, transport_type=TransportType.Amqp ) @@ -303,10 +303,10 @@ def test_token_credential_auth_with_amqp_over_websocket(self, mocker): ) assert ( - client.protocol.config.credentials._policy._credential + client.protocol._config.authentication_policy._credential == mock_azure_identity_TokenCredential ) - assert client.protocol.config.base_url == "https://" + fake_hostname + assert client.protocol._client._base_url == "https://" + fake_hostname assert amqp_client_init_mock.call_args == mocker.call( fake_hostname, mock_azure_identity_TokenCredential, transport_type=TransportType.AmqpOverWebsocket ) @@ -1269,9 +1269,9 @@ class TestQueryIoTHub(object): def test_query_iot_hub(self, mocker, mock_query_operations, iothub_registry_manager): iothub_registry_manager.query_iot_hub(fake_query_specification) assert mock_query_operations.get_twins.call_count == 1 - assert mock_query_operations.get_twins.call_args == mocker.call( - fake_query_specification, None, None, None, True - ) + args, kwargs = mock_query_operations.get_twins.call_args + assert args == (fake_query_specification, None, None) + assert callable(kwargs.get("cls")) @pytest.mark.describe("IoTHubRegistryManager - .query_iot_hub(continuation_token)") @@ -1281,9 +1281,9 @@ def test_query_iot_hub(self, mocker, mock_query_operations, iothub_registry_mana continuation_token = 42 iothub_registry_manager.query_iot_hub(fake_query_specification, continuation_token) assert mock_query_operations.get_twins.call_count == 1 - assert mock_query_operations.get_twins.call_args == mocker.call( - fake_query_specification, continuation_token, None, None, True - ) + args, kwargs = mock_query_operations.get_twins.call_args + assert args == (fake_query_specification, continuation_token, None) + assert callable(kwargs.get("cls")) @pytest.mark.describe("IoTHubRegistryManager - .query_iot_hub(continuation_token, max_item_count)") @@ -1296,9 +1296,9 @@ def test_query_iot_hub(self, mocker, mock_query_operations, iothub_registry_mana fake_query_specification, continuation_token, max_item_count ) assert mock_query_operations.get_twins.call_count == 1 - assert mock_query_operations.get_twins.call_args == mocker.call( - fake_query_specification, continuation_token, max_item_count, None, True - ) + args, kwargs = mock_query_operations.get_twins.call_args + assert args == (fake_query_specification, continuation_token, max_item_count) + assert callable(kwargs.get("cls")) @pytest.mark.describe("IoTHubRegistryManager - .get_twin()") diff --git a/tests/test_job_manager.py b/tests/test_job_manager.py index b0626ba..8eac6d5 100644 --- a/tests/test_job_manager.py +++ b/tests/test_job_manager.py @@ -7,7 +7,7 @@ import pytest from azure.iot.hub.iothub_job_manager import IoTHubJobManager from azure.iot.hub.auth import ConnectionStringAuthentication -from azure.iot.hub.protocol.iot_hub_gateway_service_ap_is import IotHubGatewayServiceAPIs +from azure.iot.hub.protocol._iot_hub_gateway_service_apis import IotHubGatewayServiceAPIs """---Constants---""" @@ -28,7 +28,7 @@ @pytest.fixture(scope="function", autouse=True) def mock_job_client_operations(mocker): mock_job_client_operations_init = mocker.patch( - "azure.iot.hub.protocol.iot_hub_gateway_service_ap_is.JobsOperations" + "azure.iot.hub.protocol._iot_hub_gateway_service_apis.JobsOperations" ) return mock_job_client_operations_init.return_value @@ -82,8 +82,8 @@ def test_connection_string_auth(self, connection_string): client = IoTHubJobManager.from_connection_string(connection_string=connection_string) assert repr(client.auth) == connection_string - assert client.protocol.config.base_url == "https://" + client.auth["HostName"] - assert client.protocol.config.credentials == client.auth + assert client.protocol._client._base_url == "https://" + client.auth["HostName"] + assert client.protocol._config.authentication_policy == client.auth @pytest.mark.it("Sets the auth and protocol attributes") def test_instantiates_auth_and_protocol_attributes(self, iothub_job_manager): @@ -152,9 +152,9 @@ def test_token_credential_auth(self, mocker): fake_hostname, mock_azure_identity_TokenCredential ) - assert client.auth._policy._credential == mock_azure_identity_TokenCredential - assert client.protocol.config.base_url == "https://" + fake_hostname - assert client.protocol.config.credentials == client.auth + assert client.auth._credential == mock_azure_identity_TokenCredential + assert client.protocol._client._base_url == "https://" + fake_hostname + assert client.protocol._config.authentication_policy == client.auth @pytest.mark.describe("IoTHubJobManager - .create_import_export_job()") From 41cd2e99f6e8ccb378d478952a31f2bb6bf21b09 Mon Sep 17 00:00:00 2001 From: Ethan Ann Date: Thu, 20 Aug 2026 09:06:11 -0400 Subject: [PATCH 2/2] Bump version to 3.0.0b2 --- src/azure/iot/hub/constant.py | 2 +- src/azure/iot/hub/protocol/_version.py | 2 +- swagger/README.md | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/azure/iot/hub/constant.py b/src/azure/iot/hub/constant.py index 8735b94..ca3ce09 100644 --- a/src/azure/iot/hub/constant.py +++ b/src/azure/iot/hub/constant.py @@ -6,4 +6,4 @@ """This module defines constants for use across the azure-iot-hub package """ -VERSION = "3.0.0b1" +VERSION = "3.0.0b2" diff --git a/src/azure/iot/hub/protocol/_version.py b/src/azure/iot/hub/protocol/_version.py index 5819b88..9764467 100644 --- a/src/azure/iot/hub/protocol/_version.py +++ b/src/azure/iot/hub/protocol/_version.py @@ -6,4 +6,4 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -VERSION = "3.0.0b1" +VERSION = "3.0.0b2" diff --git a/swagger/README.md b/swagger/README.md index f77a3a5..6082dc8 100644 --- a/swagger/README.md +++ b/swagger/README.md @@ -24,7 +24,7 @@ input-file: ../service.json output-folder: ../src/azure/iot/hub/protocol namespace: azure.iot.hub.protocol package-name: azure-iot-hub -package-version: 3.0.0b1 +package-version: 3.0.0b2 license-header: MICROSOFT_MIT_NO_VERSION clear-output-folder: true no-namespace-folders: true