How to send a C2D Direct method from the Node.js SDK to a remote device?

Florian Cartier 0 Reputation points
2023-06-06T04:55:02.21+00:00

Hello folks

I am trying to connect my local Node.js API to Azure IOT Hub and send direct methods to a remote device.

When sending the direct method directly through the Azure portal, it works like a charm. However, when attempting to do the same through the API, I get a "Timed out waiting for the response from device" message.

Here is the code I tried so far:

"use strict";

exports.sendDirectMethod = async (req, res) => {    
	const connectionString = process.env.IOTHUB_CONNECTION_STRING;    
	const deviceId = "HW2";
	const serviceClient = iothub.Client.fromConnectionString(connectionString);
	const payload = {        
		methodName: "GetAllLockerStatus_method",
		responseTimeoutInSeconds: 30,
		payload: JSON.stringify({ MessageID: 1,}),
	};
	serviceClient.invokeDeviceMethod(deviceId, payload, (err, result) => {
		if (err) {
			console.error(err.message);
		} else {
			console.log(`Response status: ${result.status}`);
			console.log(`Response payload: ${result.payload}`);
		}
	});
};

Any ideas are welcome, as I am quite stuck at the moment. Thanks!

Azure IoT Hub
Azure IoT Hub
An Azure service that enables bidirectional communication between internet of things (IoT) devices and applications.
1,272 questions
{count} votes

1 answer

Sort by: Most helpful
  1. LeelaRajeshSayana-MSFT 17,766 Reputation points Moderator
    2023-06-06T14:46:04.2033333+00:00

    Hi @Florian Cartier Greetings! Welcome to Microsoft Q&A forum. Thank you for posting the question here.

    Here is a code that I have tested and could successfully invoke the direct method on a device from Node.js code

    'use strict';
    
    const connectionString = '<Connection string>';
    const serviceClient = iothub.Client.fromConnectionString(connectionString);
    const methodName = 'reboot';
    const payload = {    input1: 'someInput',    input2: 'anotherInput'};
    serviceClient.invokeDeviceMethod('TestDevice4', { methodName, payload }, (err, result) => {    
       if (err) {        
           console.error('Failed to invoke method: ' + err.message);    
       } else {        
           console.log('Method response:');        
           console.log(JSON.stringify(result, null, 2));    
       }
    });
    
    

    I have used the Service policy connection string of IoT Hub in this code and here is the output I get from the code as I execute it.

    enter image description here

    Hope this helps. Please let us know if you have any additional questions or need further assistance.


    If the response helped, please do click Accept Answer and Yes for the answer provided. Doing so would help other community members with similar issue identify the solution. I highly appreciate your contribution to the community.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.