@@ -69,6 +69,37 @@ def create_jwt(project_id, private_key_file, algorithm):
69
69
return jwt .encode (token , private_key , algorithm = algorithm )
70
70
71
71
72
+ def publish_message (
73
+ message , message_type , base_url , project_id , cloud_region , registry_id ,
74
+ device_id , jwt_token ):
75
+ headers = {
76
+ 'authorization' : 'Bearer {}' .format (jwt_token ),
77
+ 'content-type' : 'application/json' ,
78
+ 'cache-control' : 'no-cache'
79
+ }
80
+
81
+ # Publish to the events or state topic based on the flag.
82
+ url_suffix = 'publishEvent' if message_type == 'event' else 'setState'
83
+
84
+ publish_url = (
85
+ '{}/projects/{}/locations/{}/registries/{}/devices/{}:{}' ).format (
86
+ base_url , project_id , cloud_region , registry_id , device_id ,
87
+ url_suffix )
88
+
89
+ body = None
90
+ if message_type == 'event' :
91
+ body = {'binary_data' : base64 .urlsafe_b64encode (message )}
92
+ else :
93
+ body = {
94
+ 'state' : {'binary_data' : base64 .urlsafe_b64encode (message )}
95
+ }
96
+
97
+ resp = requests .post (
98
+ publish_url , data = json .dumps (body ), headers = headers )
99
+
100
+ return resp
101
+
102
+
72
103
def parse_command_line_args ():
73
104
"""Parse command line arguments."""
74
105
parser = argparse .ArgumentParser (description = (
@@ -117,38 +148,20 @@ def parse_command_line_args():
117
148
def main ():
118
149
args = parse_command_line_args ()
119
150
120
- # Publish to the events or state topic based on the flag.
121
- url_suffix = 'publishEvent' if args .message_type == 'event' else 'setState'
122
-
123
- publish_url = (
124
- '{}/projects/{}/locations/{}/registries/{}/devices/{}:{}' ).format (
125
- args .base_url , args .project_id , args .cloud_region ,
126
- args .registry_id , args .device_id , url_suffix )
127
-
128
151
jwt_token = create_jwt (
129
152
args .project_id , args .private_key_file , args .algorithm )
130
153
131
- headers = {
132
- 'Authorization' : 'Bearer {}' .format (jwt_token ),
133
- 'Content-Type' : 'application/json'
134
- }
135
-
136
154
# Publish num_messages mesages to the HTTP bridge once per second.
137
155
for i in range (1 , args .num_messages + 1 ):
138
156
payload = '{}/{}-payload-{}' .format (
139
157
args .registry_id , args .device_id , i )
158
+
140
159
print ('Publishing message {}/{}: \' {}\' ' .format (
141
160
i , args .num_messages , payload ))
142
- body = None
143
- if args .message_type == 'event' :
144
- body = {'binary_data' : base64 .urlsafe_b64encode (payload )}
145
- else :
146
- body = {
147
- 'state' : {'binary_data' : base64 .urlsafe_b64encode (payload )}
148
- }
149
-
150
- resp = requests .post (
151
- publish_url , data = json .dumps (body ), headers = headers )
161
+
162
+ resp = publish_message (
163
+ payload , args .message_type , args .base_url , args .project_id ,
164
+ args .cloud_region , args .registry_id , args .device_id , jwt_token )
152
165
153
166
print ('HTTP response: ' , resp )
154
167
0 commit comments