你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn

用于 .NET 的 Azure IoT 库

概述

Azure IoT 中心是一个完全托管的服务,可在数百万台设备和一个解决方案后端之间实现安全可靠的双向通信。

IoT 解决方案中的设备和数据源既包括简单的联网传感器,也包括功能强大的独立计算设备。 设备的处理能力、内存、通信带宽和通信协议支持可能存在限制。 使用 IoT 设备 SDK 可以实施各种设备的客户端应用程序和后端应用程序。

用于 .NET 的设备 SDK 可帮助构建运行 .NET 的、与 Azure IoT 中心相连接的设备。

用于 .NET 的服务 SDK 可帮助构建使用 .NET 的、可从云中管理和允许运行控制设备的后端应用程序。

详细了解 Azure IoT

客户端库

使用 .NET IoT 设备客户端可以连接到 IoT 中心并向其发送消息。

直接从 Visual Studio 包管理器控制台或使用 .NET Core CLI 安装 NuGet 包

Visual Studio 包管理器

Install-Package Microsoft.Azure.Devices.Client
dotnet add package Microsoft.Azure.Devices.Client

代码示例

此示例连接到 IoT 中心,并每秒发送一条消息。

string deviceKey = "<deviceKey>";
string deviceId = "<deviceId>";
string iotHubHostName = "<IoTHubHostname>";
var deviceAuthentication = new DeviceAuthenticationWithRegistrySymmetricKey(deviceId, deviceKey);

DeviceClient deviceClient = DeviceClient.Create(iotHubHostName, deviceAuthentication, TransportType.Mqtt);

while (true)
{
    double currentTemperature = 20 + Rand.NextDouble() * 15;
    double currentHumidity = 60 + Rand.NextDouble() * 20;

    var telemetryDataPoint = new
    {
        messageId = _messageId++,
        deviceId = deviceId,
        temperature = currentTemperature,
        humidity = currentHumidity
    };
    string messageString = JsonConvert.SerializeObject(telemetryDataPoint);
    Message message = new Message(Encoding.ASCII.GetBytes(messageString));
    message.Properties.Add("temperatureAlert", (currentTemperature > 30) ? "true" : "false");

    await deviceClient.SendEventAsync(message);
    Console.WriteLine("{0} > Sending message: {1}", DateTime.Now, messageString);

    await Task.Delay(1000);
}

示例

查看 Azure IoT 升频的完整列表

查看 Azure IoT 中心开发人员指南获取更多指导。