首页 > 解决方案 > 如何在 React Native App 中使用 Node.js 代码

问题描述

我有一个 Node.js 代码,它连接到Azure's IoT Hub集线器并向集线器发送消息。这是代码:

'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);

我有一个带有按钮的 React Native 应用程序,我想在每次按下按钮时使用 Node.js 文件向 IoT 中心发送一条消息。如何在我的 React Native 文件中包含该文件?请帮忙,谢谢。

标签: node.jsazurereact-nativeazure-iot-hub

解决方案


我建议您查看Azure IoT Starter Kit Companion,它是一个示例React Native应用程序,可帮助您将IoT 设备连接到iOSAndroidWindows上的IoT Hub

希望能帮助到你!


推荐阅读