Azure 函数:物联网中心 C2D 消息(入队承诺)太慢了

问题描述 投票:0回答:1

我正在使用 NodeJs Azure 函数通过 IoT 中心服务客户端发送云到设备 (C2D) 消息。这些消息随后由订阅主题过滤器设备/[设备名称]/消息/设备绑定/#

的 MQTT 客户端读取

下面是一些index.js代码。 hashedMessageArray 是一个非常简单的 JSON,带有一些散列字段,我尝试始终按照 Azure 最佳实践使用异步/等待模式。

// Libraries
const Client = require('azure-iothub').Client;
const Message = require('azure-iot-common').Message;

// Source and Target
const serviceClient = Client.fromConnectionString(process.env.SERVICE_IOT_HUB_CONNECTION_STRING);
const targetDevice = process.env.TARGET_DEVICE_ID;

// Open connection
await serviceClient.open();


// C2D Message
const message = new Message(JSON.stringify(hashedMessageArray));
message.ack = 'full';
message.messageId = Crypto.randomBytes(16).toString('hex');

// Send
context.log('Sending message: ' + message.getData());
await serviceClient.send(targetDevice, message);
context.log('Sent message: ' + message.getData());

在两次 context.log() 调用之间,平均有 14 秒的延迟:这是等待的承诺在确认消息入队之前所需的时间。

如何实现近乎实时的通信?可以做些什么?

node.js azure-functions azure-iot-hub
1个回答
0
投票

延迟是由于 IoT 中心服务将消息排队并将其发送到设备所花费的时间。

您可以通过以下步骤对其进行优化:

使用 IoT 中心服务客户端的单例实例来避免为每个函数调用创建新客户端的开销。

使用

sendBatch method
在一次调用中发送多条消息,以减少到 IoT 中心服务的往返次数。

使用

sendEventBatch method
在一次调用中将多条消息发送到多个设备,以进一步减少往返次数。

使用

sendEvent method
异步发送消息,无需等待 IoT 中心服务的响应。

而且,通过使用不同的协议,例如

AMQP
有助于提高
IoT Hub communication
的性能。

能够毫不延迟地向物联网设备发送消息。

Node JS
中的代码以从设备接收消息。

const  client = Client.fromConnectionString(connString, Mqtt);
client.open((err) => {if (err) {
console.error('Error while connecting IoT Hub:', err);
} 
else 
{
console.log('Connection opened');
deviceclient.on('message', (msg) => {
console.log('Received message from device:', msg.getData().toString())
;});}});

enter image description here

Node JS
中的代码,用于向设备发送消息。

const client = Client.fromConnectionString(connString, Mqtt);  
client.open((err) => {  
if (err) {  
console.error('Error while openining IoT Hub :', err);  
} else {  
console.log('IoT Hub connection opened');  

const message = new Message(JSON.stringify({  
data: 'Hello from the cloud!'  
}));  
console.log('Sending message:', message.getData());  
client.sendEvent(message, (err, res) => {  
if (err) 
{  
console.error('Error sending message:', err);  
} 
else 
{  
console.log('Message sent to IoT device with status:', res.constructor.name);  
}  
client.close(); }); }});

enter image description here

有关更多信息,请参阅 MSDoc.

© www.soinside.com 2019 - 2024. All rights reserved.