Skip to content

Instantly share code, notes, and snippets.

@DazWilkin
Created April 20, 2018 20:59
Show Gist options
  • Save DazWilkin/65ad8890d5f58eae9612632d594af2de to your computer and use it in GitHub Desktop.
Save DazWilkin/65ad8890d5f58eae9612632d594af2de to your computer and use it in GitHub Desktop.
Node.JS Cloud IoT Core sample
{
"projectID": "[[YOUR-PROJECT-ID]]",
"region": "[[YOUR-REGION]]",
"registryID": "[[YOUR-REGISTRY-ID",
"device": "[[YOUR-DEVICE-ID"
}
{
"name": "cloud-iot-nodejs",
"description": "Node.JS Sample for Cloud IoT Core",
"author": "Your Name <your@email.com>",
"version": "0.0.1",
"dependencies": {
"jsonwebtoken": "^8.2.1",
"mqtt": "^2.17.0"
}
}
/*globals require */
/*jshint esversion: 6 */
const mqtt = require("mqtt");
const fs = require("fs");
const jwt = require("jsonwebtoken");
// Google Cloud IoT Core specific configuration: projectID, region &c.
const c = require("./config.json");
const host = "mqtt.googleapis.com";
const port = 8883;
const clientID = `projects/${c.projectID}/locations/${c.region}/registries/${c.registryID}/devices/${c.device}`;
const roots = fs.readFileSync("./roots.pem"); // Replace with the location to your local https://pki.goog/roots.pem
const key = fs.readFileSync("./key.pem"); // Replace with the location to your private key file; generates JWT
const username = "unused";
const password = jwt.sign({
aud: c.projectID,
exp: Math.floor(Date.now()/1000 + 24*3600),
}, key, {
algorithm: "RS256"
});
const topics = {
pub: `/devices/${c.device}/events`,
sub: `/devices/${c.device}/config`
};
const options = {
host: host,
port: port,
clientId: clientID,
ca: roots,
username: username,
password: password,
rejectUnauthorized: false,
protocol: "ssl",
clean: false
};
const client = mqtt.connect(options);
client.on("connect",()=>{
console.log("[connect}");
});
client.on("message", (topic, message)=>{
console.log(`[message] ${topic}: ${message}`);
});
client.subscribe(topics.sub);
client.publish(topics.pub, `${new Date(Date.now()).toISOString()} Hello Henry!`);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment