Node.js SDK 使用指南
在本节中,我们将详细介绍如何使用 Google Cloud IoT Node.js SDK 进行二次开发。Google Cloud IoT 提供了丰富的 API 和 SDK,使得开发者可以轻松地与 IoT 设备进行交互,实现设备管理、数据传输、消息处理等功能。Node.js SDK 是其中一种常用的开发工具,特别适合于构建事件驱动的 IoT 应用程序。
安装 Node.js SDK
在开始使用 Google Cloud IoT Node.js SDK 之前,首先需要安装 Node.js 和 npm(Node.js 包管理器)。你可以从 Node.js 官方网站 下载并安装最新版本的 Node.js。
安装完成后,打开终端或命令行工具,创建一个新的项目目录,并初始化 Node.js 项目:
mkdir iot-project
cd iot-project
npm init -y
接下来,安装 Google Cloud IoT Node.js SDK:
npm install @google-cloud/iot
配置 Google Cloud 项目
在使用 Google Cloud IoT SDK 之前,需要确保你的 Google Cloud 项目已经配置好,并且具有必要的权限。以下是配置步骤:
-
创建 Google Cloud 项目:
-
创建一个新的项目或选择一个现有项目。
-
启用 Google Cloud IoT API:
-
在 Google Cloud Console 中,导航到“API 和服务” > “库”。
-
搜索“Cloud IoT API”并启用它。
-
-
创建服务账户并下载密钥文件:
-
导航到“IAM 和管理” > “服务账户”。
-
创建一个新的服务账户,并为其分配“Cloud IoT Admin”角色。
-
生成一个 JSON 密钥文件并下载。
-
-
设置环境变量:
- 在终端中设置
GOOGLE_APPLICATION_CREDENTIALS
环境变量,指向你下载的 JSON 密钥文件。
export GOOGLE_APPLICATION_CREDENTIALS="path/to/your/credentials.json"
- 在终端中设置
连接设备
Google Cloud IoT 允许开发者通过 MQTT 或 HTTP 协议连接设备。在本节中,我们将介绍如何使用 Node.js SDK 通过 MQTT 协议连接设备。
创建设备注册
在 Google Cloud IoT 中,设备必须注册到一个设备注册表中。设备注册表可以包含多个设备,并且可以配置设备的连接和通信方式。
首先,安装 mqtt
模块:
npm install mqtt
然后,编写代码创建设备注册表:
const {IotClient} = require('@google-cloud/iot');
const projectId = 'your-project-id';
const cloudRegion = 'your-cloud-region';
const registryId = 'your-registry-id';
const iotClient = new IotClient();
async function createRegistry() {
const parent = `projects/${projectId}/locations/${cloudRegion}`;
const registry = {
id: registryId,
name: `${parent}/registries/${registryId}`,
eventNotificationConfigs: [
{
pubsubTopicName: `projects/${projectId}/topics/your-topic`,
subfolderMatches: 'your-subfolder',
},
],
};
const [response] = await iotClient.createDeviceRegistry({parent, deviceRegistry: registry});
console.log(`Registry ${registryId} created: ${response.name}`);
}
createRegistry().catch(console.error);
注册设备
创建设备注册表后,需要注册设备。每个设备都有一个唯一的 ID,并且可以配置其连接方式和凭证。
const {IotClient} = require('@google-cloud/iot');
const {MqttClient} = require('mqtt');
const projectId = 'your-project-id';
const cloudRegion = 'your-cloud-region';
const registryId = 'your-registry-id';
const deviceId = 'your-device-id';
const privateKeyFile = 'path/to/your/private-key.pem';
const algorithm = 'RS256';
const cloudIoTCoreMqttBridge = 'mqtt.googleapis.com';
const mqttBridgePort = 8883;
const iotClient = new IotClient();
async function registerDevice() {
const parent = `projects/${projectId}/locations/${cloudRegion}/registries/${registryId}`;
const device = {
id: deviceId,
credentials: [
{
publicKey: {
format: 'RSA_X509_PEM',
key: fs.readFileSync(privateKeyFile, 'utf8'),
},
expirationTime: '2023-12-31T23:59:59Z',
},
],
};
const [response] = await iotClient.createDevice({parent, device});
console.log(`Device ${deviceId} registered: ${response.name}`);
}
registerDevice().catch(console.error);
连接设备
使用 MQTT 协议连接设备时,需要配置 MQTT 客户端并进行身份验证。以下是一个示例代码,展示了如何连接设备并发送数据:
const {IotClient} = require('@google-cloud/iot');
const {MqttClient} = require('mqtt');
const fs = require('fs');
const path = require('path');
const projectId = 'your-project-id';
const cloudRegion = 'your-cloud-region';
const registryId = 'your-registry-id';
const deviceId = 'your-device-id';
const privateKeyFile = 'path/to/your/private-key.pem';
const algorithm = 'RS256';
const cloudIoTCoreMqttBridge = 'mqtt.googleapis.com';
const mqttBridgePort = 8883;
const iotClient = new IotClient();
async function getConnectionString() {
const devicePath = iotClient.devicePath(projectId, cloudRegion, registryId, deviceId);
const [device] = await iotClient.getDevice({name: devicePath});
const jwtClientEmail = device.credentials[0].publicKey.key;
const jwtPrivateKey = fs.readFileSync(privateKeyFile, 'utf8');
const client = new MqttClient(`mqtts://${cloudIoTCoreMqttBridge}:${mqttBridgePort}`, {
clientId: `projects/${projectId}/locations/${cloudRegion}/registries/${registryId}/devices/${deviceId}`,
username: 'unused',
password: createJwt(projectId, cloudRegion, registryId, deviceId, jwtClientEmail, jwtPrivateKey, algorithm),
protocol: 'mqtts',
});
return client;
}
function createJwt(projectId, cloudRegion, registryId, deviceId, jwtClientEmail, jwtPrivateKey, algorithm) {
const token = {
iat: Math.floor(Date.now() / 1000),
exp: Math.floor(Date.now() / 1000) + (20 * 60), // 20 minutes
aud: projectId,
};
const encodedToken = Buffer.from(JSON.stringify(token)).toString('base64');
const sign = crypto.createSign('RSA-SHA256');
sign.write(encodedToken);
sign.end();
const signature = sign.sign(jwtPrivateKey, 'base64');
return `${encodedToken}.${signature}`;
}
async function connectDevice() {
const client = await getConnectionString();
client.on('connect', () => {
console.log('Device connected to Google Cloud IoT Core');
client.publish(`projects/${projectId}/locations/${cloudRegion}/registries/${registryId}/devices/${deviceId}/events`, 'Hello, Cloud IoT Core!');
});
client.on('error', (error) => {
console.error('Error connecting to Google Cloud IoT Core:', error);
});
client.connect();
}
connectDevice().catch(console.error);
发送和接收数据
发送数据
连接设备后,可以通过 MQTT 协议发送数据到 Google Cloud IoT Core。以下是一个示例代码,展示了如何发送温度传感器数据:
const {IotClient} = require('@google-cloud/iot');
const {MqttClient} = require('mqtt');
const fs = require('fs');
const crypto = require('crypto');
const projectId = 'your-project-id';
const cloudRegion = 'your-cloud-region';
const registryId = 'your-registry-id';
const deviceId = 'your-device-id';
const privateKeyFile = 'path/to/your/private-key.pem';
const algorithm = 'RS256';
const cloudIoTCoreMqttBridge = 'mqtt.googleapis.com';
const mqttBridgePort = 8883;
const iotClient = new IotClient();
async function getConnectionString() {
const devicePath = iotClient.devicePath(projectId, cloudRegion, registryId, deviceId);
const [device] = await iotClient.getDevice({name: devicePath});
const jwtClientEmail = device.credentials[0].publicKey.key;
const jwtPrivateKey = fs.readFileSync(privateKeyFile, 'utf8');
const client = new MqttClient(`mqtts://${cloudIoTCoreMqttBridge}:${mqttBridgePort}`, {
clientId: `projects/${projectId}/locations/${cloudRegion}/registries/${registryId}/devices/${deviceId}`,
username: 'unused',
password: createJwt(projectId, cloudRegion, registryId, deviceId, jwtClientEmail, jwtPrivateKey, algorithm),
protocol: 'mqtts',
});
return client;
}
function createJwt(projectId, cloudRegion, registryId, deviceId, jwtClientEmail, jwtPrivateKey, algorithm) {
const token = {
iat: Math.floor(Date.now() / 1000),
exp: Math.floor(Date.now() / 1000) + (20 * 60), // 20 minutes
aud: projectId,
};
const encodedToken = Buffer.from(JSON.stringify(token)).toString('base64');
const sign = crypto.createSign('RSA-SHA256');
sign.write(encodedToken);
sign.end();
const signature = sign.sign(jwtPrivateKey, 'base64');
return `${encodedToken}.${signature}`;
}
async function sendData() {
const client = await getConnectionString();
client.on('connect', () => {
console.log('Device connected to Google Cloud IoT Core');
const temperature = 25.0;
const payload = JSON.stringify({temperature});
const topic = `projects/${projectId}/locations/${cloudRegion}/registries/${registryId}/devices/${deviceId}/events`;
client.publish(topic, payload, {qos: 1}, (error) => {
if (error) {
console.error('Error publishing data:', error);
} else {
console.log('Data sent to Google Cloud IoT Core:', payload);
}
});
});
client.on('error', (error) => {
console.error('Error connecting to Google Cloud IoT Core:', error);
});
client.connect();
}
sendData().catch(console.error);
接收数据
设备不仅可以发送数据,还可以接收来自 Google Cloud IoT Core 的命令和配置。以下是一个示例代码,展示了如何接收命令:
const {IotClient} = require('@google-cloud/iot');
const {MqttClient} = require('mqtt');
const fs = require('fs');
const crypto = require('crypto');
const projectId = 'your-project-id';
const cloudRegion = 'your-cloud-region';
const registryId = 'your-registry-id';
const deviceId = 'your-device-id';
const privateKeyFile = 'path/to/your/private-key.pem';
const algorithm = 'RS256';
const cloudIoTCoreMqttBridge = 'mqtt.googleapis.com';
const mqttBridgePort = 8883;
const iotClient = new IotClient();
async function getConnectionString() {
const devicePath = iotClient.devicePath(projectId, cloudRegion, registryId, deviceId);
const [device] = await iotClient.getDevice({name: devicePath});
const jwtClientEmail = device.credentials[0].publicKey.key;
const jwtPrivateKey = fs.readFileSync(privateKeyFile, 'utf8');
const client = new MqttClient(`mqtts://${cloudIoTCoreMqttBridge}:${mqttBridgePort}`, {
clientId: `projects/${projectId}/locations/${cloudRegion}/registries/${registryId}/devices/${deviceId}`,
username: 'unused',
password: createJwt(projectId, cloudRegion, registryId, deviceId, jwtClientEmail, jwtPrivateKey, algorithm),
protocol: 'mqtts',
});
return client;
}
function createJwt(projectId, cloudRegion, registryId, deviceId, jwtClientEmail, jwtPrivateKey, algorithm) {
const token = {
iat: Math.floor(Date.now() / 1000),
exp: Math.floor(Date.now() / 1000) + (20 * 60), // 20 minutes
aud: projectId,
};
const encodedToken = Buffer.from(JSON.stringify(token)).toString('base64');
const sign = crypto.createSign('RSA-SHA256');
sign.write(encodedToken);
sign.end();
const signature = sign.sign(jwtPrivateKey, 'base64');
return `${encodedToken}.${signature}`;
}
async function receiveCommands() {
const client = await getConnectionString();
const topic = `projects/${projectId}/locations/${cloudRegion}/registries/${registryId}/devices/${deviceId}/commands/#`;
client.on('connect', () => {
console.log('Device connected to Google Cloud IoT Core');
client.subscribe(topic, (error) => {
if (error) {
console.error('Error subscribing to commands:', error);
} else {
console.log('Subscribed to commands');
}
});
});
client.on('message', (topic, message) => {
console.log('Received command:', topic, message.toString());
});
client.on('error', (error) => {
console.error('Error connecting to Google Cloud IoT Core:', error);
});
client.connect();
}
receiveCommands().catch(console.error);
设备管理
获取设备信息
使用 Google Cloud IoT Node.js SDK,可以轻松获取设备的详细信息。以下是一个示例代码,展示了如何获取设备信息:
const {IotClient} = require('@google-cloud/iot');
const projectId = 'your-project-id';
const cloudRegion = 'your-cloud-region';
const registryId = 'your-registry-id';
const deviceId = 'your-device-id';
const iotClient = new IotClient();
async function getDevice() {
const name = iotClient.devicePath(projectId, cloudRegion, registryId, deviceId);
const [device] = await iotClient.getDevice({name});
console.log('Device information:', device);
}
getDevice().catch(console.error);
更新设备配置
设备配置可以通过 Google Cloud IoT Core 进行更新。以下是一个示例代码,展示了如何更新设备配置:
const {IotClient} = require('@google-cloud/iot');
const projectId = 'your-project-id';
const cloudRegion = 'your-cloud-region';
const registryId = 'your-registry-id';
const deviceId = 'your-device-id';
const iotClient = new IotClient();
async function updateDeviceConfig() {
const name = iotClient.devicePath(projectId, cloudRegion, registryId, deviceId);
const config = {
data: Buffer.from('{"newConfig": "value"}'),
versionToUpdate: 0, // Set to 0 to update to the latest version
};
const [response] = await iotClient.modifyCloudToDeviceConfig({name, binaryData: config.data, versionToUpdate: config.versionToUpdate});
console.log('Device configuration updated:', response);
}
updateDeviceConfig().catch(console.error);
删除设备
如果需要删除设备,可以使用以下代码:
const {IotClient} = require('@google-cloud/iot');
const projectId = 'your-project-id';
const cloudRegion = 'your-cloud-region';
const registryId = 'your-registry-id';
const deviceId = 'your-device-id';
const iotClient = new IotClient();
async function deleteDevice() {
const name = iotClient.devicePath(projectId, cloudRegion, registryId, deviceId);
await iotClient.deleteDevice({name});
console.log('Device deleted:', deviceId);
}
deleteDevice().catch(console.error);
错误处理
在开发过程中,错误处理是非常重要的。Google Cloud IoT Node.js SDK 提供了多种方法来处理错误。以下是一些常见的错误处理示例:
处理设备连接错误
在连接设备时,可能会遇到各种错误,如网络问题、认证失败等。可以使用 error
事件来捕获这些错误:
const {IotClient} = require('@google-cloud/iot');
const {MqttClient} = require('mqtt');
const fs = require('fs');
const crypto = require('crypto');
const projectId = 'your-project-id';
const cloudRegion = 'your-cloud-region';
const registryId = 'your-registry-id';
const deviceId = 'your-device-id';
const privateKeyFile = 'path/to/your/private-key.pem';
const algorithm = 'RS256';
const cloudIoTCoreMqttBridge = 'mqtt.googleapis.com';
const mqttBridgePort = 8883;
const iotClient = new IotClient();
async function getConnectionString() {
const devicePath = iotClient.devicePath(projectId, cloudRegion, registryId, deviceId);
const [device] = await iotClient.getDevice({name: devicePath});
const jwtClientEmail = device.credentials[0].publicKey.key;
const jwtPrivateKey = fs.readFileSync(privateKeyFile, 'utf8');
const client = new MqttClient(`mqtts://${cloudIoTCoreMqttBridge}:${mqttBridgePort}`, {
clientId: `projects/${projectId}/locations/${cloudRegion}/registries/${registryId}/devices/${deviceId}`,
username: 'unused',
password: createJwt(projectId, cloudRegion, registryId, deviceId, jwtClientEmail, jwtPrivateKey, algorithm),
protocol: 'mqtts',
});
return client;
}
function createJwt(projectId, cloudRegion, registryId, deviceId, jwtClientEmail, jwtPrivateKey, algorithm) {
const token = {
iat: Math.floor(Date.now() / 1000),
exp: Math.floor(Date.now() / 1000) + (20 * 60), // 20 minutes
aud: projectId,
};
const encodedToken = Buffer.from(JSON.stringify(token)).toString('base64');
const sign = crypto.createSign('RSA-SHA256');
sign.write(encodedToken);
sign.end();
const signature = sign.sign(jwtPrivateKey, 'base64');
return `${encodedToken}.${signature}`;
}
async function connectDevice() {
const client = await getConnectionString();
client.on('connect', () => {
console.log('Device connected to Google Cloud IoT Core');
});
client.on('error', (error) => {
console.error('Error connecting to Google Cloud IoT Core:', error);
});
client.connect();
}
connectDevice().catch(console.error);
处理设备操作错误
在进行### 处理设备操作错误
在进行设备操作时,可能会遇到各种错误,如设备不存在、权限不足、网络问题等。可以使用 try-catch
语句来捕获这些错误,并进行相应的处理。以下是一些常见的设备操作错误处理示例:
获取设备信息时的错误处理
const {IotClient} = require('@google-cloud/iot');
const projectId = 'your-project-id';
const cloudRegion = 'your-cloud-region';
const registryId = 'your-registry-id';
const deviceId = 'your-device-id';
const iotClient = new IotClient();
async function getDevice() {
try {
const name = iotClient.devicePath(projectId, cloudRegion, registryId, deviceId);
const [device] = await iotClient.getDevice({name});
console.log('Device information:', device);
} catch (error) {
console.error('Error getting device information:', error);
}
}
getDevice().catch(console.error);
更新设备配置时的错误处理
const {IotClient} = require('@google-cloud/iot');
const projectId = 'your-project-id';
const cloudRegion = 'your-cloud-region';
const registryId = 'your-registry-id';
const deviceId = 'your-device-id';
const iotClient = new IotClient();
async function updateDeviceConfig() {
try {
const name = iotClient.devicePath(projectId, cloudRegion, registryId, deviceId);
const config = {
data: Buffer.from('{"newConfig": "value"}'),
versionToUpdate: 0, // Set to 0 to update to the latest version
};
const [response] = await iotClient.modifyCloudToDeviceConfig({name, binaryData: config.data, versionToUpdate: config.versionToUpdate});
console.log('Device configuration updated:', response);
} catch (error) {
console.error('Error updating device configuration:', error);
}
}
updateDeviceConfig().catch(console.error);
删除设备时的错误处理
const {IotClient} = require('@google-cloud/iot');
const projectId = 'your-project-id';
const cloudRegion = 'your-cloud-region';
const registryId = 'your-registry-id';
const deviceId = 'your-device-id';
const iotClient = new IotClient();
async function deleteDevice() {
try {
const name = iotClient.devicePath(projectId, cloudRegion, registryId, deviceId);
await iotClient.deleteDevice({name});
console.log('Device deleted:', deviceId);
} catch (error) {
console.error('Error deleting device:', error);
}
}
deleteDevice().catch(console.error);
日志记录
在开发过程中,日志记录是非常重要的,可以帮助你调试和监控应用程序的运行情况。可以使用 winston
这样的日志库来记录日志。
首先,安装 winston
:
npm install winston
然后,编写代码进行日志记录:
const {IotClient} = require('@google-cloud/iot');
const {MqttClient} = require('mqtt');
const fs = require('fs');
const crypto = require('crypto');
const winston = require('winston');
const projectId = 'your-project-id';
const cloudRegion = 'your-cloud-region';
const registryId = 'your-registry-id';
const deviceId = 'your-device-id';
const privateKeyFile = 'path/to/your/private-key.pem';
const algorithm = 'RS256';
const cloudIoTCoreMqttBridge = 'mqtt.googleapis.com';
const mqttBridgePort = 8883;
const iotClient = new IotClient();
// 创建日志记录器
const logger = winston.createLogger({
level: 'info',
format: winston.format.json(),
transports: [
new winston.transports.Console(),
new winston.transports.File({ filename: 'iot.log' }),
],
});
async function getConnectionString() {
const devicePath = iotClient.devicePath(projectId, cloudRegion, registryId, deviceId);
const [device] = await iotClient.getDevice({name: devicePath});
const jwtClientEmail = device.credentials[0].publicKey.key;
const jwtPrivateKey = fs.readFileSync(privateKeyFile, 'utf8');
const client = new MqttClient(`mqtts://${cloudIoTCoreMqttBridge}:${mqttBridgePort}`, {
clientId: `projects/${projectId}/locations/${cloudRegion}/registries/${registryId}/devices/${deviceId}`,
username: 'unused',
password: createJwt(projectId, cloudRegion, registryId, deviceId, jwtClientEmail, jwtPrivateKey, algorithm),
protocol: 'mqtts',
});
return client;
}
function createJwt(projectId, cloudRegion, registryId, deviceId, jwtClientEmail, jwtPrivateKey, algorithm) {
const token = {
iat: Math.floor(Date.now() / 1000),
exp: Math.floor(Date.now() / 1000) + (20 * 60), // 20 minutes
aud: projectId,
};
const encodedToken = Buffer.from(JSON.stringify(token)).toString('base64');
const sign = crypto.createSign('RSA-SHA256');
sign.write(encodedToken);
sign.end();
const signature = sign.sign(jwtPrivateKey, 'base64');
return `${encodedToken}.${signature}`;
}
async function connectDevice() {
try {
const client = await getConnectionString();
client.on('connect', () => {
logger.info('Device connected to Google Cloud IoT Core');
});
client.on('error', (error) => {
logger.error('Error connecting to Google Cloud IoT Core:', error);
});
client.connect();
} catch (error) {
logger.error('Error getting connection string:', error);
}
}
connectDevice().catch(console.error);
async function sendData() {
try {
const client = await getConnectionString();
client.on('connect', () => {
logger.info('Device connected to Google Cloud IoT Core');
const temperature = 25.0;
const payload = JSON.stringify({temperature});
const topic = `projects/${projectId}/locations/${cloudRegion}/registries/${registryId}/devices/${deviceId}/events`;
client.publish(topic, payload, {qos: 1}, (error) => {
if (error) {
logger.error('Error publishing data:', error);
} else {
logger.info('Data sent to Google Cloud IoT Core:', payload);
}
});
});
client.on('error', (error) => {
logger.error('Error connecting to Google Cloud IoT Core:', error);
});
client.connect();
} catch (error) {
logger.error('Error getting connection string:', error);
}
}
sendData().catch(console.error);
async function receiveCommands() {
try {
const client = await getConnectionString();
const topic = `projects/${projectId}/locations/${cloudRegion}/registries/${registryId}/devices/${deviceId}/commands/#`;
client.on('connect', () => {
logger.info('Device connected to Google Cloud IoT Core');
client.subscribe(topic, (error) => {
if (error) {
logger.error('Error subscribing to commands:', error);
} else {
logger.info('Subscribed to commands');
}
});
});
client.on('message', (topic, message) => {
logger.info('Received command:', topic, message.toString());
});
client.on('error', (error) => {
logger.error('Error connecting to Google Cloud IoT Core:', error);
});
client.connect();
} catch (error) {
logger.error('Error getting connection string:', error);
}
}
receiveCommands().catch(console.error);
async function getDevice() {
try {
const name = iotClient.devicePath(projectId, cloudRegion, registryId, deviceId);
const [device] = await iotClient.getDevice({name});
logger.info('Device information:', device);
} catch (error) {
logger.error('Error getting device information:', error);
}
}
getDevice().catch(console.error);
async function updateDeviceConfig() {
try {
const name = iotClient.devicePath(projectId, cloudRegion, registryId, deviceId);
const config = {
data: Buffer.from('{"newConfig": "value"}'),
versionToUpdate: 0, // Set to 0 to update to the latest version
};
const [response] = await iotClient.modifyCloudToDeviceConfig({name, binaryData: config.data, versionToUpdate: config.versionToUpdate});
logger.info('Device configuration updated:', response);
} catch (error) {
logger.error('Error updating device configuration:', error);
}
}
updateDeviceConfig().catch(console.error);
async function deleteDevice() {
try {
const name = iotClient.devicePath(projectId, cloudRegion, registryId, deviceId);
await iotClient.deleteDevice({name});
logger.info('Device deleted:', deviceId);
} catch (error) {
logger.error('Error deleting device:', error);
}
}
deleteDevice().catch(console.error);
总结
通过本指南,你已经了解了如何使用 Google Cloud IoT Node.js SDK 进行设备的注册、连接、数据发送和接收,以及设备管理。错误处理和日志记录是确保应用程序稳定运行的重要部分,希望这些示例能帮助你更好地开发和调试你的 IoT 应用程序。
如果你有任何问题或需要进一步的帮助,可以参考 Google Cloud IoT 官方文档 或访问 Google Cloud Support。
标签:Node,const,projectId,IoT,registryId,deviceId,error,二次开发,your From: https://blog.csdn.net/chenlz2007/article/details/143027064