This tutorial describes how to connect Raspberry Pi to Google Cloud IoT. This Raspberry tutorial will cover step by step how to integrate Raspberry Pi to Google Cloud IoT and how to send data from Raspberry Pi to GCP IoT using MQTT. In more detail, Raspberry Pi uses BME280 to acquire temperature and humidity, then it sends these sensor readings to Google Cloud IoT. Therefore, to do it we will follow these steps:

  • Configuring a GCP IoT
    • Enable PubSub
    • Create and configure a Registry
    • Configuring a Google Cloud IoT device
  • Connecting Raspberry Pi to BMP280
  • Sending data from Raspberry Pi to Google Cloud IoT through MQTT

During this Raspberry tutorial, we will use Google Cloud Console (CLI) instead of configuring the GCP using Web Interface. If you want to use the Web interface to configure the GCP you can read my previous tutorial covering how to connect ESP32 to Google Cloud.

Configuring Google Cloud IoT

Before connecting Google Cloud IoT to Raspberry Pi, it is necessary to configure the Google Cloud IoT.

Configuring the Google Cloud Project

Before starting this tutorial, it is necessary you create a Google Cloud IoT account. Then, using the interface, let us create a new project. In this Raspberry Pi tutorial, this Google Cloud project name is raspberry-gcp:

export PROJECT_ID="raspberry-gcp"
gcloud projects create $PROJECT_ID
gcloud config set project $PROJECT_ID

Next, once the project is created, it is time to enable Google Cloud API:

gcloud services enable pubsub.googleapis.com
new console "https://console.cloud.google.com/iot/api?project=$PROJECT_ID"

Otherwise, you can open the browser log in into the Google console and then write this URL:

https://console.cloud.google.com/iot/api?project=raspberry-gcp

Creating a Google Cloud IoT Topic

Then, we have to create a topic where we will publish data:

export pub_topic="rasp-pub"
export subscription=”rasp-sub”

gcloud pubsub topics create $pub_topic
gcloud pubsub subscriptions create $subscription --topic $pub_topic

Using the code above, we have created a topic where we will publish data coming from Raspberry Pi once it is connected to GCP IoT. Moreover, we have created a subscription to the same topic so that we can receive data. The topic is rasp-pub.

Configuring a Google Registry

After creating the topic, we have to create the Google cloud registry. Using the CLI write to the following lines:

export registry_name=”swa_registry”
export region="europe-west1"
gcloud iot registries create $registry_name \
  --region=$region \
  --event-notification-config=topic=$pub_topic \
  --enable-mqtt-config --enable-http-config

Notice that the registry is swa_registry, while the region is europe-west1. You can change the registry name as you prefer, while the region depends on the country where you live. We will use these information when we will connect the Raspberry Pi to Google Cloud IoT to send data through MQTT.

Checking the Google Cloud Project

Before going on, it is useful to check that all the work made till now is correct. Let us connect to the Google Cloud console and select the project you have created. You should see the following information:

If everything is ok we can go on adding a device to Google Cloud.

Creating the Raspberry Pi certificate to connect to Google IoT

Add a new device using the Google Console as shown in the picture below:

Configuring the device in Google Cloud IoT

To create the certificate to use in the previous configuration, you have to use this command:

openssl req -x509 -newkey rsa:2048 -keyout rasp_private.pem -nodes -out rasp_cert.pem -subj "/CN=unused"

Using the previous command, we have created two different certificates:

  • public certificate named rasp_cert.pem that we wil use in the Google Console
  • private certificate named rasp_private.pem that we will use to connect Raspberry Pi to Google Cloud IoT

How to connect Raspberry Pi to Google Cloud IoT

After we have completed all the steps above, it is time to connect GCP IoT to Raspberry Pi. To do it we will use NodeJS that you have to install in your Raspberry Pi before going on.

As described before, Raspberry Pi connects to BME280 sensor to acquire temperature and humidity. Moreover, Raspberry Pi will send this information to GCP IoT using MQTT. If you don’t have a BME280 sensor you can use a different sensor.

Connecting Raspberry Pi to BME280

The schematic below shows how to connect Raspberry Pi with BME280 so that we can read sensor data to send to GCP:

Finally, it is time to develop the NodeJS application to connect the Raspberry Pi to Google Cloud IoT.

Configuring the NodeJS Project

Before developing the code, it is necessary to create a new directory that will hold the NodeJS source code:

mkdir rasp-gcp

Then initialize the project:

npm init -y

Moreover, it is necessary to install the library that we will use in our NodeJS code:

npm install jsonwebtoken --save
npm install bme280 --save
npm install mqtt --save

Implementing the NodeJS code to connect Raspberry Pi to CGP

The NodeJS code is shown below:

var fs = require('fs');
var jwt = require('jsonwebtoken');
var mqtt = require('mqtt');
var bme280 = require('bme280');

// Define project info
var projectId = "raspberry-gcp";
var region = "europe-west1";
var registryId = "swa_registry";
var deviceId = "rasp-device";

// MQTT Broker
var mqttHost = "mqtt.googleapis.com";
var mqttPort = 8883;
var alg = "RS256";

// MQTT topic
var mqttTopic = "/devices/rasp-device/events";


// Key
var privateKeyFile = "/home/pi/rasp-gcp/certs/rasp_private.pem";

// Let us make clientId
var clientId = "projects/" + projectId + "/locations/" +  region + "/registries/" + registryId + "/devices/" + deviceId;
console.log("Client Id ["+clientId+"]");
const mqttArgs = {
   host: mqttHost,
   port: mqttPort,
   clientId: clientId,
   username: 'unused',
   password: createJwt(projectId, privateKeyFile, alg),
   protocol: 'mqtts',
   secureProtocol: "TLSv1_2_method"
}

// Connecting
var client = mqtt.connect(mqttArgs);
client.on('connect', function(success) {
   
   if (!success) {
      console.log("client not connected...");
   } else {
      console.log("connected");
      sendData();
   }
});

client.on('error', function(err) { 
  console.log('error', err); 
});

client.on('close', function() {
   console.log("Connection closed");
  }
);

client.on('message', function(topic, message, packet) { 
  console.log(topic, 'message received: ', Buffer.from(message, 'base64').toString('ascii')); 
});  

function createJwt(projectId, privateKeyFile, algorithm) { 
  var token = { 
    'iat': parseInt(Date.now() / 1000), 
    'exp': parseInt(Date.now() / 1000) + 3600, 
    'aud': projectId 
  }; 
  var privateKey = fs.readFileSync(privateKeyFile); 
  return jwt.sign(token, privateKey, {algorithm: algorithm}); 
} 

function sendData() {
   bme280.open( {
         i2cAddress: 0x76
      }).then(async sensor => {
      var data = await sensor.read();
      console.log(data);
      var payload = JSON.stringify(data); 
      console.log("Publishing data to MQTT Topic...");
      client.publish(mqttTopic, payload, {qos: 1});
      await sensor.close();      
   }).catch(console.log);
   setTimeout(sendData, 60000);
}

In the beginning, you have to replace the values with your values. The code is quite simple. Notice that the MQTT password it the JWT token.

Testing the connection between Raspberry Pi and Google Cloud IoT

Now we can test the result:

Raspberry Pi connects to Google Cloud IoT

Wrapping up

At the end of this Raspberry Pi tutorial, we have covered how to connect Raspberry Pi to the Google Cloud IoT platform using NodeJS. We have described how to use MQTT to integrate Raspberry with GCP IoT platform and how to send sensor readings.

LEAVE A REPLY

Please enter your comment!
Please enter your name here