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

›neqto.js Snippets

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

Google Sheets

This snippet provides a function to send IoT data to Google Sheets.

Resources used: HTTPS x 1


Details

The send_sheets function can be used to POST the passed string 'payload' to Google Sheets according to the specified 'parameters' using an Access Token, over HTTPS. The Access Token can be retrieved by the getAccessToken function using a Service Account Email and Private Key. The result (error/response) is then passed to the callback function.

To start using this snippet, SERVICE_ACCOUNT (Service Account with permissions to sheets.googleapis.com), PRIVATE_KEY (Private Key linked to the provided Service Account), and CA are required to be configured by the user.

NOTE: The provided function can handle data sizes up to 4KB. To handle larger data sizes, please refer to divided writing for https objects in the neqto.js documentation.

Click here to learn how to get a CA.

var CA = "-----BEGIN CERTIFICATE-----\n...<CA>...\n-----END CERTIFICATE-----"
//=================================================================
// GOOGLE SHEETS SNIPPET
//=================================================================

//=================================================================
// The following configuration are MANDATORY. Set by user.
//=================================================================
// The email address of the service account created on Google Cloud Platform that has permission to use `sheets.googleapis.com`.
// eg. '<service_account_name>@<gcp_project_id>.iam.gserviceaccount.com'
var SA_EMAIL = "<YOUR_SERVICE-ACCOUNT-EMAIL>";

// A generated private key for the Service Account from Google Cloud Platform.
// eg. '-----BEGIN PRIVATE KEY-----\n...<PRIVATE_KEY>...\n-----END PRIVATE KEY-----'
var PRIVATE_KEY = '<YOUR_PRIVATE-KEY>';

// The ID of the Spreadsheet to append data to.
// eg. 'https://docs.google.com/spreadsheets/d/<SPREADSHEET_ID>/edit#gid=0'
var SPREADSHEET_ID = '<YOUR_SPREADSHEET-ID>';

// Public certificate of the certificate authority that signed the Google API server certificate for SSL/TLS handshake.
// eg. '-----BEGIN CERTIFICATE-----\n...<CA>...\n-----END CERTIFICATE-----'
var CA = '<YOUR_CA>';
//=================================================================

/**
 * Get Access Token from Google Sheets using Service Account email by JWT assertion.
 * https://developers.google.com/identity/protocols/oauth2#serviceaccount
 * @function getAccessToken
 * @param {object} sessionInfo - Information about the session, as an Object.
 * @param {number} tokenTimeout - Amount of time (in seconds) to generate a valid JWT for before it expires, as a Number.
 * @param {function} callback - User callback to return the result (error/response).
 * @returns {undefined}
 */
var getAccessToken = function (sessionInfo, tokenTimeout, callback) {
    // Make JWT for assertion
    var created = Math.ceil((new Date()).getTime() / 1000);
    var claim = {
        "iss": SA_EMAIL,
        "scope": 'https://www.googleapis.com/auth/spreadsheets',
        "aud": 'https://www.googleapis.com/oauth2/v4/token',
        "iat": created,
        "exp": created + parseInt(tokenTimeout)
    };
    var hdrB64 = secure.base64Encode('{"alg":"RS256","typ":"JWT"}').replace(/=/g, ""); // 'eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9'
    var claimB64 = secure.base64Encode(JSON.stringify(claim)).replace(/=/g, "");
    var stringSign = hdrB64 + "." + claimB64;
    secure.setSign('sha256');
    secure.signUpdate(stringSign);
    var signature = secure.signDigest(PRIVATE_KEY);
    var sigB64 = secure.base64Encode(signature).replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_");
    var JWT = hdrB64 + "." + claimB64 + "." + sigB64;

    var options = {
        "method": 'POST',
        "host": 'oauth2.googleapis.com',
        "path": `/token?grantType=urn:ietf:params:oauth:grant-type:jwt-bearer&assertion=${JWT}`,
        "headers": {
            "Content-type": 'application/json',
            "Content-Length": '0'
        },
        "ca": CA
    };
    var request = https.request(options, function (response) {
        response.on('end', function () {
            var resBody = response.read();
            if (response.statusCode == 200) { // 200 - OK
                var resBodyObj = JSON.parse(resBody);
                sessionInfo.accessToken = resBodyObj.access_token;
            }
            callback(null, { "statusCode": response.statusCode, "statusMessage": response.statusMessage, "body": resBody });
        });
    });
    request.on('error', function () {
        callback({ "errCode": request.errCode }, null);
    });
    request.end(function () {
        print("[request] SUCCESS");
    });
};

/**
 * Append values to Google Sheets spreadsheet range using an Access Token.
 * https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/append
 * @function send_sheets
 * @param {object} sessionInfo - Information about the session, as an Object.
 * @param {string} parameters - Query parameters for the request, as an Object.
 * @param {object} payload - Range in A1 format to append to, and the corresponding values in ValueRange format, as an Object.
 * @param {function} callback - User callback to return the result (error/response).
 * @returns {undefined}
 */
var send_sheets = function (sessionInfo, parameters, payload, callback) {
    var body = JSON.stringify(payload);
    var query_parameters = Object.keys(parameters).map(function (key) {
        return `${encodeURIComponent(key)}=${encodeURIComponent(parameters[key])}`;
    }).join('&');
    var options = {
        "method": 'POST',
        "host": 'sheets.googleapis.com',
        "path": `/v4/spreadsheets/${SPREADSHEET_ID}/values/${payload["range"]}:append?${query_parameters}`,
        "headers": {
            "Authorization": `Bearer ${sessionInfo.accessToken}`,
            "Content-Type": 'application/json',
            "Content-Length": body.length.toString()
        },
        "ca": CA
    };
    var request = https.request(options, function (response) {
        response.on('end', function () {
            callback(null, { "statusCode": response.statusCode, "statusMessage": response.statusMessage, "body": response.read() });
        });
    });
    request.on('error', function () {
        callback({ "errCode": request.errCode }, null);
    });
    request.end(body, function () {
        print("[request] SUCCESS");
    });
};

Function Usage Example

The following example script uses the send_sheets function to continuously send data to the set Google Sheets spreadsheet at regular intervals, and re-fetches the token using the getAccessToken function when it expires.

/*
<INSERT ABOVE SNIPPET HERE WITH SET CONFIGURATIONS>
*/

//=================================================================
log.setLevel(-1);       //-1:NONE 0:ERROR 1:WARNING 2:DEBUG 3:TRACE
log.printLevel(2);      //0:DISABLE 1:LOG 2:CONSOLE 3:BOTH
//=================================================================
// MAIN SCENARIO
//=================================================================

/**
 * Callback to fetch error/response from the request.
 * @function callback
 * @param {object} err - Error returned if the request failed. Has one property - `errCode`.
 * @param {object} data - Response returned by a successfully completed request. Has three properties - `statusCode`, `statusMessage`, and `body`.
 */
var callback = function (err, data) {
    if (err) {
        print("[error]", err.errCode);
    } else {
        print("[status]", data.statusCode, data.statusMessage);
        print("[response]", data.body);
    }
};

/**
 * Object to store any session related information.
 * @enum sessionInfo
 * @property {string} accessToken - Access token to authorize API requests.
 */
var sessionInfo = {
    "accessToken": ''
};
var parameters = {
    "valueInputOption": 'USER_ENTERED', /* 'USER_ENTERED', 'RAW', 'USER_ENTERED' */
    "insertDataOption": 'INSERT_ROWS', /* 'INSERT_ROWS', 'OVERWRITE' */
    "includeValuesInResponse": true, /* true, false */
    "responseValueRenderOption": 'FORMATTED_VALUE', /* 'FORMATTED_VALUE', 'UNFORMATTED_VALUE', 'FORMULA' */
    "responseDateTimeRenderOption": 'SERIAL_NUMBER' /* 'SERIAL_NUMBER', 'FORMATTED_STRING' */
};
var payload = {
    "range": 'A1:D',
    "values": [
        ['Hello', 'from', 'NEQTO', 'Device'],
    ]
};

// A mutex to limit the active HTTP requests.
var lock = false;

while (1) {
    if (!lock) { // wait for the lock to release
        lock = true; // lock
        if (sessionInfo.accessToken) {
            print("[info] send_sheets()");
            send_sheets(sessionInfo, parameters, payload, function (err, data) {
                callback(err, data);
                if (data.statusCode == 401) sessionInfo.accessToken = ''; // 401 - Unauthorized
                lock = false; // unlock
            });
            setTimeout(60000).wait(); // wait for 60 seconds
        }
        else {
            print("[info] getAccessToken()");
            getAccessToken(sessionInfo, 3600, function (err, data) {
                callback(err, data);
                lock = false; // unlock
            });
            setTimeout(10000).wait(); // wait for 10 seconds
        }
    }
};
The company names and product names mentioned above are registered trademarks or trademarks of their respective companies.

Updated: 2023-01-20
← DropboxInfluxDB →
  • Details
  • Function Usage Example
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.