0

Working with Azure Functions, I want to send a C2D message to IoT Hub, and manage feedback message. How could implement async pattern to manage feedback StatusCode message and log it?

const IotHubClient = require("azure-iothub").Client;
const MessageC2D = require("azure-iot-common").Message;
const connectionString = process.env.IOTHUB_CONNECTION_STRING
const serviceClientIotHub = IotHubClient.fromConnectionString(connectionString);


module.exports = async(context, IoTHubMessages) => {
 for (const message of IoTHubMessages) {
 if(message.temp > 50){
   const messagec2d = new MessageC2D(`{"state": "off"}`);
   messagec2d.ack = 'full';
   messagec2d.messageId = 'id001';

   serviceClientIotHub.getFeedbackReceiver(context,receiveFeedback);
   serviceClientIotHub.send(message.targetDevice, messagec2d, printResultFor(context, 'send'));
 }
}

function receiveFeedback (context, err, receiver){
    try {
        receiver.on('message', (context, msg) => {
            context.log('Feedback message:');
            context.log(msg.getData().toString('utf-8'));
            return msg;
        });
    } catch (e) { //UnhandledPromiseRejectionWarning: Unhandled promise rejection
        context.log(e.message);
        context.log.error('ERROR', e);
        throw e;
    }
};

function printResultFor(context, op) {
    return function printResult(err, res) {
        if (err) context.log(op + ' error: ' + err.toString());
        if (res) context.log(op + ' status: ' + res.constructor.name);
    };
}

Warning from local debugging:

Warning: Unexpected call to 'log' on the context object after function execution has completed. Please check for asynchronous calls that are not awaited or calls to 'done' made before function execution completes. Function name: ic_IoTHub_EventHub. Invocation Id: 824b849f-6be3-4de1-a175-bb82280ef4e1. Learn more: https://go.microsoft.com/fwlink/?linkid=2097909 
smontoya
  • 91
  • 10
  • Have you referred to Node.js sample [Send a cloud-to-device message](https://learn.microsoft.com/en-us/azure/iot-hub/iot-hub-node-node-c2d#send-a-cloud-to-device-message). Are you referring to Azure Function App or a general function in node.js ? – SatishBoddu Jun 25 '20 at 01:16
  • I am referring to Azure Function App, working with javascript and node.js. I already checked your link, It is in what I am based off. But I dont know how correctly implement async pattern to manage receiveFeedback... – smontoya Jun 25 '20 at 11:01
  • See related thread that may help: https://stackoverflow.com/questions/48339829/async-programming-and-azure-functions – asergaz Jun 26 '20 at 18:12
  • @smontoya, Please let us know if you need further help in this matter. – SatishBoddu Jul 02 '20 at 16:39

0 Answers0