-->

How to use Node.js code in React Native App

2019-08-31 14:19发布

问题:

I have a Node.js code that connects to Azure's IoT Huband sends messages to the hub. Here is the code:

'use strict';

var connectionString = 'connectionString';

// Using the Node.js Device SDK for IoT Hub:
//   https://github.com/Azure/azure-iot-sdk-node
// The sample connects to a device-specific MQTT endpoint on your IoT Hub.
var Mqtt = require('azure-iot-device-mqtt').Mqtt;
var DeviceClient = require('azure-iot-device').Client
var Message = require('azure-iot-device').Message;

var client = DeviceClient.fromConnectionString(connectionString, Mqtt);

// Create a message and send it to the IoT hub every second
setInterval(function(){
  // Simulate telemetry.
  var temperature = 20 + (Math.random() * 15);
  var message = new Message(JSON.stringify({
    temperature: temperature,
    humidity: 60 + (Math.random() * 20)
  }));

  // Add a custom application property to the message.
  // An IoT hub can filter on these properties without access to the message body.
  message.properties.add('temperatureAlert', (temperature > 30) ? 'true' : 'false');

  console.log('Sending message: ' + message.getData());

  // Send the message.
  client.sendEvent(message, function (err) {
    if (err) {
      console.error('send error: ' + err.toString());
    } else {
      console.log('message sent');
    }
  });
}, 1000);

I have a React Native app that has a button and I want to send a message using the Node.js file to the IoT Hub every time I press the button. How do I include the file within my React Native file? Please help, thanks.

回答1:

I would suggest you take a look at Azure IoT Starter Kit Companion, which is a sample React Native application that helps you get your IoT device connected to an IoT Hub on iOS, Android and Windows.

Hope it helps!