NEQTO Docs
  • Languages iconEnglish
    • 日本語
  • Docs
  • API
  • FAQ

›Integration

Getting Started

  • NEQTO Hello World!
  • Tutorial Step 1. NEQTO Console Setting
  • Tutorial Step 2. Device Settings & Launching Service (NEQTO Bridge)
  • Tutorial Step 2. Device Settings & Launching Service (STM32 Discovery)
  • Tutorial Step 2. Device Settings & Launching Service (SPRESENSE)
  • Tutorial Step 3. Application development using scripts

NEQTO

  • NEQTO Account Registration
  • Sub-accounts
  • API Usage
  • NEQTO CloudSync for GCP
  • NEQTO Engine Firmware List
  • Support Guidelines

NEQTO Console

  • Introduction
  • Fundamentals
  • Administrative Actions
  • Device Management
  • Linux-based Device Management
  • Batch Registration
  • Scripts
  • Actions and Contacts
  • View Data from the Console
  • NEQTO Apps

    • About NEQTO Apps
    • NEQTO Infinitypool
    • NEQTO Insights
    • NEQTO Custodia
    • NEQTO Flow
  • Machine Driver
  • Recommended Browsers
  • Billing Information

SPRESENSE

    Hardware Specifications

    • 01. About Spresense

    Software Specifications

    • 01. Operational Flow
    • 02. Initial Installation
    • 03. Spresense Wi-Fi Initial Setup
    • 04. Spresense LTE-M Initial Setup
    • 05. Debug Log Acquisition
    • 06. System LED Indications
    • 07. Event Messages
    • 08. Updating Firmware

    neqto.js

    • 01. About neqto.js
    • 02. Log
    • 03. Timers
    • 04. HTTP
    • 05. HTTPS
    • 06. MQTT
    • 07. Secure
    • 08. Storage
    • 09. Sleep
    • 10. RTC
    • 11. GPIO
    • 12. UART
    • 13. SPI
    • 14. I2C
    • 15. ADC
    • 16. GNSS
    • 17. Camera
    • 18. Utils
    • 19. nqSpresense
    • 20. nqService
    • 21. nqMqtt
    • 22. nqFOTA
    • 23. nqWiFi
    • 24. nqLte

STM32 Discovery

    Hardware Specifications

    • 01. About STM32 Discovery Kit (B-L4S5I-IOT01A)

    Software Specifications

    • 01. Operational Flow
    • 02. Initial Installation
    • 03. STM32 Discovery Wi-Fi Initial Setup
    • 04. Debug Log Acquisition
    • 05. System LED Indications
    • 06. Event Messages
    • 07. Updating Firmware

    neqto.js

    • 01. About neqto.js
    • 02. Log
    • 03. Timers
    • 04. HTTP
    • 05. HTTPS
    • 06. MQTT
    • 07. Secure
    • 08. Storage
    • 09. Sleep
    • 10. RTC
    • 11. UserSW
    • 12. GPIO
    • 13. UART
    • 14. SPI
    • 15. I2C
    • 16. ADC
    • 18. Utils
    • 19. nqDiscovery
    • 20. nqService
    • 21. nqMqtt
    • 22. nqFOTA
    • 23. nqWiFi

NEQTO Bridge

    Hardware Specifications

    • 01. NEQTO Bridge Module
    • 02. NEQTO Bridge Wi-Fi Module
    • 03. NEQTO Bridge LTE-1 Module
    • 04. NEQTO Bridge LTE-M/NB Module
    • 05. NEQTO Bridge IO Board
    • 06. NEQTO Bridge Digital IO Board
    • 07. NEQTO Bridge Connector Board

    Software Specifications

    • 01. Operational Flow
    • 02. NEQTO Bridge Wi-Fi Module Initial Setup
    • 03. NEQTO Bridge LTE Module Initial Setup
    • 04. Debug Log Acquisition
    • 05. System LED Indications
    • 06. Event Messages
    • 07. Updating Firmware

    neqto.js

    • 01. About neqto.js
    • 02. Log
    • 03. Timers
    • 04. HTTP
    • 05. HTTPS
    • 06. MQTT
    • 07. Secure
    • 08. Storage
    • 09. Sleep
    • 10. RTC
    • 11. UserSW
    • 12. GPIO
    • 13. UART
    • 14. SPI
    • 15. I2C
    • 16. ADC
    • 17. BLE
    • 18. Utils
    • 19. nqBridge
    • 20. nqService
    • 21. nqMqtt
    • 22. nqFOTA
    • 23. nqWiFi
    • 24. nqLte
    • 25. nqLAN
    • 26. nqEx

Linux-based device

    Software Specifications

    • 01. System Requirements
    • 02. Installation
    • 03. Software Configurations
    • 04. Operational Flow
    • 05. Debug Log Acquisition
    • 06. Event Messages
    • 07. Updating Software

    neqto.js

    • 01. About neqto.js
    • 02. Log
    • 03. Timers
    • 04. HTTP
    • 05. HTTPS
    • 06. MQTT
    • 07. Secure
    • 08. Storage
    • 09. RTC
    • 10. UNIXSocket
    • 11. FileSystem
    • 12. SubProcess
    • 13. Utils
    • 14. nqLinux
    • 15. nqService
    • 16. nqMqtt
    • 17. nqFOTA
    • 18. nqLAN

neqto.js Libraries

  • About neqto.js Libraries
  • UART

    • GM65 Barcode Reader
    • SRF Ultrasonic Range Finder - Serial Mode

    I2C

    • HTS221 v2 Temperature and Humidity Sensor
    • LIS2DW12 v2 Accelerometer
    • SRF Ultrasonic Range Finder - I2C Mode
    • [Archive] HTS221 Temperature and Humidity Sensor
    • [Archive] LIS2DW12 Accelerometer

    Utils

    • RTC Alarm Synchronized Scheduler

    Integration

    • AWS S3 v2
    • AWS IoT Core v2
    • Azure IoT v2
    • GCP IoT Core
    • [Archive] AWS S3
    • [Archive] AWS IoT Core

neqto.js Snippets

  • About neqto.js Snippets
  • DataDog
  • Dropbox
  • Google Sheets
  • InfluxDB
  • Oracle Cloud Object Storage
  • Salesforce
  • SAP Cloud Platform Internet of Things
  • Splunk
  • Niagara

Release Notes

  • NEQTO Console Updates
  • NEQTO Firmware (Bridge Wi-Fi/LTE Module) Releases
  • NEQTO Firmware (STM32 Discovery Wi-Fi) Releases
  • NEQTO Firmware (Spresense Wi-Fi/LTE-M) Releases
  • NEQTO Engine for Linux Releases

GCP IoT Core

This library is a built-in class that provides functions to communicate with Google Cloud IoT Core.

Library usage requirements
Type Integrations
Name Google_IoT_Core
Version 2021-03-31
Code size used 4.1KB
Resources used HTTPS x 1, MQTT x 1, Timers x 1

Related Documents

For information on the Google Cloud IoT Core API used in this library, please refer to the documentation.



Abstracts

Methods()/PropertiesSummary
new GOOGLE_IOT_CORE()Initializes the GOOGLE_IOT_CORE object with the passed configuration.

{GOOGLE_IOT_CORE} Instance

Methods()/PropertiesSummary
.buildGrpcUrl()Build a URL using gRPC Transcoding syntax from the set configuration.
.makeDeviceJWT()Creates a valid JWT for use with GCP, following the JWT documentation
.httpPost()Sends a POST request to the Google Cloud IoT REST Device API. See Publishing over HTTP for information on publishing telemetry events or updating the device configuration.
.abortHttpRequest()Aborts the ongoing HTTP request.
.mqttConnect()Performs the necessary setup and connects the GCP IoT Core long-term service MQTT domain. Extends the MQTT.Client object with Client.exPublish() and Client.mqttSubscribe().
.errorsAn array containing the invalid configuration key names. Exists only when an invalid configuration is passed to setConfig or the constructor.

Details

new GOOGLE_IOT_CORE(config)

Initializes the GOOGLE_IOT_CORE object according to its initial configuration.

Configuration

When instantiating the GOOGLE_IOT_CORE object, the following configuration options are mandatory:

NameTypeDefaultSummary
privateKeystringMANDATORYDevice private key. Upload the corresponding public key in the Google Cloud IoT Core console before use. Must be a valid JavaScript string.
- Creating public/private key pairs on Google Cloud IoT Core
castringMANDATORYThe root CA for HTTP requests made by this instance.
mqttCastringMANDATORYThe minimal certificate for MQTT requests made by this instance.
projectstringMANDATORYGCP IoT Core Project.
locationstringMANDATORYGCP IoT Core Location.
registrystringMANDATORYGCP IoT Core Registry.
devicestringMANDATORYGCP IoT Core Device.
[timeout]number90000Defaults to 90 seconds (90000ms). Value expected in milliseconds. For HTTP requests, changes the time before a request automatically times out.
[tokenTimeout]number3600Defaults to 60 minutes (3600s). Amount of time a generated JWT is valid (in seconds).

config must be a JavaScript object in the following form:

var config = {
    privateKey: "<String>",
    ca: "<String>",
    mqttCa: "<String>",
    project: "<String>",
    location: "<String>",
    registry: "<String>",
    device: "<String>",
    timeout: "<Number>",
    tokenTimeout: "<Number>",
};

Once the configuration object has been created, it can be passed to GOOGLE_IOT_CORE during instance creation. If any invalid values are passed, the invalid key names are stored in the errors property, and should be handled appropriately.

var iot = new GOOGLE_IOT_CORE(config);
if ('errors' in iot) {
    // TODO: handle errors
}

Setter Methods

After creating an instance of the GOOGLE_IOT_CORE object, each of the aforementioned configurations may be changed by its corresponding setter function. If an invalid value is passed to any setter, it returns false.

SetterSummary
.setPrivateKey(value: string)Set the private key used for authenticating this device with GCP IoT Core. Upload the corresponding public key in the Google Cloud IoT Core console before use. Must be a valid JavaScript string.
- Creating public/private key pairs on Google Cloud IoT Core
.setTimeout(value: number)Set the HTTP request timeout for this instance (default: 90000 ms (90 seconds))
.setTokenTimeout(value: number)Set the token timeout for this instance (default: 60*60*1000 ms (1 hour))
.setProject(value: string)Set the IoT Core instance project used for building the REST endpoint
.setLocation(value: string)Set the IoT Core instance location used for building the REST endpoint
.setRegistry(value: string)Set the IoT Core instance registry used for building the REST endpoint
.setDevice(value: string)Set the IoT Core instance device used for building the REST endpoint
.setRootCA(value: string)Set the Root CA for GCP IoT Core. See "Object Usage Example" for a sample value
.setMqttCa(value: string)Set the MQTT CA for GCP IoT Core. See "Object Usage Example" for a sample value

.setConfig(config)

The setConfig function can be used to set or change multiple configuration options at the same time. This function expects a typical JavaScript object of key:value pairs as an argument. If any invalid values are passed, this returns an array containing the names of each invalid key, and sets the errors property to that array. When a valid config is passed to setConfig, if errors exists, it is removed.

iot.setConfig({
    privateKey: "value",
    ca: "value",
    project: "value",
    location: "value",
    registry: "value",
    device: "value"
});

Instance Methods

.buildGrpcUrl()

Build a URL using gRPC Transcoding syntax from the set configuration.

NameTypeDefaultSummary
returnstring-A string containing the gRPC URL in the form projects/{PROJECT}/locations/{LOCATION}/registries/{REGISTRY}/devices/{DEVICE}

.makeDeviceJWT([tokenTimeout][,iat])

Creates a valid JWT for use with GCP, following the JWT documentation.

NameTypeDefaultSummary
tokenTimeoutnumberconfig.tokenTimeoutAmount of time this JWT should be valid, in seconds.
iatnumber(Current time)The time at which the JWT was issued, in milliseconds
returnstring-The JWT signed with the passed privateKey with a 24 hour expiry.

.httpPost(jwt,path,body,callback,length)

Sends a POST request to the Google Cloud IoT REST Device API. See Publishing over HTTP for information on publishing telemetry events or updating the device configuration.

NameTypeDefaultSummary
jwtstringMANDATORYThe JWT Token used for authentication, returned from makeDeviceJWT
pathstringMANDATORYThe GRPC Transcoding path. The only GCP IoT Core endpoints are publishEvent ({grpcUrl}:publishEvent), or setState ({grpcUrl}:setState), for API v1.
bodystring or functionMANDATORYstring: The intended payload to send to the path. GCP IoT Core accepts only JSON strings in the correct format for the endpoint. The maximum payload size is 4KB.

[ver. 2021-03-31+]
function: Callback (body) for retrieving the payload to send. Returns data in [string/ArrayBuffer] chunks of 4KB or less until exhausted, then returns null. Payloads larger than 4KB can be handled.
callback(err, resp)functionMANDATORYThe user's callback function, to handle the response. Will pass an Error as err and a Response as resp.
lengthnumber-ver. 2021-03-31+
Only mandatory if body is a function. The total length of the data that is being sent.
returnundefined--

Responses

This library uses an object to handle AWS IoT Core responses. These responses are always in the following format:

{
    statusCode: <Number>,
    statusMessage: <String>,
    body: <String>
}

More details on statusCode and statusMessage can be seen in the HTTPS documentation for the appropriate device (NEQTO Bridge | Spresense).

body is the HTTP response data.

Errors

This library passes an Error object from HTTP errors into the user-provided callback. Error objects have the following form:

{
    errCode: <Number>
}

This errCode parameter has more information in the appropriate device (NEQTO Bridge | Spresense).

.abortHttpRequest()

Abort the currently ongoing HTTP request.

NameTypeDefaultSummary
returnundefined--

.mqttConnect(jwt,[options])

Performs the necessary setup and connects to GCP IoT Core over MQTT. Connects to the long-term MQTT domain. If the connnection is successful, the MQTT.Client object is extended with exPublish and exSubscribe as described below.

NameTypeDefaultSummary
jwtstringMANDATORYThe JWT Token used for authentication, returned from makeDeviceJWT
optionsobject{}The MQTT Options from the appropriate MQTT documentation. protocolId, clientId, username, and password are reserved and will be overwritten.
returnMQTT.Client-The MQTT.Client object returned from a mqtt.connect() call. See the appropriate device's MQTT page for more details on this object.
- NEQTO Bridge
- Spresense

MQTT.Client Methods

Methods()/PropertiesSummary
Client.exPublish()Publishes to /devices/${device}/${dest} -- "event" and "state" are the only valid options.
Client.mqttSubscribe()Subscribes to /devices/${device}/${dest} -- "config" and "commands/#" are the only valid endpoints.

.exPublish(dest,message[,options][,callback])

Publishes to /devices/${device}/${dest} -- "event" and "state" are the only valid options.

NameTypeDefaultSummary
deststringMANDATORY"event" or "state" only.
messagestringMANDATORYThe desired telemetry or state data, as a string.
optionsobject{"qos": 0}See the Google Cloud MQTT QoS documentation for details.
callbackfunction-See the NEQTO MQTT docs
returnboolean-true if a valid dest was passed; false otherwise. Actual response of the subscribe returned to callback.

.exSubscribe(dest[,options][,callback])

Subscribes to /devices/${device}/${dest} -- "config" and "commands/#" are the only valid endpoints. For more information, refer to the Google Cloud documentation for MQTT Configuration and Receiving A Command.

NameTypeDefaultSummary
deststringMANDATORY"config" or "commands/#" only.
optionsobject{"qos": 0}See the Google Cloud MQTT QoS documentation for details.
callbackfunction-See the NEQTO MQTT docs
returnboolean-true if a valid dest was passed; false otherwise. Actual response of the subscribe returned to callback.

Usage Examples

Click here to learn how to get the CA that can be used in the config option.

Verify that the root CA is appropriate for the desired use and GCP IoT Core endpoint.

var gcpIotCa = '-----BEGIN CERTIFICATE-----\n...<CA>...\n-----END CERTIFICATE-----';
var mqttMinCa = '-----BEGIN CERTIFICATE-----\n...<CA>...\n-----END CERTIFICATE-----';

The following sample code sections all use the following configuration:

// IMPORTED LIBRARIES
// - Google_IoT_Core

// Logging setup
log.setLevel(0,2); //-1:NONE 0:ERROR 1:WARNING 2:DEBUG 3:TRACE, 0:DISABLE 1:LOG 2:CONSOLE 3:BOTH
log.printLevel(2); //0:DISABLE 1:LOG 2:CONSOLE 3:BOTH

// Set configurations
var config = {
    privateKey: "<String>",
    project: "<String>",
    location: "<String>",
    registry: "<String>",
    device: "<String>"
};

var iot = new GOOGLE_IOT_CORE(config);

if ('errors' in iot) {
    // TODO: Handle errors
    throw 'Invalid configuration'
}

Sample 1: Basic HTTPS Usage

iot.setRootCA(gcpIotCa);
var host = iot.buildGrpcUrl();
var payload = secure.base64Encode("Publishing via HTTP");
var callback = function(err, resp) {
    if (err) {
        print(JSON.stringify(err));
    }
    if (resp) {
        print(JSON.stringify(resp));
    }
}
var body = {
    "binary_data": payload
}
var jwt = iot.makeDeviceJWT(3600);  //update JWT each connection. 3600 == 1 hour.
iot.httpPost(jwt, `${host}:publishEvent`, JSON.stringify(body), callback);

Sample 2: Using HTTPS With a Large Payload

iot.setRootCA(gcpIotCa);
var host = iot.buildGrpcUrl();
// This simulates a large payload.
// In a production environment, this may be collected data from attached devices.
var sensorData = "";
while (sensorData.length < 4096) {
  sensorData += sensorData.length.toString();
}
// See the Secure object documentation for possible limitations.
var encodedData = secure.base64Encode(sensorData);
var payload = JSON.stringify({
  "binary_data": encodedData
});
var callback = function(err, resp) {
    if (err) {
        print(JSON.stringify(err));
    }
    if (resp) {
        print(JSON.stringify(resp));
    }
}
// body must be a function that returns data in chunks until exhausted, then returns null
var returnedDataChunks = 0;
var body = function() {
  var retSize = payload.length / 8;
  if (returnedDataChunks < 8) {
    return payload.slice(returnedDataChunks++ * retSize, returnedDataChunks * retSize)
  } else {
    return null;
  }
}
var jwt = iot.makeDeviceJWT(3600);  //update JWT each connection. 3600 == 1 hour.
// [length] parameter is needed because body is a function
iot.httpPost(jwt, `${host}:publishEvent`, body, callback, payload.length);

Sample 3: Using MQTT with Token Refresh

iot.setMqttCa(mqttMinCa);
var reconnectAttempts = 0;
var client;

var reconnectSt = 0;    //0: No reconnect, 1: Reconnect backoff, 2: Expired backoff(available reconnect)
var scheduleMqttReconnect = function() {
    if(reconnectSt) {
        return;
    }
    reconnectSt = 1;    //waiting reconnect
    var backoff = 64 * 1000;    //backoff[msec]
    reconnectAttempts++;
    //Notice: This example updates the JWT for each connection.
    //        You may want to check the token timeout and update the JWT.
    //        [Refer](https://cloud.google.com/iot/docs/how-tos/credentials/jwts#required_claims)
    if(client) {
        client.end(); // close the connection, free resources
        client = undefined; // destroy the current client
    }
    print('Reconnect backoff[ms]:' + backoff);
    setTimeout(function() {
        print('Backoff expired');
        reconnectSt=2;
    }, backoff);
}

var registerEventHandlers = function() {
    if(!client){
        print('skip registerEventHandlers()');
        return; // quit
    }
    client.on('connect', function() {
        reconnectAttempts = 0;
        if(client.isConnected()){
            var rc = client.exSubscribe('config', { qos : 1 }, function(err) {
                if(err.code != 0){
                    print('exSubscribe() failed');
                    //TODO: Error Handling. (Reconnect is recommended)
                }
            });
            if(!rc) {throw 'subscribe topic failed';}
            var rc = client.exSubscribe('commands/#', { qos : 1 }, function(err) {
                if(err.code != 0){
                    print('exSubscribe() failed');
                    //TODO: Error Handling. (Reconnect is recommended)
                }
            });
            if(!rc) {throw 'subscribe topic failed';}
        }
    });
    client.on('error', function(err) {
        print('mqttClientOnError: ' + err.code);
        if(err.code == 1) {     // 1: connection failed
            var errnoConnect = client.get('errnoConnect');
            print('errnoConnect ' + errnoConnect);
            scheduleMqttReconnect();
        } else {
            //TODO: Error Handling.
        }
    });
    client.on('message', function(topic, message) {
        print('TOPIC ' + topic);
        print('MESSAGE ' + message);
        //TODO: Message Handling
    });
    client.on('close', function() {
        print('DISCONNECTED');
        scheduleMqttReconnect();
    });
}

var publishInterval = 60 * 1000;
var publishEvent = 0;
setInterval(function() {
    publishEvent = 1;
}, publishInterval);

//  Main loop
reconnectSt = 2;
while(1) {
    if(reconnectSt == 2) {  //Allow MQTT connection
        reconnectSt = 0;
        if(!client) {
            var jwt = iot.makeDeviceJWT(3600);  //update JWT each connection. 3600 == 1 hour.
            client = iot.mqttConnect(jwt);
            if(!client) {
                scheduleMqttReconnect();
            } else {
                registerEventHandlers();
            }
        } else {
            client.reconnect();
        }
    }
    if(client && client.canPublish()) {
        if(publishEvent) {
            publishEvent = 0;
            client.exPublish('event', 'Publishing over MQTT', { qos : 1 }, function(err) {
                if(err.code == 0) {
                    print('publish success');
                } else {
                    print('publish failure ' + err.code);
                }
            });
        }
    }
}

The company names and product names mentioned above are registered trademarks or trademarks of their respective companies.

Updated: 2023-01-20
← Azure IoT v2[Archive] AWS S3 →
  • Abstracts
    • {GOOGLE_IOT_CORE} Instance
  • Details
    • new GOOGLE_IOT_CORE(config)
    • Setter Methods
    • Instance Methods
  • Usage Examples
    • Sample 1: Basic HTTPS Usage
    • Sample 2: Using HTTPS With a Large Payload
    • Sample 3: Using MQTT with Token Refresh
AboutNewsProductsFAQPrivacy Policy}
NEQTO Console
IntroductionFundamentalsAdministrative ActionsDevice Management NEQTO Apps
NEQTO Bridge
NEQTO Bridge ModuleNEQTO Bridge Wi-Fi ModuleNEQTO Bridge LTE-1 ModuleError Logging Event Messages
API Documentation
API UsageGlobal APIRegional APIAPI Terms of Service
Jigsaw, Inc.
© 2023 JIG-SAW INC.