|
| 1 | +#!/usr/bin/env python |
| 2 | + |
| 3 | +# Copyright 2017 Google Inc. |
| 4 | +# |
| 5 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 6 | +# you may not use this file except in compliance with the License. |
| 7 | +# You may obtain a copy of the License at |
| 8 | +# |
| 9 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | +# |
| 11 | +# Unless required by applicable law or agreed to in writing, software |
| 12 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 13 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 14 | +# See the License for the specific language governing permissions and |
| 15 | +# limitations under the License. |
| 16 | +"""Python sample for connecting to Google Cloud IoT Core via HTTP, using JWT. |
| 17 | +This example connects to Google Cloud IoT Core via HTTP, using a JWT for device |
| 18 | +authentication. After connecting, by default the device publishes 100 messages |
| 19 | +to the server at a rate of one per second, and then exits. |
| 20 | +Before you run the sample, you must register your device as described in the |
| 21 | +README in the parent folder. |
| 22 | +""" |
| 23 | + |
| 24 | +import argparse |
| 25 | +import base64 |
| 26 | +import datetime |
| 27 | +import json |
| 28 | +import time |
| 29 | + |
| 30 | +import jwt |
| 31 | +import requests |
| 32 | + |
| 33 | + |
| 34 | +_BASE_URL = 'https://cloudiot-device.googleapis.com/v1beta1' |
| 35 | + |
| 36 | + |
| 37 | +def create_jwt(project_id, private_key_file, algorithm): |
| 38 | + """Creates a JWT (https://jwt.io) to authenticate this device. |
| 39 | + Args: |
| 40 | + project_id: The cloud project ID this device belongs to |
| 41 | + private_key_file: A path to a file containing either an RSA256 or |
| 42 | + ES256 private key. |
| 43 | + algorithm: The encryption algorithm to use. Either 'RS256' or |
| 44 | + 'ES256' |
| 45 | + Returns: |
| 46 | + A JWT generated from the given project_id and private key, which |
| 47 | + expires in 20 minutes. After 20 minutes, your client will be |
| 48 | + disconnected, and a new JWT will have to be generated. |
| 49 | + Raises: |
| 50 | + ValueError: If the private_key_file does not contain a known key. |
| 51 | + """ |
| 52 | + |
| 53 | + token = { |
| 54 | + # The time the token was issued. |
| 55 | + 'iat': datetime.datetime.utcnow(), |
| 56 | + # Token expiration time. |
| 57 | + 'exp': datetime.datetime.utcnow() + datetime.timedelta(minutes=60), |
| 58 | + # The audience field should always be set to the GCP project id. |
| 59 | + 'aud': project_id |
| 60 | + } |
| 61 | + |
| 62 | + # Read the private key file. |
| 63 | + with open(private_key_file, 'r') as f: |
| 64 | + private_key = f.read() |
| 65 | + |
| 66 | + print('Creating JWT using {} from private key file {}'.format( |
| 67 | + algorithm, private_key_file)) |
| 68 | + |
| 69 | + return jwt.encode(token, private_key, algorithm=algorithm) |
| 70 | + |
| 71 | + |
| 72 | +def parse_command_line_args(): |
| 73 | + """Parse command line arguments.""" |
| 74 | + parser = argparse.ArgumentParser(description=( |
| 75 | + 'Example Google Cloud IoT Core HTTP device connection code.')) |
| 76 | + parser.add_argument( |
| 77 | + '--project_id', required=True, help='GCP cloud project name') |
| 78 | + parser.add_argument( |
| 79 | + '--registry_id', required=True, help='Cloud IoT Core registry id') |
| 80 | + parser.add_argument( |
| 81 | + '--device_id', required=True, help='Cloud IoT Core device id') |
| 82 | + parser.add_argument( |
| 83 | + '--private_key_file', |
| 84 | + required=True, |
| 85 | + help='Path to private key file.') |
| 86 | + parser.add_argument( |
| 87 | + '--algorithm', |
| 88 | + choices=('RS256', 'ES256'), |
| 89 | + required=True, |
| 90 | + help='The encryption algorithm to use to generate the JWT.') |
| 91 | + parser.add_argument( |
| 92 | + '--cloud_region', default='us-central1', help='GCP cloud region') |
| 93 | + parser.add_argument( |
| 94 | + '--ca_certs', |
| 95 | + default='roots.pem', |
| 96 | + help=('CA root from https://pki.google.com/roots.pem')) |
| 97 | + parser.add_argument( |
| 98 | + '--num_messages', |
| 99 | + type=int, |
| 100 | + default=100, |
| 101 | + help='Number of messages to publish.') |
| 102 | + parser.add_argument( |
| 103 | + '--message_type', |
| 104 | + choices=('event', 'state'), |
| 105 | + default='event', |
| 106 | + required=True, |
| 107 | + help=('Indicates whether the message to be published is a ' |
| 108 | + 'telemetry event or a device state message.')) |
| 109 | + parser.add_argument( |
| 110 | + '--base_url', |
| 111 | + default=_BASE_URL, |
| 112 | + help=('Base URL for the Cloud IoT Core Device Service API')) |
| 113 | + |
| 114 | + return parser.parse_args() |
| 115 | + |
| 116 | + |
| 117 | +def main(): |
| 118 | + args = parse_command_line_args() |
| 119 | + |
| 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 | + jwt_token = create_jwt( |
| 129 | + args.project_id, args.private_key_file, args.algorithm) |
| 130 | + |
| 131 | + headers = { |
| 132 | + 'Authorization': 'Bearer {}'.format(jwt_token), |
| 133 | + 'Content-Type': 'application/json' |
| 134 | + } |
| 135 | + |
| 136 | + # Publish num_messages mesages to the HTTP bridge once per second. |
| 137 | + for i in range(1, args.num_messages + 1): |
| 138 | + payload = '{}/{}-payload-{}'.format( |
| 139 | + args.registry_id, args.device_id, i) |
| 140 | + print('Publishing message {}/{}: \'{}\''.format( |
| 141 | + 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) |
| 152 | + |
| 153 | + print('HTTP response: ', resp) |
| 154 | + |
| 155 | + # Send events every second. State should not be updated as often |
| 156 | + time.sleep(1 if args.message_type == 'event' else 5) |
| 157 | + print('Finished.') |
| 158 | + |
| 159 | + |
| 160 | +if __name__ == '__main__': |
| 161 | + main() |
0 commit comments