Google Cloud IoT Core

Learn how to use IoTIFY's network simulator to connect a virtual device to the Google Cloud IoT Core platform.

Introduction

Google Cloud IoT Core is Google’s offering in the IoT cloud platform provider marketplace. It supports MQTT and HTTP as communication protocol. This guide describes how to use IoTIFY network simulator to create virtual devices that communicate with Google Cloud IoT Core.

The official documentation for integration can be found at https://cloud.google.com/iot/docs/how-tos/ This guide is prepared specifically for integrating IoTIFY to Google Cloud IoT Core infrastructure.

1. Sign up with Google Cloud IoT Core and create a new IoT Registry

In Google cloud console, click on the IoT Core project. You will have to enable billing in order to create this project. The IoT Core menu item can be found under Big Data section on the left hand side menu. The very first step is to create an IoT device registry.

Let’s create a new registry named myregistry and choose the region as europe-west1. You will also need to specify the default cloud pub-sub topics for sending events and state from this registry. We just created two default topics for event and state as follows:

These topics will be used later in Step 8 to monitor data coming from IoT devices.

2. Generate public/private key for your device

In order to configure authentication for devices in Google Cloud IoT core, we need to generate a public and private key pair. You could use any tool to create those key pairs, for this guide we will use openssl command-line tool on a Linux machine. Run following two commands to generate a public and private key pairs in RSA 256. Following are the parameters for generating these key pairs.

openssl genpkey -algorithm RSA -out private_key.pem -pkeyopt rsa_keygen_bits:2048
openssl rsa -pubout -in private_key.pem -out public_key.pem

These two commands will produce private_key.pem and public_key.pem files in the current folder.

3. Configure our device in IoT Core

Now let's go back to our registry page and click add device button to add our new virtual device. Lets call it iotify_0

We will keep all the default values. In the text field named public key value we will add our newly generated public key file public_key.pem contents.

That’s it. The device has now been provisioned in Google cloud IoT Core platform. Let’s take note of following 4 values which we will need into IOTIFY template.

Project ID: This is the top level project ID for your IoT Project. Notice that project ID is different than project Name. The ID can be retrieved by clicking the project name on the top blue bar on the Google Cloud console web page. It is also visible in your default telemetry topics while creating registry in step 1. In our example, the project ID is iotify-200307

Region: This is the region where you created your IoT registry. It is set to europe-west1 in our case.

Registry name: This is the name of the registry we just created in step 1. It is set to myregistry in our case.

Device ID: This is the name of the new device which we just provisioned a while ago. It is set to iotify_0 in our case.

Private key: This is the content of the private_key.pem file which we just generated.

These four parameters will now be used to configure our IoTIFY template.

4. IoTIFY HTTP Template.

You can import our IoTify HTTP Boilerplate from the link below

https://raw.githubusercontent.com/iotify/nsim-examples/master/connectors/GCloud-HTTP.json

Or, Make your own from scratch

Once we have all the information, it's time to create a device template in IoTIFY. Let’s create a new HTTP(S) template and set following parameters:-

Protocol: Set to HTTPS (TLS 1.2)

Host: Set to cloudiotdevice.googleapis.com

Path: Path should be set in a specific format of /v1/projects/[Project ID]/locations/[Region]/registries/[Registry Name]/devices/[DeviceID]:publishEvent

E.g. in our case the path would be as follows:

/v1/projects/iotify-200307/locations/europe-west1/registries/myregistry/devices/iotify_0:publishEvent

Method: Change the HTTP method to POST

Additional Headers: In order to authenticate with Google Cloud IoT core, we will need to have a bearer Token in HTTP header. Add following two header fields as follows:

authorization: Bearer {{state.token}}

Content-Type: application/json

Remember that {{state.token}} is a dynamic field, which will be calculated at run time.

This is how our new template will look like

Let’s now create our authentication parameters.

5. Generate JWT token

Google Cloud IoT Core needs JWT token for authentication. The JWT token can be created in the Device Setup function.

Click on the Tab Device setup in our template and paste following contents.

{
  var private_key = `
---- Paste the entire contents of your private_key.pem file here including the
---- header and footer line
  `;
  
  var token = {
        'iat': parseInt(moment().valueOf() / 1000),
        'exp': parseInt(moment().valueOf() / 1000) + 60 * 60 * 24,  // 24 hours is the maximum validity time. The token could be cached if performance of jwt.sign is a problem
        
        // ****** Important: Replace your Project ID below as well*****        
        'aud': 'iotify-200307' 
   };
      
   state.token = jwt.sign(token, private_key, { algorithm: 'RS256' });

  //no need for return 
}

Copy the entire content of your private_key.pem file and paste it into the string value of the private_key variable in the above code. The setup function code will use the private key to generate a JSON Web token and save it into state.token field, which will be reused later.

Make sure that you change your project ID in the aud field as well.

6. Specify the payload

Once the authentication parameters are set, it's time to specify the payload. Unlike other cloud platforms, Google IoT Core is very specific when it comes to payload formatting. You will need to supply the content into a particular format and any violation will generate HTTP Error 400. Nevertheless, paste following contents in the Specify Message Contents tab

{ 
  // Contents has your actual message
  var content = { hello: "world"};
  
  // you could also specify a subfolder pattern here. 
  var subfolder = {};

  var payload = {};

  // we need to base64 encode the values for each of the two keys separately
  payload.binary_data = Buffer.from(JSON.stringify(content)).toString('base64');
  payload.sub_folder = Buffer.from(JSON.stringify(subfolder)).toString('base64');
  
  //return a string value which will be sent as the message payload
  return JSON.stringify(payload, null, 2);
}

That’s it. Click preview button and you should see the content has been posted successfully.

Once the preview is successful, you could go and simulate the template. Remember to specify the number of clients as 1 as we have only configured 1 device in GCP. You could also change the message content to generate contents more dynamically.

7. Use MQTT Template (Optional)

It is also possible to use the MQTT(S) protocol to connect with Google IoT Core. The Device Setup function content and Specify Message Contents value can be reused from the HTTP template above. The only change required is in the MQTT Connection settings as follows:-

Protocol: mqtts (TLS 1.2)

Endpoint: mqtt.googleapis.com:8883

Topic: use the following format: /devices/[deviceID]/events

ClientId: projects/[projectiD]/locations/[location]/registries/[Registryname]/devices/[DeviceID]

E.g. in our setup, the clientID will be as follows:

projects/iotify-200307/locations/europe-west1/registries/myregistry/devices/iotify_0

Username: dummy

Password: {{state.token}}

That’s it. Your virtual device should now be able to connect to GCP IoT Core via MQTT. Click on the preview tab to verify this.

8. Monitoring the published Contents from Google Cloud

Now once your device is ready and publishing successfully to the cloud, it's time to monitor the contents on the pub/sub. For this, we will use the built on google cloud shell console which can be invoked directly from your GCP webpage. Click on the terminal icon on the top bar right hand side.

This will provision a google Cloud console. Enter following commands to subscribe to your newly published topic.

gcloud pubsub subscriptions create --topic projects/iotify-200307/topics/events  mySubscription         

gcloud pubsub subscriptions pull --auto-ack mySubscription

Once you publish a new message via our simulated device, you will be able to see the message contents in the console output.

Summary

In this guide we connected a single device to Google Cloud IoT Core. In future, we will update this guide to enable automated provisioning of devices and scale to a higher number. You could learn more about how to generate dynamic contents here.

Last updated