将 Raspberry Pi 连接到 Azure IoT 中心 (Node.js)Connect Raspberry Pi to Azure IoT Hub (Node.js)

在本教程中,首先学习有关使用运行 Raspbian 的 Raspberry Pi 的基础知识。In this tutorial, you begin by learning the basics of working with Raspberry Pi that's running Raspbian. 然后学习如何使用 Azure IoT 中心将设备无缝连接到云。You then learn how to seamlessly connect your devices to the cloud by using Azure IoT Hub. 有关 Windows 10 IoT Core 的示例,请访问 Windows 开发人员中心For Windows 10 IoT Core samples, go to the Windows Dev Center.

还没有工具包?Don't have a kit yet? 试用 Raspberry Pi 联机模拟器Try Raspberry Pi online simulator. 或在此处购买新工具包。Or buy a new kit here.

准备工作What you do

  • 创建 IoT 中心。Create an IoT hub.
  • 在 IoT 中心内为 Pi 注册设备。Register a device for Pi in your IoT hub.
  • 设置 Raspberry Pi。Set up Raspberry Pi.
  • 在 Pi 上运行示例应用程序,将传感器数据发送到 IoT 中心。Run a sample application on Pi to send sensor data to your IoT hub.

学习内容What you learn

  • 如何创建 Azure IoT 中心以及如何获取新的设备连接字符串。How to create an Azure IoT hub and get your new device connection string.
  • 如何通过 BME280 传感器连接 Pi。How to connect Pi with a BME280 sensor.
  • 如何通过在 Pi 上运行示例应用程序来收集传感器数据。How to collect sensor data by running a sample application on Pi.
  • 如何将传感器数据发送到 IoT 中心。How to send sensor data to your IoT hub.

需要什么What you need

需要什么

  • 一个 Raspberry Pi 2 或 Raspberry Pi 3 电路板。A Raspberry Pi 2 or Raspberry Pi 3 board.
  • Azure 订阅。An Azure subscription. 如果没有 Azure 订阅,可在开始前创建一个试用帐户If you don't have an Azure subscription, create a trial account before you begin.
  • 连接到 Pi 的监视器、USB 键盘和鼠标。A monitor, a USB keyboard, and mouse that connects to Pi.
  • 运行 Windows 或 Linux 的 Mac 或电脑。A Mac or PC that is running Windows or Linux.
  • Internet 连接。An internet connection.
  • 16 GB 或更大容量的 microSD 卡。A 16 GB or above microSD card.
  • USB-SD 适配器或 microSD 卡,用于将操作系统映像刻录到 microSD 卡中。A USB-SD adapter or microSD card to burn the operating system image onto the microSD card.
  • 带有 6 英尺微型 USB 电缆的 5 伏 2 安电源。A 5-volt 2-amp power supply with the 6-foot micro USB cable.

以下项可选:The following items are optional:

  • 已装配的 Adafruit BME280 温度、压力和湿度传感器。An assembled Adafruit BME280 temperature, pressure, and humidity sensor.
  • 试验板。A breadboard.
  • 6 根 F/M 跳线。6 F/M jumper wires.
  • 散射的 10 毫米 LED 灯。A diffused 10-mm LED.

Note

如果没有可选项,可以使用模拟的传感器数据。If you don't have the optional items, you can use simulated sensor data.

创建 IoT 中心Create an IoT hub

此部分介绍如何使用 Azure 门户创建 IoT 中心。This section describes how to create an IoT hub using the Azure portal.

  1. 登录到 Azure 门户Log in to the Azure portal.

  2. 选择“+创建资源”,然后搜索市场,寻找 IoT 中心Choose +Create a resource, then Search the Marketplace for the IoT Hub.

  3. 选择“IoT 中心”,然后单击“创建”按钮 。Select IoT Hub and click the Create button. 随即显示 IoT 中心创建过程的第一个屏幕。You see the first screen for creating an IoT hub.

    在 Azure 门户中创建中心

    填充字段。Fill in the fields.

    订阅:请选择要用于 IoT 中心的订阅。Subscription: Select the subscription to use for your IoT hub.

    资源组:可创建新的资源组或使用现有资源组。Resource Group: You can create a new resource group or use an existing one. 若要新建一个,请单击“新建” ,并填写要使用的名称。To create a new one, click Create new and fill in the name you want to use. 若要使用现有资源组,请单击“使用现有资源组” 并从下拉列表中选择该组。To use an existing resource group, click Use existing and select the resource group from the dropdown list. 有关详细信息,请参阅管理 Azure 资源管理器资源组For more information, see Manage Azure Resource Manager resource groups.

    区域:这是要在其中设置中心的区域。Region: This is the region in which you want your hub to be located. 从下拉列表中选择最靠近自己的位置。Select the location closest to you from the dropdown list.

    IoT 中心名称:输入 IoT 中心的名称。IoT Hub Name: Put in the name for your IoT Hub. 此名称必须全局唯一。This name must be globally unique. 如果输入的名称可用,会显示一个绿色复选标记。If the name you enter is available, a green check mark appears.

    Important

    IoT 中心将公开为 DNS 终结点,因此,命名时请务必避免包含任何敏感信息。The IoT hub will be publicly discoverable as a DNS endpoint, so make sure to avoid any sensitive information while naming it.

  4. 单击“下一步: 大小和规模”,以便继续创建 IoT 中心。Click Next: Size and scale to continue creating your IoT hub.

    使用 Azure 门户为新的 IoT 中心设置大小和缩放级别

    在此屏幕上,可以采用默认值,只需在底部单击“查看+创建”即可 。On this screen, you can take the defaults and just click Review + create at the bottom.

    定价和缩放层:可以根据你需要的功能数以及每天通过解决方案发送的消息数从多个层中进行选择。Pricing and scale tier: You can choose from several tiers depending on how many features you want and how many messages you send through your solution per day. 免费层适用于测试和评估。The free tier is intended for testing and evaluation. 它允许 500 台设备连接到 IoT 中心,并且每天最多传输 8,000 条信息。It allows 500 devices to be connected to the IoT hub and up to 8,000 messages per day. 每个 Azure 订阅可以在免费层中创建一个 IoT 中心。Each Azure subscription can create one IoT Hub in the free tier.

    IoT 中心单元:每个单位每日允许的消息数取决于中心的定价层。IoT Hub units: The number of messages allowed per unit per day depends on your hub's pricing tier. 例如,如果希望 IoT 中心支持 700,000 条消息输入,则选择两个 S1 层单位。For example, if you want the IoT hub to support ingress of 700,000 messages, you choose two S1 tier units.

    有关其他层选项的详细信息,请参阅选择合适的 IoT 中心层For details about the other tier options, see Choosing the right IoT Hub tier.

    高级 / 设备到云分区:此属性将设备到云消息与这些消息的同步读取器数目相关联。Advanced / Device-to-cloud partitions: This property relates the device-to-cloud messages to the number of simultaneous readers of the messages. 大多数 IoT 中心只需要 4 个分区。Most IoT hubs only need four partitions.

  5. 单击“查看+创建” 可查看选择。Click Review + create to review your choices. 会显示类似于以下的屏幕。You see something similar to this screen.

    查看用于创建新 IoT 中心的信息

  6. 单击“创建”以创建新的 IoT 中心 。Click Create to create your new IoT hub. 创建中心需要几分钟时间。Creating the hub takes a few minutes.

检索 IoT 中心的连接字符串Retrieve connection string for IoT hub

创建中心以后,请检索中心的连接字符串。After your hub has been created, retrieve the connection string for the hub. 该字符串用于将设备和应用程序连接到中心。This is used to connect devices and applications to your hub.

  1. 单击中心,查看“IoT 中心”窗格,其中包含“设置”等内容。Click on your hub to see the IoT Hub pane with Settings, and so on. 单击“共享访问策略”。Click Shared access policies.

  2. 在“共享访问策略”中,选择 iothubowner 策略。In Shared access policies, select the iothubowner policy.

  3. 在“共享访问密钥”下,复制“连接字符串 -- 主密钥”供以后使用。Under Shared access keys, copy the Connection string -- primary key to be used later.

    显示如何检索连接字符串

    有关详细信息,请参阅“IoT 中心开发人员指南”中的访问控制For more information, see Access control in the "IoT Hub developer guide."

在 IoT 中心内注册新设备Register a new device in the IoT hub

本部分在 IoT 中心的标识注册表中创建设备标识。In this section, you create a device identity in the identity registry in your IoT hub. 设备无法连接到 IoT 中心,除非它在标识注册表中具有条目。A device cannot connect to IoT hub unless it has an entry in the identity registry. 有关详细信息,请参阅 IoT 中心开发人员指南的“标识注册表”部分For more information, see the "Identity registry" section of the IoT Hub developer guide

  1. 在 IoT 中心导航菜单中,打开“IoT 设备”,然后单击“添加”,在 IoT 中心注册新设备。In your IoT hub navigation menu, open IoT Devices, then click Add to register a new device in your IoT hub.

    在门户中创建设备标识

  2. 提供新设备的名称(例如 myDeviceId),然后单击“保存”。Provide a name for your new device, such as myDeviceId, and click Save. 此操作会为 IoT 中心创建新设备标识。This action creates a new device identity for your IoT hub.

    添加新设备

    Important

    收集的日志中可能会显示设备 ID 用于客户支持和故障排除,因此,在为日志命名时,请务必避免包含任何敏感信息。The device ID may be visible in the logs collected for customer support and troubleshooting, so make sure to avoid any sensitive information while naming it.

  3. 创建设备后,在“IoT 设备”窗格的列表中打开该设备。After the device is created, open the device from the list in the IoT devices pane. 复制“连接字符串 ---主密钥”供以后使用。Copy the Connection string---primary key to use later.

    设备连接字符串

Note

IoT 中心标识注册表仅存储用于实现 IoT 中心安全访问的设备标识。The IoT Hub identity registry only stores device identities to enable secure access to the IoT hub. 它存储设备 ID 和密钥作为安全凭据,以及启用/禁用标志让你禁用对单个设备的访问。It stores device IDs and keys to use as security credentials, and an enabled/disabled flag that you can use to disable access for an individual device. 如果应用程序需要存储其他特定于设备的元数据,则应使用特定于应用程序的存储。If your application needs to store other device-specific metadata, it should use an application-specific store. 有关详细信息,请参阅 IoT 中心开发人员指南For more information, see IoT Hub developer guide.

设置 Raspberry PiSetup Raspberry Pi

为 Pi 安装 Raspbian 操作系统Install the Raspbian operating system for Pi

准备用于安装 Raspbian 映像的 microSD 卡。Prepare the microSD card for installation of the Raspbian image.

  1. 下载 Raspbian。Download Raspbian.

    a.a. 下载 Raspbian Stretch(.zip 文件)。Download Raspbian Stretch (the .zip file).

    Warning

    请使用上面的链接来下载 raspbian-2017-07-5 zip 映像。Please use above link to download raspbian-2017-07-5 zip image. Raspbian 映像的最新版本具有与接线 Pi 节点相关的已知问题,这可能会导致在接下来的步骤中发生故障。The latest version of Raspbian images has some known issues with Wiring-Pi Node, which might cause failure in your next steps.

    b.b. 将 Raspbian 映像解压缩到计算机的某个文件夹中。Extract the Raspbian image to a folder on your computer.

  2. 将 Raspbian 安装到 microSD 卡。Install Raspbian to the microSD card.

    a.a. 下载并安装 Etcher SD 卡刻录机实用工具Download and install the Etcher SD card burner utility.

    b.b. 运行 Etcher 并选择已在步骤 1 中解压缩的 Raspbian 映像。Run Etcher and select the Raspbian image that you extracted in step 1.

    c.c. 选择 microSD 卡驱动器。Select the microSD card drive. Etcher 可能已选择了正确的驱动器。Etcher may have already selected the correct drive.

    d.d. 单击“刷机”,将 Raspbian 安装到 microSD 卡。Click Flash to install Raspbian to the microSD card.

    e.e. 在安装完成后,从计算机中移除 microSD 卡。Remove the microSD card from your computer when installation is complete. 可以安全地直接取出 microSD 卡,因为 Etcher 会在完成后自动弹出或卸载 microSD 卡。It's safe to remove the microSD card directly because Etcher automatically ejects or unmounts the microSD card upon completion.

    f.f. 将 microSD 卡插入 Pi。Insert the microSD card into Pi.

启用 SSH 和 I2CEnable SSH and I2C

  1. 将 Pi 连接到监视器、键盘和鼠标。Connect Pi to the monitor, keyboard, and mouse.

  2. 启动 Pi,然后使用 pi 作为用户名并使用 raspberry 作为密码来登录 Raspbian。Start Pi and then sign into Raspbian by using pi as the user name and raspberry as the password.

  3. 依次单击 Raspberry 图标 >“首选项” > “Raspberry Pi 配置”。 Click the Raspberry icon > Preferences > Raspberry Pi Configuration.

    Raspbian 首选项菜单

  4. 在“接口” 选项卡上,将“I2C” 和“SSH” 设置为“启用” ,然后单击“确定” 。On the Interfaces tab, set I2C and SSH to Enable, and then click OK. 如果没有物理传感器并且想要使用模拟的传感器数据,则此步骤是可选的。If you don't have physical sensors and want to use simulated sensor data, this step is optional.

    在 Raspberry Pi 上启用 I2C 和 SSH

Note

若要启用 SSH 和 I2C,可在 raspberrypi.orgAdafruit.com 中找到更多参考文档。To enable SSH and I2C, you can find more reference documents on raspberrypi.org and Adafruit.com.

将传感器连接到 PiConnect the sensor to Pi

使用试验板和跳线,将 LED 灯和 BME280 连接到 Pi,如下所示。Use the breadboard and jumper wires to connect an LED and a BME280 to Pi as follows. 如果没有该传感器,请跳过此部分If you don’t have the sensor, skip this section.

Raspberry Pi 和传感器连接

BME280 传感器可以收集温度和湿度数据。The BME280 sensor can collect temperature and humidity data. 当设备向云发送消息时,LED 将闪烁。The LED blinks when the device sends a message to the cloud.

对于传感器引脚,请使用以下接线:For sensor pins, use the following wiring:

始端(传感器和 LED 灯)Start (Sensor & LED) 结束(开发板)End (Board) 线缆颜色Cable Color
VDD(引脚 5G)VDD (Pin 5G) 3.3V 电源(引脚 1)3.3V PWR (Pin 1) 白线White cable
GND(引脚 7G)GND (Pin 7G) GND(引脚 6)GND (Pin 6) 棕色电缆Brown cable
SDI(引脚 10G)SDI (Pin 10G) I2C1 SDA(引脚 3)I2C1 SDA (Pin 3) 红线Red cable
SCK(引脚 8G)SCK (Pin 8G) I2C1 SCL(引脚 5)I2C1 SCL (Pin 5) 橙色电缆Orange cable
LED VDD(引脚 18F)LED VDD (Pin 18F) GPIO 24(引脚 18)GPIO 24 (Pin 18) 白线White cable
LED GND(引脚 17F)LED GND (Pin 17F) GND(引脚 20)GND (Pin 20) 黑线Black cable

单击以查看 Raspberry Pi 2 和 3 引脚映射以供参考。Click to view Raspberry Pi 2 & 3 pin mappings for your reference.

成功将 BME280 连接到 Raspberry Pi 后,它应如下图所示。After you've successfully connected BME280 to your Raspberry Pi, it should be like below image.

连接在一起的 Pi 和 BME280

将 Pi 连接到网络Connect Pi to the network

使用 USB 微电缆和电源开启 Pi。Turn on Pi by using the micro USB cable and the power supply. 使用以太网电缆将 Pi 连接到有线网络,或者按照 Raspberry Pi Foundation 中的说明将 Pi 连接到无线网络。Use the Ethernet cable to connect Pi to your wired network or follow the instructions from the Raspberry Pi Foundation to connect Pi to your wireless network. 将 Pi 成功连接到网络后,需要记下 Pi 的 IP 地址After your Pi has been successfully connected to the network, you need to take a note of the IP address of your Pi.

已连接到有线网络

Note

确保 Pi 与计算机连接到同一网络。Make sure that Pi is connected to the same network as your computer. 例如,如果计算机连接到无线网络,而 Pi 连接到有线网络,则在 devdisco 输出中可能看不到 IP 地址。For example, if your computer is connected to a wireless network while Pi is connected to a wired network, you might not see the IP address in the devdisco output.

在 Pi 上运行示例应用程序Run a sample application on Pi

克隆示例应用程序,并安装必备组件包Clone sample application and install the prerequisite packages

  1. 从主计算机使用下列 SSH 客户端之一连接到 Raspberry Pi:Connect to your Raspberry Pi with one of the following SSH clients from your host computer:

    Windows 用户Windows Users

    a.a. 下载并安装 PuTTY for Windows。Download and install PuTTY for Windows.

    b.b. 将 Pi 的 IP 地址复制到主机名(或 IP 地址)部分,并选择 SSH 作为连接类型。Copy the IP address of your Pi into the Host name (or IP address) section and select SSH as the connection type.

    PuTTy

    Mac 和 Ubuntu 用户Mac and Ubuntu Users

    使用 Ubuntu 或 macOS 上的内置 SSH 客户端。Use the built-in SSH client on Ubuntu or macOS. 可能需要运行 ssh pi@<ip address of pi>,以通过 SSH 连接 Pi。You might need to run ssh pi@<ip address of pi> to connect Pi via SSH.

    Note

    默认用户名是 pi,密码是 raspberryThe default username is pi and the password is raspberry.

  2. 将 Node.js 和 NPM 安装到 Pi。Install Node.js and NPM to your Pi.

    首先检查 Node.js 版本。First check your Node.js version.

    node -v
    

    如果版本低于 10.x,或者 Pi 上没有 Node.js,请安装最新版本。If the version is lower than 10.x, or if there is no Node.js on your Pi, install the latest version.

    curl -sL https://deb.nodesource.com/setup_10.x | sudo -E bash
    sudo apt-get -y install nodejs
    
  3. 克隆示例应用程序。Clone the sample application.

    git clone https://github.com/Azure-Samples/iot-hub-node-raspberrypi-client-app
    
  4. 安装示例的所有程序包。Install all packages for the sample. 安装包括 Azure IoT 设备 SDK、BME280 传感器库和接线 Pi 库。The installation includes Azure IoT device SDK, BME280 Sensor library, and Wiring Pi library.

    cd iot-hub-node-raspberrypi-client-app
    sudo npm install
    

    Note

    完成此安装过程可能需要几分钟,具体取决于网络连接情况。It might take several minutes to finish this installation process depending on your network connection.

配置示例应用程序Configure the sample application

  1. 通过运行以下命令,打开配置文件:Open the config file by running the following commands:

    nano config.json
    

    配置文件

    此文件中有两个可以配置的项。There are two items in this file you can configure. 第一个是 interval,它定义发送到云的消息之间的时间间隔(以毫秒为单位)。The first one is interval, which defines the time interval (in milliseconds) between messages sent to the cloud. 第二个是 simulatedData,它是一个布尔值,指示是否使用模拟的传感器数据。The second one is simulatedData, which is a Boolean value for whether to use simulated sensor data or not.

    如果没有传感器,请将 simulatedData 值设置为 true,使示例应用程序创建和使用模拟的传感器数据。If you don't have the sensor, set the simulatedData value to true to make the sample application create and use simulated sensor data.

  2. 通过按“Ctrl-O”>“Enter”>“Ctrl-X”保存并退出。Save and exit by typing Control-O > Enter > Control-X.

运行示例应用程序Run the sample application

通过运行以下命令,生成示例应用程序:Run the sample application by running the following command:

sudo node index.js '<YOUR AZURE IOT HUB DEVICE CONNECTION STRING>'

Note

确保将设备连接字符串复制并粘贴到单引号中。Make sure you copy-paste the device connection string into the single quotes.

应看到以下输出,其中显示传感器数据以及发送至 IoT 中心的消息。You should see the following output that shows the sensor data and the messages that are sent to your IoT hub.

输出 - 从 Raspberry Pi 发送到 IoT 中心的传感器数据

读取 IoT 中心收到的消息Read the messages received by your hub

若要监视 IoT 中心从设备收到的消息,一种方法是使用适用于 Visual Studio Code 的 Azure IoT Tools。One way to monitor messages received by your IoT hub from your device is to use the Azure IoT Tools for Visual Studio Code. 若要了解详细信息,请参阅使用适用于 Visual Studio Code 的 Azure IoT Tools 在设备和 IoT 中心之间发送和接收消息To learn more, see Use Azure IoT Tools for Visual Studio Code to send and receive messages between your device and IoT Hub.

若要了解如何通过更多方式来处理设备发送的数据,请转到下一部分。For more ways to process data sent by your device, continue on to the next section.

后续步骤Next steps

此时已运行示例应用程序,收集传感器数据并将其发送到 IoT 中心。You’ve run a sample application to collect sensor data and send it to your IoT hub.

若要继续了解 Azure IoT 中心入门知识并浏览所有扩展的 IoT 方案,请参阅:To continue to get started with Azure IoT Hub and to explore all extended IoT scenarios, see the following: