File: _patch.py

package info (click to toggle)
python-azure 20250603%2Bgit-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, trixie
  • size: 851,724 kB
  • sloc: python: 7,362,925; ansic: 804; javascript: 287; makefile: 195; sh: 145; xml: 109
file content (873 lines) | stat: -rw-r--r-- 46,420 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
# ------------------------------------
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
# ------------------------------------
"""Customize generated code here.

Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize
"""

import sys
from io import IOBase
from typing import IO, Any, Callable, Dict, Optional, TypeVar, Union, cast

from azure.core.exceptions import (
    ClientAuthenticationError,
    HttpResponseError,
    ResourceExistsError,
    ResourceNotFoundError,
    ResourceNotModifiedError,
    map_error,
)
from azure.core.paging import ItemPaged
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpResponse
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.core.utils import case_insensitive_dict

from ._operations import (
    DeviceRegistrationStateOperations as DeviceRegistrationStateOperationsGenerated,
)
from ._operations import EnrollmentGroupOperations as EnrollmentGroupOperationsGenerated
from ._operations import EnrollmentOperations as EnrollmentOperationsGenerated
from ._operations import (
    build_device_registration_state_query_request,
    build_enrollment_group_query_request,
    build_enrollment_query_request,
)

if sys.version_info >= (3, 9):
    from collections.abc import MutableMapping
else:
    from typing import MutableMapping

JSON = MutableMapping[str, Any]  # pylint: disable=unsubscriptable-object
T = TypeVar("T")
ClsType = Optional[
    Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]
]


def _extract_data_default(pipeline_response, **kwargs):
    response = pipeline_response.http_response
    response_json = response.json() if response.content else None
    continuation = response.headers.get("x-ms-continuation", None)
    cls: ClsType[JSON] = kwargs.pop("cls", None)
    if cls:
        return cls(pipeline_response, cast(JSON, response_json), {})
    return continuation or None, cast(JSON, response_json)


class EnrollmentOperations(EnrollmentOperationsGenerated):
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.iot.deviceprovisioning.DeviceProvisioningClient`'s
        :attr:`enrollment` attribute.
    """

    @distributed_trace
    def query(  # type: ignore[override]
        self,
        query_specification: Union[JSON, IO],
        *,
        top: Optional[int] = None,
        **kwargs: Any,
    ) -> ItemPaged[JSON]:
        """Query the device enrollment records.

        Query the device enrollment records.

        :param query_specification: The query specification. Is either a JSON type or a IO type.
         Required.
        :type query_specification: JSON or IO
        :keyword top: Page size. Default value is None.
        :paramtype top: Optional[int]
        :return: list of JSON object
        :rtype: ~azure.core.paging.ItemPaged[JSON]
        :raises ~azure.core.exceptions.HttpResponseError:

        Example:
            .. code-block:: python

                # JSON input template you can fill out and use as your body input.
                query_specification = {
                    "query": "str"  # Required.
                }

                # response body for status code(s): 200
                response == [
                    {
                        "attestation": {
                            "type": "str",  # Attestation Type. Required. Known values
                              are: "none", "tpm", "x509", and "symmetricKey".
                            "symmetricKey": {
                                "primaryKey": "str",  # Optional. Primary symmetric
                                  key.
                                "secondaryKey": "str"  # Optional. Secondary
                                  symmetric key.
                            },
                            "tpm": {
                                "endorsementKey": "str",  # Required.
                                "storageRootKey": "str"  # Optional. TPM attestation
                                  method.
                            },
                            "x509": {
                                "caReferences": {
                                    "primary": "str",  # Optional. Primary and
                                      secondary CA references.
                                    "secondary": "str"  # Optional. Primary and
                                      secondary CA references.
                                },
                                "clientCertificates": {
                                    "primary": {
                                        "certificate": "str",  # Optional.
                                          Certificate and Certificate info.
                                        "info": {
                                            "issuerName": "str",  #
                                              Required.
                                            "notAfterUtc": "2020-02-20
                                              00:00:00",  # Required.
                                            "notBeforeUtc": "2020-02-20
                                              00:00:00",  # Required.
                                            "serialNumber": "str",  #
                                              Required.
                                            "sha1Thumbprint": "str",  #
                                              Required.
                                            "sha256Thumbprint": "str",  #
                                              Required.
                                            "subjectName": "str",  #
                                              Required.
                                            "version": 0  # Required.
                                        }
                                    },
                                    "secondary": {
                                        "certificate": "str",  # Optional.
                                          Certificate and Certificate info.
                                        "info": {
                                            "issuerName": "str",  #
                                              Required.
                                            "notAfterUtc": "2020-02-20
                                              00:00:00",  # Required.
                                            "notBeforeUtc": "2020-02-20
                                              00:00:00",  # Required.
                                            "serialNumber": "str",  #
                                              Required.
                                            "sha1Thumbprint": "str",  #
                                              Required.
                                            "sha256Thumbprint": "str",  #
                                              Required.
                                            "subjectName": "str",  #
                                              Required.
                                            "version": 0  # Required.
                                        }
                                    }
                                },
                                "signingCertificates": {
                                    "primary": {
                                        "certificate": "str",  # Optional.
                                          Certificate and Certificate info.
                                        "info": {
                                            "issuerName": "str",  #
                                              Required.
                                            "notAfterUtc": "2020-02-20
                                              00:00:00",  # Required.
                                            "notBeforeUtc": "2020-02-20
                                              00:00:00",  # Required.
                                            "serialNumber": "str",  #
                                              Required.
                                            "sha1Thumbprint": "str",  #
                                              Required.
                                            "sha256Thumbprint": "str",  #
                                              Required.
                                            "subjectName": "str",  #
                                              Required.
                                            "version": 0  # Required.
                                        }
                                    },
                                    "secondary": {
                                        "certificate": "str",  # Optional.
                                          Certificate and Certificate info.
                                        "info": {
                                            "issuerName": "str",  #
                                              Required.
                                            "notAfterUtc": "2020-02-20
                                              00:00:00",  # Required.
                                            "notBeforeUtc": "2020-02-20
                                              00:00:00",  # Required.
                                            "serialNumber": "str",  #
                                              Required.
                                            "sha1Thumbprint": "str",  #
                                              Required.
                                            "sha256Thumbprint": "str",  #
                                              Required.
                                            "subjectName": "str",  #
                                              Required.
                                            "version": 0  # Required.
                                        }
                                    }
                                }
                            }
                        },
                        "registrationId": "str",  # This id is used to uniquely identify a
                          device registration of an enrollment."nA case-insensitive string (up to 128
                          characters long) of alphanumeric characters plus certain special characters :
                          . _ -. No special characters allowed at start or end. Required.
                        "allocationPolicy": "str",  # Optional. The allocation policy of this
                          resource. This policy overrides the tenant level allocation policy for this
                          individual enrollment or enrollment group. Possible values include 'hashed':
                          Linked IoT hubs are equally likely to have devices provisioned to them,
                          'geoLatency':  Devices are provisioned to an IoT hub with the lowest latency
                          to the device.If multiple linked IoT hubs would provide the same lowest
                          latency, the provisioning service hashes devices across those hubs, 'static'
                          : Specification of the desired IoT hub in the enrollment list takes priority
                          over the service-level allocation policy, 'custom': Devices are provisioned
                          to an IoT hub based on your own custom logic. The provisioning service passes
                          information about the device to the logic, and the logic returns the desired
                          IoT hub as well as the desired initial configuration. We recommend using
                          Azure Functions to host your logic. Known values are: "hashed", "geoLatency",
                          "static", and "custom".
                        "capabilities": {
                            "iotEdge": False  # Default value is False. If set to true,
                              this device is an IoTEdge device. Required.
                        },
                        "createdDateTimeUtc": "2020-02-20 00:00:00",  # Optional. The
                          DateTime this resource was created.
                        "customAllocationDefinition": {
                            "apiVersion": "str",  # The API version of the provisioning
                              service types (such as Enrollment) sent in the custom
                              allocation request. Minimum supported version: "2018-09-01-preview".
                              Required.
                            "webhookUrl": "str"  # The webhook URL used for allocation
                              requests. Required.
                        },
                        "deviceId": "str",  # Optional. Desired IoT Hub device ID (optional).
                        "etag": "str",  # Optional. The entity tag associated with the
                          resource.
                        "initialTwin": {
                            "properties": {
                                "desired": {
                                    "count": 0,  # Optional. Number of properties
                                      in the TwinCollection.
                                    "metadata": {
                                        "lastUpdated": "2020-02-20 00:00:00",
                                          # Optional. Last time the TwinCollection was updated.
                                        "lastUpdatedVersion": 0  # Optional.
                                          This is null for reported properties metadata and is not null
                                          for desired properties metadata.
                                    },
                                    "version": 0  # Optional. Version of the
                                      TwinCollection.
                                }
                            },
                            "tags": {
                                "count": 0,  # Optional. Number of properties in the
                                  TwinCollection.
                                "metadata": {
                                    "lastUpdated": "2020-02-20 00:00:00",  #
                                      Optional. Last time the TwinCollection was updated.
                                    "lastUpdatedVersion": 0  # Optional. This is
                                      null for reported properties metadata and is not null for desired
                                      properties metadata.
                                },
                                "version": 0  # Optional. Version of the
                                  TwinCollection.
                            }
                        },
                        "iotHubHostName": "str",  # Optional. The Iot Hub host name.
                        "iotHubs": [
                            "str"  # Optional. The list of IoT Hub hostnames the
                              device(s) in this resource can be allocated to. Must be a subset of
                              tenant level list of IoT hubs.
                        ],
                        "lastUpdatedDateTimeUtc": "2020-02-20 00:00:00",  # Optional. The
                          DateTime this resource was last updated.
                        "optionalDeviceInformation": {
                            "count": 0,  # Optional. Number of properties in the
                              TwinCollection.
                            "metadata": {
                                "lastUpdated": "2020-02-20 00:00:00",  # Optional.
                                  Last time the TwinCollection was updated.
                                "lastUpdatedVersion": 0  # Optional. This is null for
                                  reported properties metadata and is not null for desired properties
                                  metadata.
                            },
                            "version": 0  # Optional. Version of the TwinCollection.
                        },
                        "provisioningStatus": "enabled",  # Optional. Default value is
                          "enabled". The provisioning status. Known values are: "enabled" and
                          "disabled".
                        "registrationState": {
                            "assignedHub": "str",  # Optional. Assigned Azure IoT Hub.
                            "createdDateTimeUtc": "2020-02-20 00:00:00",  # Optional.
                              Registration create date time (in UTC).
                            "deviceId": "str",  # Optional. Device ID.
                            "errorCode": 0,  # Optional. Error code.
                            "errorMessage": "str",  # Optional. Error message.
                            "etag": "str",  # Optional. The entity tag associated with
                              the resource.
                            "lastUpdatedDateTimeUtc": "2020-02-20 00:00:00",  # Optional.
                              Last updated date time (in UTC).
                            "payload": {},  # Optional. Custom allocation payload
                              returned from the webhook to the device.
                            "registrationId": "str",  # Optional. This id is used to
                              uniquely identify a device registration of an enrollment."nA
                              case-insensitive string (up to 128 characters long) of alphanumeric
                              characters plus certain special characters : . _ -. No special characters
                              allowed at start or end.
                            "status": "str",  # Optional. Enrollment status. Known values
                              are: "unassigned", "assigning", "assigned", "failed", and "disabled".
                            "substatus": "str"  # Optional. Substatus for 'Assigned'
                              devices. Possible values include - 'initialAssignment': Device has been
                              assigned to an IoT hub for the first time, 'deviceDataMigrated': Device
                              has been assigned to a different IoT hub and its device data was migrated
                              from the previously assigned IoT hub. Device data was removed from the
                              previously assigned IoT hub, 'deviceDataReset':  Device has been assigned
                              to a different IoT hub and its device data was populated from the initial
                              state stored in the enrollment. Device data was removed from the
                              previously assigned IoT hub, 'reprovisionedToInitialAssignment': Device
                              has been re-provisioned to a previously assigned IoT hub. Known values
                              are: "initialAssignment", "deviceDataMigrated", "deviceDataReset", and
                              "reprovisionedToInitialAssignment".
                        },
                        "reprovisionPolicy": {
                            "migrateDeviceData": True,  # Default value is True. When set
                              to true (default), the Device Provisioning Service will migrate the
                              device's data (twin, device capabilities, and device ID) from one IoT hub
                              to another during an IoT hub assignment update. If set to false, the
                              Device Provisioning Service will reset the device's data to the initial
                              desired configuration stored in the corresponding enrollment list.
                            "updateHubAssignment": True  # Default value is True. When
                              set to true (default), the Device Provisioning Service will evaluate the
                              device's IoT Hub assignment and update it if necessary for any
                              provisioning requests beyond the first from a given device. If set to
                              false, the device will stay assigned to its current IoT hub.
                        }
                    }
                ]
        """
        error_map = {
            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 = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop(
            "content_type", _headers.pop("Content-Type", None)
        )

        content_type = content_type or "application/json"
        _json = None
        _content = None
        if isinstance(query_specification, (IOBase, bytes)):
            _content = query_specification
        else:
            _json = query_specification

        def prepare_request(continuation_token=None):
            if not continuation_token:
                request = build_enrollment_query_request(
                    x_ms_max_item_count=top,
                    content_type=content_type,
                    api_version=self._config.api_version,
                    json=_json,
                    content=_content,
                    headers=_headers,
                    params=_params,
                    **kwargs,
                )
            else:
                request = build_enrollment_query_request(
                    x_ms_max_item_count=top,
                    x_ms_continuation=continuation_token,
                    content_type=content_type,
                    api_version=self._config.api_version,
                    json=_json,
                    content=_content,
                    headers=_headers,
                    params=_params,
                    **kwargs,
                )
            request.url = self._client.format_url(request.url)
            return request

        def get_next(continuation_token: Optional[str] = None):
            request = prepare_request(continuation_token)
            pipeline_response = self._client._pipeline.run(  # type: ignore # pylint: disable=protected-access
                request, stream=False, **kwargs
            )
            return pipeline_response

        def _extract_data(pipeline_response):
            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)
            return _extract_data_default(pipeline_response)

        return ItemPaged(get_next=get_next, extract_data=_extract_data)


class EnrollmentGroupOperations(EnrollmentGroupOperationsGenerated):
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.iot.deviceprovisioning.DeviceProvisioningClient`'s
        :attr:`enrollment_group` attribute.
    """

    @distributed_trace
    def query(  # type: ignore[override]
        self,
        query_specification: Union[JSON, IO],
        *,
        top: Optional[int] = None,
        **kwargs: Any,
    ) -> ItemPaged[JSON]:
        """Query the device enrollment groups.

        Query the device enrollment groups.

        :param query_specification: The query specification. Is either a JSON type or a IO type.
         Required.
        :type query_specification: JSON or IO
        :keyword top: Page size. Default value is None.
        :paramtype top: Optional[int]
        :return: list of JSON object
        :rtype: ~azure.core.paging.ItemPaged[JSON]
        :raises ~azure.core.exceptions.HttpResponseError:

        Example:
            .. code-block:: python

                # JSON input template you can fill out and use as your body input.
                query_specification = {
                    "query": "str"  # Required.
                }

                # response body for status code(s): 200
                response == [
                    {
                        "attestation": {
                            "type": "str",  # Attestation Type. Required. Known values
                              are: "none", "tpm", "x509", and "symmetricKey".
                            "symmetricKey": {
                                "primaryKey": "str",  # Optional. Primary symmetric
                                  key.
                                "secondaryKey": "str"  # Optional. Secondary
                                  symmetric key.
                            },
                            "tpm": {
                                "endorsementKey": "str",  # Required.
                                "storageRootKey": "str"  # Optional. TPM attestation
                                  method.
                            },
                            "x509": {
                                "caReferences": {
                                    "primary": "str",  # Optional. Primary and
                                      secondary CA references.
                                    "secondary": "str"  # Optional. Primary and
                                      secondary CA references.
                                },
                                "clientCertificates": {
                                    "primary": {
                                        "certificate": "str",  # Optional.
                                          Certificate and Certificate info.
                                        "info": {
                                            "issuerName": "str",  #
                                              Required.
                                            "notAfterUtc": "2020-02-20
                                              00:00:00",  # Required.
                                            "notBeforeUtc": "2020-02-20
                                              00:00:00",  # Required.
                                            "serialNumber": "str",  #
                                              Required.
                                            "sha1Thumbprint": "str",  #
                                              Required.
                                            "sha256Thumbprint": "str",  #
                                              Required.
                                            "subjectName": "str",  #
                                              Required.
                                            "version": 0  # Required.
                                        }
                                    },
                                    "secondary": {
                                        "certificate": "str",  # Optional.
                                          Certificate and Certificate info.
                                        "info": {
                                            "issuerName": "str",  #
                                              Required.
                                            "notAfterUtc": "2020-02-20
                                              00:00:00",  # Required.
                                            "notBeforeUtc": "2020-02-20
                                              00:00:00",  # Required.
                                            "serialNumber": "str",  #
                                              Required.
                                            "sha1Thumbprint": "str",  #
                                              Required.
                                            "sha256Thumbprint": "str",  #
                                              Required.
                                            "subjectName": "str",  #
                                              Required.
                                            "version": 0  # Required.
                                        }
                                    }
                                },
                                "signingCertificates": {
                                    "primary": {
                                        "certificate": "str",  # Optional.
                                          Certificate and Certificate info.
                                        "info": {
                                            "issuerName": "str",  #
                                              Required.
                                            "notAfterUtc": "2020-02-20
                                              00:00:00",  # Required.
                                            "notBeforeUtc": "2020-02-20
                                              00:00:00",  # Required.
                                            "serialNumber": "str",  #
                                              Required.
                                            "sha1Thumbprint": "str",  #
                                              Required.
                                            "sha256Thumbprint": "str",  #
                                              Required.
                                            "subjectName": "str",  #
                                              Required.
                                            "version": 0  # Required.
                                        }
                                    },
                                    "secondary": {
                                        "certificate": "str",  # Optional.
                                          Certificate and Certificate info.
                                        "info": {
                                            "issuerName": "str",  #
                                              Required.
                                            "notAfterUtc": "2020-02-20
                                              00:00:00",  # Required.
                                            "notBeforeUtc": "2020-02-20
                                              00:00:00",  # Required.
                                            "serialNumber": "str",  #
                                              Required.
                                            "sha1Thumbprint": "str",  #
                                              Required.
                                            "sha256Thumbprint": "str",  #
                                              Required.
                                            "subjectName": "str",  #
                                              Required.
                                            "version": 0  # Required.
                                        }
                                    }
                                }
                            }
                        },
                        "enrollmentGroupId": "str",  # Enrollment Group ID. Required.
                        "allocationPolicy": "str",  # Optional. The allocation policy of this
                          resource. This policy overrides the tenant level allocation policy for this
                          individual enrollment or enrollment group. Possible values include 'hashed':
                          Linked IoT hubs are equally likely to have devices provisioned to them,
                          'geoLatency':  Devices are provisioned to an IoT hub with the lowest latency
                          to the device.If multiple linked IoT hubs would provide the same lowest
                          latency, the provisioning service hashes devices across those hubs, 'static'
                          : Specification of the desired IoT hub in the enrollment list takes priority
                          over the service-level allocation policy, 'custom': Devices are provisioned
                          to an IoT hub based on your own custom logic. The provisioning service passes
                          information about the device to the logic, and the logic returns the desired
                          IoT hub as well as the desired initial configuration. We recommend using
                          Azure Functions to host your logic. Known values are: "hashed", "geoLatency",
                          "static", and "custom".
                        "capabilities": {
                            "iotEdge": False  # Default value is False. If set to true,
                              this device is an IoTEdge device. Required.
                        },
                        "createdDateTimeUtc": "2020-02-20 00:00:00",  # Optional. The
                          DateTime this resource was created.
                        "customAllocationDefinition": {
                            "apiVersion": "str",  # The API version of the provisioning
                              service types (such as Enrollment) sent in the custom
                              allocation request. Minimum supported version: "2018-09-01-preview".
                              Required.
                            "webhookUrl": "str"  # The webhook URL used for allocation
                              requests. Required.
                        },
                        "etag": "str",  # Optional. The entity tag associated with the
                          resource.
                        "initialTwin": {
                            "properties": {
                                "desired": {
                                    "count": 0,  # Optional. Number of properties
                                      in the TwinCollection.
                                    "metadata": {
                                        "lastUpdated": "2020-02-20 00:00:00",
                                          # Optional. Last time the TwinCollection was updated.
                                        "lastUpdatedVersion": 0  # Optional.
                                          This is null for reported properties metadata and is not null
                                          for desired properties metadata.
                                    },
                                    "version": 0  # Optional. Version of the
                                      TwinCollection.
                                }
                            },
                            "tags": {
                                "count": 0,  # Optional. Number of properties in the
                                  TwinCollection.
                                "metadata": {
                                    "lastUpdated": "2020-02-20 00:00:00",  #
                                      Optional. Last time the TwinCollection was updated.
                                    "lastUpdatedVersion": 0  # Optional. This is
                                      null for reported properties metadata and is not null for desired
                                      properties metadata.
                                },
                                "version": 0  # Optional. Version of the
                                  TwinCollection.
                            }
                        },
                        "iotHubHostName": "str",  # Optional. The Iot Hub host name.
                        "iotHubs": [
                            "str"  # Optional. The list of IoT Hub hostnames the
                              device(s) in this resource can be allocated to. Must be a subset of
                              tenant level list of IoT hubs.
                        ],
                        "lastUpdatedDateTimeUtc": "2020-02-20 00:00:00",  # Optional. The
                          DateTime this resource was last updated.
                        "provisioningStatus": "enabled",  # Optional. Default value is
                          "enabled". The provisioning status. Known values are: "enabled" and
                          "disabled".
                        "reprovisionPolicy": {
                            "migrateDeviceData": True,  # Default value is True. When set
                              to true (default), the Device Provisioning Service will migrate the
                              device's data (twin, device capabilities, and device ID) from one IoT hub
                              to another during an IoT hub assignment update. If set to false, the
                              Device Provisioning Service will reset the device's data to the initial
                              desired configuration stored in the corresponding enrollment list.
                            "updateHubAssignment": True  # Default value is True. When
                              set to true (default), the Device Provisioning Service will evaluate the
                              device's IoT Hub assignment and update it if necessary for any
                              provisioning requests beyond the first from a given device. If set to
                              false, the device will stay assigned to its current IoT hub.
                        }
                    }
                ]
        """
        error_map = {
            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 = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))

        content_type = content_type or "application/json"
        _json = None
        _content = None
        if isinstance(query_specification, (IOBase, bytes)):
            _content = query_specification
        else:
            _json = query_specification

        def prepare_request(continuation_token=None):
            if not continuation_token:
                request = build_enrollment_group_query_request(
                    x_ms_max_item_count=top,
                    content_type=content_type,
                    api_version=self._config.api_version,
                    json=_json,
                    content=_content,
                    headers=_headers,
                    params=_params,
                    **kwargs,
                )
            else:
                request = build_enrollment_group_query_request(
                    x_ms_max_item_count=top,
                    x_ms_continuation=continuation_token,
                    content_type=content_type,
                    api_version=self._config.api_version,
                    json=_json,
                    content=_content,
                    headers=_headers,
                    params=_params,
                    **kwargs,
                )
            request.url = self._client.format_url(request.url)
            return request

        def get_next(continuation_token: Optional[str] = None):
            request = prepare_request(continuation_token)
            pipeline_response = self._client._pipeline.run(  # type: ignore # pylint: disable=protected-access
                request, stream=False, **kwargs
            )
            return pipeline_response

        def _extract_data(pipeline_response):
            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)
            return _extract_data_default(pipeline_response)

        return ItemPaged(get_next=get_next, extract_data=_extract_data)


class DeviceRegistrationStateOperations(DeviceRegistrationStateOperationsGenerated):
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.iot.deviceprovisioning.DeviceProvisioningClient`'s
        :attr:`device_registration_state` attribute.
    """

    @distributed_trace
    def query(  # type: ignore[override]
        self,
        id: str,
        *,
        top: Optional[int] = None,
        **kwargs: Any,
    ) -> ItemPaged[JSON]:
        """Gets the registration state of devices in this enrollmentGroup.

        Gets the registration state of devices in this enrollmentGroup.

        :param id: Enrollment group ID. Required.
        :type id: str
        :keyword top: Page size. Default value is None.
        :paramtype top: Optional[int]
        :return: list of JSON object
        :rtype: ~azure.core.paging.ItemPaged[JSON]
        :raises ~azure.core.exceptions.HttpResponseError:

        Example:
            .. code-block:: python

                # response body for status code(s): 200
                response == [
                    {
                        "assignedHub": "str",  # Optional. Assigned Azure IoT Hub.
                        "createdDateTimeUtc": "2020-02-20 00:00:00",  # Optional.
                          Registration create date time (in UTC).
                        "deviceId": "str",  # Optional. Device ID.
                        "errorCode": 0,  # Optional. Error code.
                        "errorMessage": "str",  # Optional. Error message.
                        "etag": "str",  # Optional. The entity tag associated with the
                          resource.
                        "lastUpdatedDateTimeUtc": "2020-02-20 00:00:00",  # Optional. Last
                          updated date time (in UTC).
                        "payload": {},  # Optional. Custom allocation payload returned from
                          the webhook to the device.
                        "registrationId": "str",  # Optional. This id is used to uniquely
                          identify a device registration of an enrollment."nA case-insensitive string
                          (up to 128 characters long) of alphanumeric characters plus certain special
                          characters : . _ -. No special characters allowed at start or end.
                        "status": "str",  # Optional. Enrollment status. Known values are:
                          "unassigned", "assigning", "assigned", "failed", and "disabled".
                        "substatus": "str"  # Optional. Substatus for 'Assigned' devices.
                          Possible values include - 'initialAssignment': Device has been assigned to an
                          IoT hub for the first time, 'deviceDataMigrated': Device has been assigned to
                          a different IoT hub and its device data was migrated from the previously
                          assigned IoT hub. Device data was removed from the previously assigned IoT
                          hub, 'deviceDataReset':  Device has been assigned to a different IoT hub and
                          its device data was populated from the initial state stored in the
                          enrollment. Device data was removed from the previously assigned IoT hub,
                          'reprovisionedToInitialAssignment': Device has been re-provisioned to a
                          previously assigned IoT hub. Known values are: "initialAssignment",
                          "deviceDataMigrated", "deviceDataReset", and
                          "reprovisionedToInitialAssignment".
                    }
                ]
        """
        error_map = {
            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 = kwargs.pop("params", {}) or {}

        def prepare_request(continuation_token=None):
            if not continuation_token:
                request = build_device_registration_state_query_request(
                    id=id,
                    x_ms_max_item_count=top,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                    **kwargs,
                )
            else:
                request = build_device_registration_state_query_request(
                    id=id,
                    x_ms_max_item_count=top,
                    x_ms_continuation=continuation_token,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                    **kwargs,
                )
            request.url = self._client.format_url(request.url)
            return request

        def get_next(continuation_token: Optional[str] = None):
            request = prepare_request(continuation_token)
            pipeline_response = self._client._pipeline.run(  # type: ignore # pylint: disable=protected-access
                request, stream=False, **kwargs
            )
            return pipeline_response

        def _extract_data(pipeline_response):
            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)
            return _extract_data_default(pipeline_response)

        return ItemPaged(get_next=get_next, extract_data=_extract_data)


__all__ = [
    "EnrollmentOperations",
    "EnrollmentGroupOperations",
    "DeviceRegistrationStateOperations",
]


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
    """