forked from smooth80/python-docs-samples
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathgateway_demo.py
208 lines (179 loc) · 6.18 KB
/
gateway_demo.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
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
# Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# [START iot_gateway_demo]
import csv
import datetime
import logging
import os
import sys
import time
sys.path.append(os.path.join(os.path.dirname(__file__), "..", "manager")) # noqa
import cloudiot_mqtt_example # noqa
import manager # noqa
logging.getLogger("googleapiclient.discovery_cache").setLevel(logging.CRITICAL)
cloud_region = "us-central1"
device_id_template = "test-device-{}"
gateway_id_template = "test-gateway-{}"
topic_id = "test-device-events-topic-{}".format(int(time.time()))
ca_cert_path = "resources/roots.pem"
log_path = "config_log.csv"
rsa_cert_path = "resources/rsa_cert.pem"
rsa_private_path = "resources/rsa_private.pem"
if (
"GOOGLE_CLOUD_PROJECT" not in os.environ
or "GOOGLE_APPLICATION_CREDENTIALS" not in os.environ
):
print("You must set GCLOUD_PROJECT and GOOGLE_APPLICATION_CREDENTIALS")
quit()
project_id = os.environ["GOOGLE_CLOUD_PROJECT"]
service_account_json = os.environ["GOOGLE_APPLICATION_CREDENTIALS"]
pubsub_topic = "projects/{}/topics/{}".format(project_id, topic_id)
registry_id = "test-registry-{}".format(int(time.time()))
base_url = "https://console.cloud.google.com/iot/locations/{}".format(cloud_region)
edit_template = "{}/registries/{}?project={}".format(base_url, "{}", "{}")
device_url_template = "{}/registries/{}/devices/{}?project={}".format(
base_url, "{}", "{}", "{}"
)
mqtt_bridge_hostname = "mqtt.googleapis.com"
mqtt_bridge_port = 8883
num_messages = 15
jwt_exp_time = 20
listen_time = 30
if __name__ == "__main__":
print("Running demo")
gateway_id = device_id_template.format("RS256")
device_id = device_id_template.format("noauthbind")
# [START iot_gateway_demo_create_registry]
print("Creating registry: {}".format(registry_id))
manager.create_registry(
service_account_json, project_id, cloud_region, pubsub_topic, registry_id
)
# [END iot_gateway_demo_create_registry]
# [START iot_gateway_demo_create_gateway]
print("Creating gateway: {}".format(gateway_id))
manager.create_gateway(
service_account_json,
project_id,
cloud_region,
registry_id,
None,
gateway_id,
rsa_cert_path,
"RS256",
)
# [END iot_gateway_demo_create_gateway]
# [START iot_gateway_demo_create_bound_device]
print("Creating device to bind: {}".format(device_id))
manager.create_device(
service_account_json, project_id, cloud_region, registry_id, device_id
)
# [END iot_gateway_demo_create_bound_device]
# [START iot_gateway_demo_bind_device]
print("Binding device")
manager.bind_device_to_gateway(
service_account_json,
project_id,
cloud_region,
registry_id,
device_id,
gateway_id,
)
# [END iot_gateway_demo_bind_device]
# [START iot_gateway_demo_listen]
print("Listening for messages for {} seconds".format(listen_time))
print("Try setting configuration in: ")
print("\t{}".format(edit_template.format(registry_id, project_id)))
try:
input("Press enter to continue")
except SyntaxError:
pass
def log_callback(client):
def log_on_message(unused_client, unused_userdata, message):
if not os.path.exists(log_path):
with open(log_path, "w") as csvfile:
logwriter = csv.writer(csvfile, dialect="excel")
logwriter.writerow(["time", "topic", "data"])
with open(log_path, "a") as csvfile:
logwriter = csv.writer(csvfile, dialect="excel")
logwriter.writerow(
[
datetime.datetime.now().isoformat(),
message.topic,
message.payload,
]
)
client.on_message = log_on_message
cloudiot_mqtt_example.listen_for_messages(
service_account_json,
project_id,
cloud_region,
registry_id,
device_id,
gateway_id,
num_messages,
rsa_private_path,
"RS256",
ca_cert_path,
mqtt_bridge_hostname,
mqtt_bridge_port,
jwt_exp_time,
listen_time,
log_callback,
)
# [END iot_gateway_demo_listen]
# [START iot_gateway_demo_publish]
print("Publishing messages demo")
print("Publishing: {} messages".format(num_messages))
cloudiot_mqtt_example.send_data_from_bound_device(
service_account_json,
project_id,
cloud_region,
registry_id,
device_id,
gateway_id,
num_messages,
rsa_private_path,
"RS256",
ca_cert_path,
mqtt_bridge_hostname,
mqtt_bridge_port,
jwt_exp_time,
"Hello from gateway_demo.py",
)
print("You can read the state messages for your device at this URL:")
print("\t{}".format(device_url_template).format(registry_id, device_id, project_id))
try:
input("Press enter to continue after reading the messages.")
except SyntaxError:
pass
# [END iot_gateway_demo_publish]
# [START iot_gateway_demo_cleanup]
# Clean up
manager.unbind_device_from_gateway(
service_account_json,
project_id,
cloud_region,
registry_id,
device_id,
gateway_id,
)
manager.delete_device(
service_account_json, project_id, cloud_region, registry_id, device_id
)
manager.delete_device(
service_account_json, project_id, cloud_region, registry_id, gateway_id
)
manager.delete_registry(service_account_json, project_id, cloud_region, registry_id)
# [END iot_gateway_demo_cleanup]
# [END iot_gateway_demo]