【问题标题】:How to use Node.js code in React Native App如何在 React Native App 中使用 Node.js 代码
【发布时间】:2018-12-23 20:46:14
【问题描述】:

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

'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.js azure react-native azure-iot-hub


    【解决方案1】:

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

    希望对你有帮助!

    【讨论】:

      【解决方案2】:

      Azure IoT Hub 设备 SDK 需要 Node.js 运行时,React Native 应用程序中不存在该运行时。

      有一个名为 nodejs-mobile-react-native 的 React Native 插件,它引入了 Node.js 运行时,使您能够在 React Native 应用程序旁边运行 Node.js 应用程序。

      我已经写了一封关于这个主题的detailed blog post,概述了实现这一目标的必要步骤。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-11-18
        • 2019-07-28
        • 1970-01-01
        • 1970-01-01
        • 2019-08-09
        • 1970-01-01
        • 2022-08-09
        • 1970-01-01
        相关资源
        最近更新 更多