-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathiot_core.py
98 lines (74 loc) · 3.11 KB
/
iot_core.py
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
import logging
from typing import List
from google.cloud import iot_v1
from google.protobuf import field_mask_pb2 as gp_field_mask
from google.cloud.iot_v1.types.resources import Device
class IotCore:
def __init__(self, project_id: str, cloud_region: str):
self.project_id = project_id
self.cloud_region = cloud_region
def list_registries(self) -> List[object]:
"""List all registries in the project."""
client = iot_v1.DeviceManagerClient()
parent = f"projects/{self.project_id}/locations/{self.cloud_region}"
registries = list(client.list_device_registries(
request={"parent": parent}))
return registries
def list_devices(self, registry_id: str) -> List[Device]:
"""List all devices in the registry."""
client = iot_v1.DeviceManagerClient()
registry_path = client.registry_path(self.project_id, self.cloud_region, registry_id)
field_mask = gp_field_mask.FieldMask(
paths=[
"id",
"name",
"credentials",
"blocked",
"config",
"gateway_config",
]
)
devices = list(
client.list_devices(request={"parent": registry_path, "field_mask": field_mask})
)
return devices
def list_gateways(self, registry_id: str) -> List[Device]:
client = iot_v1.DeviceManagerClient()
path = client.registry_path(self.project_id, self.cloud_region, registry_id)
mask = gp_field_mask.FieldMask(
paths=[
"id",
"name",
"credentials",
"blocked",
"config",
"gateway_config",
]
)
devices = list(client.list_devices(request={"parent": path, "field_mask": mask}))
gateways = []
for device in devices:
if device.gateway_config is not None:
if device.gateway_config.gateway_type == 1:
gateways.append(device)
return gateways
def list_gateway_devices(self, registry_id: str, gateway_id: str):
client = iot_v1.DeviceManagerClient()
path = client.registry_path(self.project_id, self.cloud_region, registry_id)
mask = gp_field_mask.FieldMask(
paths=[
"id",
"name",
"credentials",
"blocked",
"config",
"gateway_config",
]
)
devices = list(
client.list_devices(
request={"parent": path, "field_mask": mask, "gateway_list_options": {"associations_gateway_id": gateway_id,}})
)
if not devices:
logging.warning("No devices bound to gateway {}".format(gateway_id))
return devices