Created
April 20, 2018 20:59
-
-
Save DazWilkin/65ad8890d5f58eae9612632d594af2de to your computer and use it in GitHub Desktop.
Node.JS Cloud IoT Core sample
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"projectID": "[[YOUR-PROJECT-ID]]", | |
"region": "[[YOUR-REGION]]", | |
"registryID": "[[YOUR-REGISTRY-ID", | |
"device": "[[YOUR-DEVICE-ID" | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"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" | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/*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