1

I am fairly new to React Native, but I created a simple app that has a button and a text that changes when the button is clicked. However, I want to connect to the IoT hub and receive information from the hub.

I am having issues currently with the connection. Here is my code:

import React from 'react';
import {StyleSheet, Dimensions, Alert, Text, View, Image, Button} from 'react-native';
const { width, height } = Dimensions.get("window");

    'use strict';
var iothub = require('azure-iothub');
var connectionString = 'connection string';
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);

The above part is a Node.js code, but I want to use it in a React application. How do I use Node packages in React?

I am getting the following error: Could not connect to development server.

Thanks.

Ruby
  • 413
  • 1
  • 4
  • 16

3 Answers3

1

As in your other question, 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!

Itay Podhajcer
  • 2,616
  • 2
  • 9
  • 14
1

Small point, you should NOT publish your connection strings. This is a rather large security issue.

0

As mentioned in your other question, the Azure IoT Hub Device SDK needs a Node.js runtime, which does not exists within the React Native app.

There is a plugin called nodejs-mobile-react-native for React Native that brings in the Node.js runtime and enables you to run Node.js apps alongside your React Native application.

I have written a detailed blog post about this topic outlining the steps necessary to achieve this.

Ben
  • 21
  • 4