[Archive] GCP IoT Core
This library has been archived and is no longer supported.
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()/Properties | Summary |
---|---|
new GOOGLE_IOT_CORE() | Initializes the GOOGLE_IOT_CORE object with the passed configuration. |
{GOOGLE_IOT_CORE} Instance
Methods()/Properties | Summary |
---|---|
.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() . |
.errors | An 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:
Name | Type | Default | Summary |
---|---|---|---|
privateKey | string | MANDATORY | Device 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 |
ca | string | MANDATORY | The root CA for HTTP requests made by this instance. |
mqttCa | string | MANDATORY | The minimal certificate for MQTT requests made by this instance. |
project | string | MANDATORY | GCP IoT Core Project. |
location | string | MANDATORY | GCP IoT Core Location. |
registry | string | MANDATORY | GCP IoT Core Registry. |
device | string | MANDATORY | GCP IoT Core Device. |
[timeout] | number | 90000 | Defaults to 90 seconds (90000ms). Value expected in milliseconds. For HTTP requests, changes the time before a request automatically times out. |
[tokenTimeout] | number | 3600 | Defaults 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
.
Setter | Summary |
---|---|
.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.
Name | Type | Default | Summary |
---|---|---|---|
return | string | - | 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.
Name | Type | Default | Summary |
---|---|---|---|
tokenTimeout | number | config.tokenTimeout | Amount of time this JWT should be valid, in seconds. |
iat | number | (Current time) | The time at which the JWT was issued, in milliseconds |
return | string | - | 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.
Name | Type | Default | Summary |
---|---|---|---|
jwt | string | MANDATORY | The JWT Token used for authentication, returned from makeDeviceJWT |
path | string | MANDATORY | The GRPC Transcoding path. The only GCP IoT Core endpoints are publishEvent ({grpcUrl}:publishEvent ), or setState ({grpcUrl}:setState ), for API v1. |
body | string or function | MANDATORY | string: 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) | function | MANDATORY | The user's callback function, to handle the response. Will pass an Error as err and a Response as resp . |
length | number | - | ver. 2021-03-31+ Only mandatory if body is a function. The total length of the data that is being sent. |
return | undefined | - | - |
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.
Name | Type | Default | Summary |
---|---|---|---|
return | undefined | - | - |
.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.
Name | Type | Default | Summary |
---|---|---|---|
jwt | string | MANDATORY | The JWT Token used for authentication, returned from makeDeviceJWT |
options | object | {} | The MQTT Options from the appropriate MQTT documentation. protocolId , clientId , username , and password are reserved and will be overwritten. |
return | MQTT.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()/Properties | Summary |
---|---|
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.
Name | Type | Default | Summary |
---|---|---|---|
dest | string | MANDATORY | "event" or "state" only. |
message | string | MANDATORY | The desired telemetry or state data, as a string. |
options | object | {"qos": 0} | See the Google Cloud MQTT QoS documentation for details. |
callback | function | - | See the NEQTO MQTT docs |
return | boolean | - | 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.
Name | Type | Default | Summary |
---|---|---|---|
dest | string | MANDATORY | "config" or "commands/#" only. |
options | object | {"qos": 0} | See the Google Cloud MQTT QoS documentation for details. |
callback | function | - | See the NEQTO MQTT docs |
return | boolean | - | 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);
}
});
}
}
}