Skip to content

Instantly share code, notes, and snippets.

@mvisintin
Last active March 22, 2022 12:44
Show Gist options
  • Save mvisintin/a95eefa53fa5814dff5846d0f6c47be9 to your computer and use it in GitHub Desktop.
Save mvisintin/a95eefa53fa5814dff5846d0f6c47be9 to your computer and use it in GitHub Desktop.
state-subscription-example
process.env.GOOGLE_APPLICATION_CREDENTIALS = 'gCloudAuth.json';
const fs = require('fs');
const path = require('path');
const jwt = require('jsonwebtoken');
const mqtt = require('mqtt');
const { PubSub } = require('@google-cloud/pubsub');
const pubSubClient = new PubSub();
const createJwt = (projectId, privateKeyFile) => {
const token = {
iat: parseInt(Date.now() / 1000),
exp: parseInt(Date.now() / 1000) + 20 * 60,
aud: projectId,
};
const privateKey = fs.readFileSync(privateKeyFile);
return jwt.sign(token, privateKey, { algorithm: 'RS256' });
};
const projectId = 'portal-dev-340714';
const region = 'europe-west1';
const registryId = 'tests';
const deviceId = 'test1';
const rootsCertsFile = path.join(__dirname, 'resources', 'roots.pem');
const privateKeyFile = path.join(__dirname, 'resources', 'private.pem');
const mqttClientId = `projects/${projectId}/locations/${region}/registries/${registryId}/devices/${deviceId}`;
function listenForMessages() {
const subscription = pubSubClient.subscription('tests-state');
const messageHandler = (message) => {
const payload = JSON.parse(message.data.toString());
console.log(message.attributes);
console.log(payload);
message.ack();
};
subscription.on('message', messageHandler);
}
const connectDevice = () => {
const connectionArgs = {
host: 'mqtt.googleapis.com',
port: '8883',
clientId: mqttClientId,
username: 'unused',
password: createJwt(projectId, privateKeyFile),
protocol: 'mqtts',
secureProtocol: 'TLSv1_2_method',
ca: [fs.readFileSync(rootsCertsFile)],
};
const client = mqtt.connect(connectionArgs);
return client;
};
listenForMessages();
const iotClient = connectDevice();
iotClient.on('connect', (success) => {
console.log('connect');
if (!success) {
console.log('Client not connected...');
} else {
console.log('connected');
iotClient.publish('/devices/test1/state', JSON.stringify({ a: 1 }), (err) =>
console.log(err),
);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment