Skip to content

Commit 9dd2367

Browse files
authored
Acknowledge messages before parsing to avoid infinite loop / re… (GoogleCloudPlatform#2384)
* Acknowledge messages before parsing to avoid infinite loop / retry on non-base64-encoded messages
1 parent b57328f commit 9dd2367

File tree

1 file changed

+17
-7
lines changed

1 file changed

+17
-7
lines changed

iot/api-client/mqtt_example/cloudiot_mqtt_image.py

Lines changed: 17 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
# limitations under the License.
1515
import argparse
1616
import base64
17+
import binascii
1718
import io
1819
import os
1920
import sys
@@ -61,14 +62,18 @@ def receive_image(project_id, sub_name, prefix, extension, duration):
6162

6263
def callback(message):
6364
global count
64-
count = count + 1
65-
print('Received image {}:'.format(count))
66-
image_data = base64.b64decode(message.data)
65+
try:
66+
count = count + 1
67+
print('Received image {}:'.format(count))
68+
image_data = base64.b64decode(message.data)
6769

68-
with io.open(file_pattern.format(prefix, count, extension), 'wb') as f:
69-
f.write(image_data)
70+
with io.open(
71+
file_pattern.format(prefix, count, extension), 'wb') as f:
72+
f.write(image_data)
73+
message.ack()
7074

71-
message.ack()
75+
except binascii.Error:
76+
message.ack() # To move forward if a message can't be processed
7277

7378
subscriber.subscribe(subscription_path, callback=callback)
7479

@@ -118,6 +123,11 @@ def parse_command_line_args():
118123
parser.add_argument(
119124
'--image_extension',
120125
help='Image extension used when receiving images.')
126+
parser.add_argument(
127+
'--duration',
128+
default=60,
129+
type=int,
130+
help='Number of seconds to receieve images for.')
121131

122132
command = parser.add_subparsers(dest='command')
123133
command.add_parser(
@@ -140,7 +150,7 @@ def main():
140150
elif args.command == 'recv':
141151
receive_image(
142152
args.project_id, args.subscription_name, args.image_prefix,
143-
args.image_extension, 60)
153+
args.image_extension, args.duration)
144154
else:
145155
print(args.print_help())
146156

0 commit comments

Comments
 (0)