10000 IoT Image Example (#2268) · pardeep-tm/python-docs-samples@530c8bf · GitHub
[go: up one dir, main page]

Skip to content

Commit 530c8bf

Browse files
authored
IoT Image Example (GoogleCloudPlatform#2268)
* Adds image scaffold * Adds test and image receiver * Test image receive works
1 parent ef4e137 commit 530c8bf

File tree

5 files changed

+375
-22
lines changed

5 files changed

+375
-22
lines changed

iot/api-client/mqtt_example/README.rst

Lines changed: 91 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -76,48 +76,117 @@ To run this sample:
7676
7777
$ python cloudiot_mqtt_example.py
7878
79-
usage: cloudiot_mqtt_example.py [-h] [--project_id PROJECT_ID] --registry_id
80-
REGISTRY_ID --device_id DEVICE_ID
81-
--private_key_file PRIVATE_KEY_FILE
82-
--algorithm {RS256,ES256}
83-
[--cloud_region CLOUD_REGION]
79+
usage: cloudiot_mqtt_example.py [-h] --algorithm {RS256,ES256}
8480
[--ca_certs CA_CERTS]
85-
[--num_messages NUM_MESSAGES]
81+
[--cloud_region CLOUD_REGION] [--data DATA]
82+
--device_id DEVICE_ID
83+
[--gateway_id GATEWAY_ID]
84+
[--jwt_expires_minutes JWT_EXPIRES_MINUTES]
85+
[--listen_dur LISTEN_DUR]
8686
[--message_type {event,state}]
8787
[--mqtt_bridge_hostname MQTT_BRIDGE_HOSTNAME]
8888
[--mqtt_bridge_port {8883,443}]
89-
[--jwt_expires_minutes JWT_EXPIRES_MINUTES]
90-
89+
[--num_messages NUM_MESSAGES]
90+
--private_key_file PRIVATE_KEY_FILE
91+
[--project_id PROJECT_ID] --registry_id
92+
REGISTRY_ID
93+
[--service_account_json SERVICE_ACCOUNT_JSON]
94+
{device_demo,gateway_send,gateway_listen} ...
95+
9196
Example Google Cloud IoT Core MQTT device connection code.
92-
97+
98+
positional arguments:
99+
{device_demo,gateway_send,gateway_listen}
100+
device_demo Connects a device, sends data, and receives data.
101+
gateway_send Sends data from a gateway on behalf of a device that
102+
is bound to it.
103+
gateway_listen Listens for messages sent to the gateway and bound
104+
devices.
105+
93106
optional arguments:
94107
-h, --help show this help message and exit
95-
--project_id PROJECT_ID
96-
GCP cloud project name
97-
--registry_id REGISTRY_ID
98-
Cloud IoT Core registry id
99-
--device_id DEVICE_ID
100-
Cloud IoT Core device id
101-
--private_key_file PRIVATE_KEY_FILE
102-
Path to private key file.
103108
--algorithm {RS256,ES256}
104109
Which encryption algorithm to use to generate the JWT.
110+
--ca_certs CA_CERTS CA root from https://pki.google.com/roots.pem
105111
--cloud_region CLOUD_REGION
106112
GCP cloud region
107-
--ca_certs CA_CERTS CA root from https://pki.google.com/roots.pem
108-
--num_messages NUM_MESSAGES
109-
Number of messages to publish.
113+
--data DATA The telemetry data sent on behalf of a device
114+
--device_id DEVICE_ID
115+
Cloud IoT Core device id
116+
--gateway_id GATEWAY_ID
117+
Gateway identifier.
118+
--jwt_expires_minutes JWT_EXPIRES_MINUTES
119+
Expiration time, in minutes, for JWT tokens.
120+
--listen_dur LISTEN_DUR
121+
Duration (seconds) to listen for configuration
122+
messages
110123
--message_type {event,state}
111124
Indicates whether the message to be published is a
112125
telemetry event or a device state message.
113126
--mqtt_bridge_hostname MQTT_BRIDGE_HOSTNAME
114127
MQTT bridge hostname.
115128
--mqtt_bridge_port {8883,443}
116129
MQTT bridge port.
117-
--jwt_expires_minutes JWT_EXPIRES_MINUTES
118-
Expiration time, in minutes, for JWT tokens.
130+
--num_messages NUM_MESSAGES
131+
Number of messages to publish.
132+
--private_key_file PRIVATE_KEY_FILE
133+
Path to private key file.
134+
--project_id PROJECT_ID
135+
GCP cloud project name
136+
--registry_id REGISTRY_ID
137+
Cloud IoT Core registry id
138+
--service_account_json SERVICE_ACCOUNT_JSON
139+
Path to service account json file.
119140
120141
142+
MQTT Image Example
143+
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
144+
145+
.. image:: https://gstatic.com/cloudssh/images/open-btn.png
146+
:target: https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/GoogleCloudPlatform/python-docs-samples&page=editor&open_in_edi 57AE tor=iot/api-client/mqtt_example/cloudiot_mqtt_image.py,iot/api-client/mqtt_example/README.rst
147+
148+
149+
150+
151+
To run this sample:
152+
153+
.. code-block:: bash
154+
155+
$ python cloudiot_mqtt_image.py
156+
157+
usage: cloudiot_mqtt_image.py [-h] [--ca_certs CA_CERTS]
158+
[--cloud_region CLOUD_REGION]
159+
[--image_path IMAGE_PATH] --device_id DEVICE_ID
160+
--private_key_file PRIVATE_KEY_FILE
161+
[--project_id PROJECT_ID] --registry_id
162+
REGISTRY_ID
163+
[--service_account_json SERVICE_ACCOUNT_JSON]
164+
{send} ...
165+
166+
Google Cloud IoT Core MQTT binary transmission demo.
167+
168+
positional arguments:
169+
{send}
170+
send Send an inage to a device registry
171+
172+
optional arguments:
173+
-h, --help show this help message and exit
174+
--ca_certs CA_CERTS CA root from https://pki.google.com/roots.pem
175+
--cloud_region CLOUD_REGION
176+
GCP cloud region
177+
--image_path IMAGE_PATH
178+
The telemetry data sent on behalf of a device
179+
--device_id DEVICE_ID
180+
Cloud IoT Core device id
181+
--private_key_file PRIVATE_KEY_FILE
182+
Path to private key file.
183+
--project_id PROJECT_ID
184+
GCP cloud project name
185+
--registry_id REGISTRY_ID
186+
Cloud IoT Core registry id
187+
--service_account_json SERVICE_ACCOUNT_JSON
188+
Path to service account json file.
189+
121190
122191
123192

iot/api-client/mqtt_example/README.rst.in

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,9 @@ samples:
3131
- name: MQTT Device Client Example
3232
file: cloudiot_mqtt_example.py
3333
show_help: True
34+
- name: MQTT Image Example
35+
file: cloudiot_mqtt_image.py
36+
show_help: True
3437

3538
cloud_client_library: false
3639

Lines changed: 149 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,149 @@
1+
# Copyright 2019 Google Inc. All Rights Reserved.
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
5+
# you may not use this file except in compliance with the License.
6+
# You may obtain a copy of the License at
7+
#
8+
# http://www.apache.org/licenses/LICENSE-2.0
9+
#
10+
# Unless required by applicable law or agreed to in writing, software
11+
# distributed under the License is distributed on an "AS IS" BASIS,
12+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
# See the License for the specific language governing permissions and
14+
# limitations under the License.
15+
import argparse
16+
import base64
17+
import io
18+
import os
19+
import sys
20+
import time
21+
22+
from google.cloud import pubsub
23+
24+
# Add manager as library
25+
sys.path.append(os.path.join(os.path.dirname(__file__), '..', 'manager')) # noqa
26+
import cloudiot_mqtt_example
27+
28+
29+
# [START iot_mqtt_image]
30+
def transmit_image(
31+
cloud_region, registry_id, device_id, rsa_private_path, ca_cert_path,
32+
image_path, project_id, service_account_json):
33+
"""Send an inage to a device registry"""
34+
35+
with io.open(image_path, 'rb') as image_file:
36+
image_data = base64.b64encode(image_file.read()).decode('utf-8')
37+
38+
sub_topic = 'events'
39+
mqtt_topic = '/devices/{}/{}'.format(device_id, sub_topic)
40+
41+
client = cloudiot_mqtt_example.get_client(
42+
project_id, cloud_region, registry_id, device_id,
43+
rsa_private_path, 'RS256', ca_cert_path,
44+
'mqtt.googleapis.com', 8883)
45+
46+
client.loop_start()
47+
client.publish(mqtt_topic, image_data, qos=1)
48+
time.sleep(2)
49+
client.loop_stop()
50+
# [END iot_mqtt_image]
51+
52+
53+
def receive_image(project_id, sub_name, prefix, extension, duration):
54+
"""Receieve images transmitted to a PubSub subscription."""
55+
subscriber = pubsub.SubscriberClient()
56+
subscription_path = subscriber.subscription_path(project_id, sub_name)
57+
58+
global count
59+
count = 0
60+
file_pattern = '{}-{}.{}'
61+
62+
def callback(message):
63+
global count
64+
count = count + 1
65+
print('Received image {}:'.format(count))
66+
image_data = base64.b64decode(message.data)
67+
68+
with io.open(file_pattern.format(prefix, count, extension), 'wb') as f:
69+
f.write(image_data)
70+
71+
message.ack()
72+
73+
subscriber.subscribe(subscription_path, callback=callback)
74+
75+
sleep_count = 0
76+
print('Listening for messages on {}'.format(subscription_path))
77+
while sleep_count < duration:
78+
time.sleep(1)
79+
sleep_count = sleep_count + 1
80+
81+
82+
def parse_command_line_args():
83+
"""Parse command line arguments."""
84+
parser = argparse.ArgumentParser(description=(
85+
'Google Cloud IoT Core MQTT binary transmission demo.'))
86+
parser.add_argument(
87+
'--ca_certs',
88+
default='roots.pem',
89+
help=('CA root from https://pki.google.com/roots.pem'))
90+
parser.add_argument(
91+
'--cloud_region', default='us-central1', help='GCP cloud region')
92+
parser.add_argument(
93+
'--image_path',
94+
default='./',
95+
help='The telemetry data sent on behalf of a device')
96+
parser.add_argument(
97+
'--device_id', required=True, help='Cloud IoT Core device id')
98+
parser.add_argument(
99+
'--private_key_file',
100+
required=True,
101+
help='Path to private key file.')
102+
parser.add_argument(
103+
'--project_id',
104+
default=os.environ.get('GOOGLE_CLOUD_PROJECT'),
105+
help='GCP cloud project name')
106+
parser.add_argument(
107+
'--registry_id', required=True, help='Cloud IoT Core registry id')
108+
parser.add_argument(
109+
'--service_account_json',
110+
default=os.environ.get("GOOGLE_APPLICATION_CREDENTIALS"),
111+
help='Path to service account json file.')
112+
parser.add_argument(
113+
'--subscription_name',
114+
help='PubSub subscription for receieving images.')
115+
parser.add_argument(
116+
'--image_prefix',
117+
help='Image prefix used when receieving images.')
118+
parser.add_argument(
119+
'--image_extension',
120+
help='Image extension used when receiving images.')
121+
122+
command = parser.add_subparsers(dest='command')
123+
command.add_parser(
124+
'send',
125+
help=transmit_image.__doc__)
126+
command.add_parser(
127+
'recv',
128+
help=receive_image.__doc__)
129+
return parser.parse_args()
130+
131+
132+
def main():
133+
args = parse_command_line_args()
134+
135+
if args.command == 'send':
136+
transmit_image(
137+
args.cloud_region, args.registry_id, args.device_id,
138+
args.private_key_file, args.ca_certs, args.image_path,
139+
args.project_id, args.service_account_json)
140+
elif args.command == 'recv':
141+
receive_image(
142+
args.project_id, args.subscription_name, args.image_prefix,
143+
args.image_extension, 60)
144+
else:
145+
print(args.print_help())
146+
147+
148+
if __name__ == '__main__':
149+
main()

0 commit comments

Comments
 (0)
0