How to use Node.js code in React Native App

三世轮回 提交于 2019-12-11 17:31:28

问题


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!



来源:https://stackoverflow.com/questions/53907041/how-to-use-node-js-code-in-react-native-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!