Sending data through MQTT

Let's get the MQTT client from the official GCP GitHub repository. In this simple example, we are going to use Node.js:

  1. First, we need to clone the Node.js client from the official repository. From the root path where we have stored our certificate, enter the following command:
$ mkdir my-iiot-device
$ cd my-iiot-device
$ git clone https://github.com/GoogleCloudPlatform/nodejs-docs-samples
$ cd nodejs-docs-samples/iot/mqtt_example/
$ npm install
  1. We can then start publishing. The following code sends an MQTTS payload to the IoT core that was just configured on europe-west1, identifying itself as my-iiot-device:
$ node cloudiot_mqtt_example_nodejs.js 
--projectId=iiot-book
--cloudRegion=europe-west1
--registryId=iiot-book-registry
--deviceId=my-iiot-device
--privateKeyFile=../../../../../certificates/device_private.pem
--algorithm=RS256
  1. Finally, we can check the reception status on the Registry details page, as shown in the following screenshot:

Registry details page
  1. We now need to change the payload so that it is compliant with our CSV format. On line 161 of the cloudiot_mqtt_example_nodejs.js file located in the nodejs-docs-samples/iot/mqtt_example/ directory, we need to replace the payload with the following:

setTimeout(function () {
//const payload = `${argv.registryId}/${argv.deviceId}-payload-${messagesSent}`;
const ts = new Date().getTime();
const payload =
`${argv.registryId}.${argv.deviceId}.signal1,${messagesSent},${ts},GOOD`;

The expected output is as follows:

Publishing to the GCP IoT
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset