Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Commit 223abde

Browse filesBrowse files
authored
Cloud client library migration for registry management features (GoogleCloudPlatform#2453)
* Cloud client library migration for registry management features
1 parent 9055e71 commit 223abde
Copy full SHA for 223abde

File tree

Expand file treeCollapse file tree

2 files changed

+89
-121
lines changed
Filter options
Expand file treeCollapse file tree

2 files changed

+89
-121
lines changed

‎iot/api-client/manager/manager.py

Copy file name to clipboardExpand all lines: iot/api-client/manager/manager.py
+85-118Lines changed: 85 additions & 118 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@
3535
import sys
3636
import time
3737

38+
from google.api_core.exceptions import AlreadyExists
3839
from google.cloud import iot_v1
3940
from google.cloud import pubsub
4041
from google.oauth2 import service_account
@@ -143,37 +144,29 @@ def create_device(
143144
"""Create a device to bind to a gateway if it does not exist."""
144145
# [START iot_create_device]
145146
# Check that the device doesn't already exist
147+
client = iot_v1.DeviceManagerClient()
148+
146149
exists = False
147150

148-
client = get_client(service_account_json)
149-
registry_path = 'projects/{}/locations/{}/registries/{}'.format(
150-
project_id, cloud_region, registry_id)
151+
parent = client.registry_path(project_id, cloud_region, registry_id)
151152

152-
devices = client.projects().locations().registries().devices(
153-
).list(
154-
parent=registry_path, fieldMask='config,gatewayConfig'
155-
).execute().get('devices', [])
153+
devices = list(client.list_devices(parent=parent))
156154

157155
for device in devices:
158-
if device.get('id') == device_id:
156+
if device.id == device_id:
159157
exists = True
160158

161159
# Create the device
162-
registry_name = 'projects/{}/locations/{}/registries/{}'.format(
163-
project_id, cloud_region, registry_id)
164-
165160
device_template = {
166161
'id': device_id,
167-
'gatewayConfig': {
168-
'gatewayType': 'NON_GATEWAY',
169-
'gatewayAuthMethod': 'ASSOCIATION_ONLY'
162+
'gateway_config': {
163+
'gateway_type': 'NON_GATEWAY',
164+
'gateway_auth_method': 'ASSOCIATION_ONLY'
170165
}
171166
}
172-
devices = client.projects().locations().registries().devices()
173167

174168
if not exists:
175-
res = devices.create(
176-
parent=registry_name, body=device_template).execute()
169+
res = client.create_device(parent, device_template)
177170
print('Created Device {}'.format(res))
178171
else:
179172
print('Device exists, skipping')
@@ -217,12 +210,17 @@ def delete_registry(
217210
"""Deletes the specified registry."""
218211
# [START iot_delete_registry]
219212
print('Delete registry')
220-
client = get_client(service_account_json)
221-
registry_name = 'projects/{}/locations/{}/registries/{}'.format(
222-
project_id, cloud_region, registry_id)
223213

224-
registries = client.projects().locations().registries()
225-
return registries.delete(name=registry_name).execute()
214+
client = iot_v1.DeviceManagerClient()
215+
registry_path = client.registry_path(project_id, cloud_region, registry_id)
216+
217+
try:
218+
response = client.delete_device_registry(registry_path)
219+
print('Deleted registry')
220+
return response
221+
except HttpError:
222+
print('Error, registry not deleted')
223+
return ""
226224
# [END iot_delete_registry]
227225

228226

@@ -330,40 +328,40 @@ def create_registry(
330328
""" Creates a registry and returns the result. Returns an empty result if
331329
the registry already exists."""
332330
# [START iot_create_registry]
333-
client = get_client(service_account_json)
334-
registry_parent = 'projects/{}/locations/{}'.format(
335-
project_id,
336-
cloud_region)
331+
client = iot_v1.DeviceManagerClient()
332+
parent = client.location_path(project_id, cloud_region)
333+
334+
if not pubsub_topic.startswith('projects/'):
335+
pubsub_topic = 'projects/{}/topics/{}'.format(project_id, pubsub_topic)
336+
337337
body = {
338-
'eventNotificationConfigs': [{
339-
'pubsubTopicName': pubsub_topic
338+
'event_notification_configs': [{
339+
'pubsub_topic_name': pubsub_topic
340340
}],
341341
'id': registry_id
342342
}
343-
request = client.projects().locations().registries().create(
344-
parent=registry_parent, body=body)
345343

346344
try:
347-
response = request.execute()
345+
response = client.create_device_registry(parent, body)
348346
print('Created registry')
349347
return response
350348
except HttpError:
351349
print('Error, registry not created')
352350
return ""
351+
except AlreadyExists:
352+
print('Error, registry already exists')
353+
return ""
353354
# [END iot_create_registry]
354355

355356

356357
def get_registry(
357358
service_account_json, project_id, cloud_region, registry_id):
358359
""" Retrieves a device registry."""
359360
# [START iot_get_registry]
360-
client = get_client(service_account_json)
361-
registry_parent = 'projects/{}/locations/{}'.format(
362-
project_id,
363-
cloud_region)
364-
topic_name = '{}/registries/{}'.format(registry_parent, registry_id)
365-
request = client.projects().locations().registries().get(name=topic_name)
366-
return request.execute()
361+
client = iot_v1.DeviceManagerClient()
362+
registry_path = client.registry_path(project_id, cloud_region, registry_id)
363+
364+
return client.get_device_registry(registry_path)
367365
# [END iot_get_registry]
368366

369367

@@ -377,7 +375,7 @@ def open_registry(
377375
service_account_json, project_id, cloud_region,
378376
pubsub_topic, registry_id)
379377

380-
if response == "":
378+
if response == '':
381379
# Device registry already exists
382380
print(
383381
'Registry {} already exists - looking it up instead.'.format(
@@ -386,7 +384,7 @@ def open_registry(
386384
service_account_json, project_id, cloud_region,
387385
registry_id)
388386

389-
print('Registry {} opened: '.format(response.get('name')))
387+
print('Registry {} opened: '.format(response.name))
390388
print(response)
391389

392390

@@ -512,12 +510,11 @@ def get_iam_permissions(
512510
service_account_json, project_id, cloud_region, registry_id):
513511
"""Retrieves IAM permissions for the given registry."""
514512
# [START iot_get_iam_policy]
515-
client = get_client(service_account_json)
516-
registry_path = 'projects/{}/locations/{}/registries/{}'.format(
517-
project_id, cloud_region, registry_id)
513+
client = iot_v1.DeviceManagerClient()
514+
515+
registry_path = client.registry_path(project_id, cloud_region, registry_id)
518516

519-
policy = client.projects().locations().registries().getIamPolicy(
520-
resource=registry_path, body={}).execute()
517+
policy = client.get_iam_policy(registry_path)
521518

522519
return policy
523520
# [END iot_get_iam_policy]
@@ -528,23 +525,18 @@ def set_iam_permissions(
528525
member):
529526
"""Sets IAM permissions for the given registry to a single role/member."""
530527
# [START iot_set_iam_policy]
531-
client = get_client(service_account_json)
528+
client = iot_v1.DeviceManagerClient()
529+
registry_path = client.registry_path(project_id, cloud_region, registry_id)
532530

533-
registry_path = 'projects/{}/locations/{}/registries/{}'.format(
534-
project_id, cloud_region, registry_id)
535531
body = {
536-
"policy":
537-
{
538-
"bindings":
539-
[{
540-
"members": [member],
541-
"role": role
542-
}]
543-
}
532+
'bindings':
533+
[{
534+
'members': [member],
535+
'role': role
536+
}]
544537
}
545538

546-
return client.projects().locations().registries().setIamPolicy(
547-
resource=registry_path, body=body).execute()
539+
return client.set_iam_policy(registry_path, body)
548540
# [END iot_set_iam_policy]
549541

550542

@@ -577,17 +569,13 @@ def create_gateway(
577569
# [START iot_create_gateway]
578570
# Check that the gateway doesn't already exist
579571
exists = False
580-
client = get_client(service_account_json)
581-
registry_path = 'projects/{}/locations/{}/registries/{}'.format(
582-
project_id, cloud_region, registry_id)
572+
client = iot_v1.DeviceManagerClient()
583573

584-
devices = client.projects().locations().registries().devices(
585-
).list(
586-
parent=registry_path, fieldMask='config,gatewayConfig'
587-
).execute().get('devices', [])
574+
parent = client.registry_path(project_id, cloud_region, registry_id)
575+
devices = list(client.list_devices(parent=parent))
588576

589577
for device in devices:
590-
if device.get('id') == gateway_id:
578+
if device.id == gateway_id:
591579
exists = True
592580
print('Device: {} : {} : {} : {}'.format(
593581
device.get('id'),
@@ -596,10 +584,6 @@ def create_gateway(
596584
device.get('gatewayConfig')
597585
))
598586

599-
# Create the gateway
600-
registry_name = 'projects/{}/locations/{}/registries/{}'.format(
601-
project_id, cloud_region, registry_id)
602-
603587
with io.open(certificate_file) as f:
604588
certificate = f.read()
605589

@@ -617,17 +601,15 @@ def create_gateway(
617601
'key': certificate
618602
}
619603
}],
620-
'gatewayConfig': {
621-
'gatewayType': 'GATEWAY',
622-
'gatewayAuthMethod': 'ASSOCIATION_ONLY'
604+
'gateway_config': {
605+
'gateway_type': 'GATEWAY',
606+
'gateway_auth_method': 'ASSOCIATION_ONLY'
623607
}
624608
}
625-
devices = client.projects().locations().registries().devices()
626609

627610
if not exists:
628-
res = devices.create(
629-
parent=registry_name, body=device_template).execute()
630-
print('Created gateway {}'.format(res))
611+
res = client.create_device(parent, device_template)
612+
print('Created Gateway {}'.format(res))
631613
else:
632614
print('Gateway exists, skipping')
633615
# [END iot_create_gateway]
@@ -638,21 +620,17 @@ def bind_device_to_gateway(
638620
gateway_id):
639621
"""Binds a device to a gateway."""
640622
# [START iot_bind_device_to_gateway]
641-
client = get_client(service_account_json)
623+
client = iot_v1.DeviceManagerClient()
642624

643625
create_device(
644626
service_account_json, project_id, cloud_region, registry_id,
645627
device_id)
646628

647-
registry_name = 'projects/{}/locations/{}/registries/{}'.format(
648-
project_id, cloud_region, registry_id)
649-
bind_request = {
650-
'deviceId': device_id,
651-
'gatewayId': gateway_id
652-
}
653-
client.projects().locations().registries().bindDeviceToGateway(
654-
parent=registry_name, body=bind_request).execute()
655-
print('Device Bound!')
629+
parent = client.registry_path(project_id, cloud_region, registry_id)
630+
631+
res = client.bind_device_to_gateway(parent, gateway_id, device_id)
632+
633+
print('Device Bound! {}'.format(res))
656634
# [END iot_bind_device_to_gateway]
657635

658636

@@ -661,17 +639,12 @@ def unbind_device_from_gateway(
661639
gateway_id):
662640
"""Unbinds a device to a gateway."""
663641
# [START iot_unbind_device_from_gateway]
664-
client = get_client(service_account_json)
642+
client = iot_v1.DeviceManagerClient()
665643

666-
registry_name = 'projects/{}/locations/{}/registries/{}'.format(
667-
project_id, cloud_region, registry_id)
668-
bind_request = {
669-
'deviceId': device_id,
670-
'gatewayId': gateway_id
671-
}
644+
parent = client.registry_path(project_id, cloud_region, registry_id)
645+
646+
res = client.unbind_device_from_gateway(parent, gateway_id, device_id)
672647

673-
res = client.projects().locations().registries().unbindDeviceFromGateway(
674-
parent=registry_name, body=bind_request).execute()
675648
print('Device unbound: {}'.format(res))
676649
# [END iot_unbind_device_from_gateway]
677650

@@ -680,19 +653,18 @@ def list_gateways(
680653
service_account_json, project_id, cloud_region, registry_id):
681654
"""Lists gateways in a registry"""
682655
# [START iot_list_gateways]
683-
client = get_client(service_account_json)
684-
registry_path = 'projects/{}/locations/{}/registries/{}'.format(
685-
project_id, cloud_region, registry_id)
656+
client = iot_v1.DeviceManagerClient()
686657

687-
devices = client.projects().locations().registries().devices(
688-
).list(
689-
parent=registry_path, fieldMask='config,gatewayConfig'
690-
).execute().get('devices', [])
658+
path = client.registry_path(project_id, cloud_region, registry_id)
659+
mask = iot_v1.types.FieldMask()
660+
mask.paths.append('config')
661+
mask.paths.append('gateway_config')
662+
devices = list(client.list_devices(parent=path, field_mask=mask))
691663

692664
for device in devices:
693-
if device.get('gatewayConfig') is not None:
694-
if device.get('gatewayConfig').get('gatewayType') == 'GATEWAY':
695-
print('Gateway ID: {}\n\t{}'.format(device.get('id'), device))
665+
if device.gateway_config is not None:
666+
if device.gateway_config.gateway_type == 1:
667+
print('Gateway ID: {}\n\t{}'.format(device.id, device))
696668
# [END iot_list_gateways]
697669

698670

@@ -701,23 +673,18 @@ def list_devices_for_gateway(
701673
gateway_id):
702674
"""List devices bound to a gateway"""
703675
# [START iot_list_devices_for_gateway]
704-
client = get_client(service_account_json)
676+
client = iot_v1.DeviceManagerClient()
705677

706-
registry_name = 'projects/{}/locations/{}/registries/{}'.format(
707-
project_id, cloud_region, registry_id)
678+
path = client.registry_path(project_id, cloud_region, registry_id)
708679

709-
devices = client.projects().locations().registries().devices(
710-
).list(
711-
parent=registry_name,
712-
gatewayListOptions_associationsGatewayId=gateway_id
713-
).execute()
680+
devices = list(client.list_devices(
681+
parent=path,
682+
gateway_list_options={'associations_gateway_id': gateway_id}))
714683

715684
found = False
716-
for device in devices.get('devices', []):
685+
for device in devices:
717686
found = True
718-
print('Device: {} : {}'.format(
719-
device.get('numId'),
720-
device.get('id')))
687+
print('Device: {} : {}'.format(device.num_id, device.id))
721688

722689
if not found:
723690
print('No devices bound to gateway {}'.format(gateway_id))

‎iot/api-client/manager/manager_test.py

Copy file name to clipboardExpand all lines: iot/api-client/manager/manager_test.py
+4-3Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -137,7 +137,7 @@ def test_create_delete_registry(test_topic, capsys):
137137

138138
# Check that create / list worked
139139
assert 'Created registry' in out
140-
assert 'eventNotificationConfig' in out
140+
assert 'event_notification_config' in out
141141

142142
# Clean up
143143
manager.delete_registry(
@@ -167,7 +167,8 @@ def test_get_iam_permissions(test_topic, capsys):
167167

168168
# Check that create / list worked
169169
assert 'Created registry' in out
170-
assert 'eventNotificationConfig' in out
170+
assert 'event_notification_config' in out
171+
assert 'dpebot' in out
171172
assert 'etag' in out
172173

173174
# Clean up
@@ -430,7 +431,7 @@ def test_create_gateway(test_topic, capsys):
430431

431432
out, _ = capsys.readouterr()
432433

433-
assert 'Created gateway' in out
434+
assert 'Created Gateway' in out
434435

435436

436437
def test_list_gateways(test_topic, capsys):

0 commit comments

Comments
0 (0)
Morty Proxy This is a proxified and sanitized view of the page, visit original site.