精品国产人成在线_亚洲高清无码在线观看_国产在线视频国产永久2021_国产AV综合第一页一个的一区免费影院黑人_最近中文字幕MV高清在线视频

電子發燒友App

硬聲App

0
  • 聊天消息
  • 系統消息
  • 評論與回復
登錄后你可以
  • 下載海量資料
  • 學習在線課程
  • 觀看技術視頻
  • 寫文章/發帖/加入社區
會員中心
創作中心

完善資料讓更多小伙伴認識你,還能領取20積分哦,立即完善>

3天內不再提示
創作
電子發燒友網>電子資料下載>電子資料>通過IoT中心將環境數據從ProjectLab發送到Azure

通過IoT中心將環境數據從ProjectLab發送到Azure

2023-06-13 | zip | 0.00 MB | 次下載 | 免費

資料介紹

描述

(項目更新為RC-3(2023年3月30日發布)

此項目向您展示如何使用 IoT 中心連接將環境數據從您的 ProjectLab 發送到 Azure!

Meadow.Foundation是一個平臺,用于在 Meadow 上使用 .NET 快速輕松地構建連接的事物。它由Wilderness Labs 創建,完全開源并由 Wilderness Labs 社區維護。

在您開始這個項目之前,請確保您的 Meadow 板和開發環境是完全最新的。檢查發行說明部分以仔細檢查。

第 1 步 - 創建 Meadow 應用程序項目

在 Visual Studio 2022 for WindowsmacOS中創建一個新的Meadow Application項目并將其命名為MeadowAzureIoTHub

第 2 步 - 添加所需的 NuGet 包

對于這個項目,搜索并安裝以下 NuGet 包:

第 3 步 - 為 MeadowAzureIoTHub 編寫代碼

該項目具有以下結構:

pYYBAGSBN0CAfK5OAAA6YQ3MXxE464.jpg
?

配置文件

讓我們介紹 Meadow 開機時自動使用的所有三個配置文件。

app.config.yaml

# Uncomment additional options as needed.
# To learn more about these config options, including custom application configuration settings, check out the Application Settings Configuration documentation.
# http://developer.wildernesslabs.co/Meadow/Meadow.OS/Configuration/Application_Settings_Configuration/

Lifecycle:
    # Control whether Meadow will restart when an unhandled app exception occurs. Combine with Lifecycle > AppFailureRestartDelaySeconds to control restart timing.
    RestartOnAppFailure: false
    # When app set to restart automatically on app failure, 
    # AppFailureRestartDelaySeconds: 15

# Adjust the level of logging detail.
Logging:
    LogLevel:
        Default: "Information"

meadow.config.yaml

meadow.config.yaml 文件可用于設置通用板和系統配置設置。這包括操作系統和設備級別的設置,例如設備名稱、默認網絡行為和網絡設置。

# Uncommented these options as needed.
# To learn more about these config options, check out the OS & Device Configuration documentation.
# http://developer.wildernesslabs.co/Meadow/Meadow.OS/Configuration/OS_Device_Configuration/

Device:
    # Name of the device on the network.
    Name: MeadowAzureIoTHub

    # Uncomment if SD card hardware present on this hardware (e.g., Core-Compute module with SD add-on)? Optional; default value is `false`.
    SdStorageSupported: true

# Control how the ESP coprocessor will start and operate.
Coprocessor:
    # Should the ESP32 automatically attempt to connect to an access point at startup?
    # If set to true, wifi.config.yaml credentials must be stored in the device.
    AutomaticallyStartNetwork: true

    # Should the ESP32 automatically reconnect to the configured access point?
    AutomaticallyReconnect: true

    # Maximum number of retry attempts for connections etc. before an error code is returned.
    MaximumRetryCount: 7

# Network configuration.
Network:
    # Which interface should be used?
    DefaultInterface: WiFi

    # Automatically attempt to get the time at startup?
    GetNetworkTimeAtStartup: true

    # Time synchronization period in seconds.
    NtpRefreshPeriodSeconds: 600

    # Name of the NTP servers.
    NtpServers:
        - 0.pool.ntp.org
        - 1.pool.ntp.org
        - 2.pool.ntp.org
        - 3.pool.ntp.org

    # IP addresses of the DNS servers.
    DnsServers:
        - 1.1.1.1
        - 8.8.8.8

wifi.config.yaml

wifi.config.yaml 文件可用于設置默認 Wi-Fi 接入點和該接入點的密碼。

# To enable automatically connecting to a default network, make sure to enable the Coprocessor > AutomaticallyStartNetwork value in meadow.config.yaml.
Credentials:
    Ssid: SSID
    Password: PASSWORD

注意:確保每個文件的“屬性”窗口中將“復制到輸出目錄”設置“始終” 。

圖片資產

在此項目中,我們將使用一些圖像和圖標來指示我們Meadow何時加入我們的 WiFi 網絡以及何時通過 IoT Hub 將數據發送到 Azure 您可以從附件部分下載它們。

poYBAGSBN0OAfIzYAAAXlqEaH1Y157.jpg
?

注意:確保這些圖像中的每一個都“屬性”面板中將“構建操作”設置為嵌入式資源”

源代碼

現在我們將介紹此項目中使用的所有 C# 類。

Secrets.cs

public class Secrets
{
    ///     /// Name of the Azure IoT Hub created
    /// summary>
    public const string HUB_NAME = "HUB_NAME";

    ///     /// Name of the Azure IoT Hub created
    /// summary>
    public const string DEVICE_ID = "DEVICE_ID";

    ///     /// example "SharedAccessSignature sr=MeadowIoTHub ..... "
    /// summary>
    public const string SAS_TOKEN = "SharedAccessSignature...";
}

在此類中,您需要根據 Azure IoT 中心配置設置適當的值。您可以按照這篇博文一步一步地操作,其中會向您展示如何做到這一點。

IotHubManager.cs

public class IotHubManager
{
    private const string HubName = Secrets.HUB_NAME;
    private const string SasToken = Secrets.SAS_TOKEN;
    private const string DeviceId = Secrets.DEVICE_ID;

    private Connection connection;
    private SenderLink sender;

    public IotHubManager() { }

    public async Task Initialize()
    {
        string hostName = HubName + ".azure-devices.net";
        string userName = DeviceId + "@sas." + HubName;
        string senderAddress = "devices/" + DeviceId + "/messages/events";

        Resolver.Log.Info("Create connection factory...");
        var factory = new ConnectionFactory();

        Resolver.Log.Info("Create connection ...");
        connection = await factory.CreateAsync(new Address(hostName, 5671, userName, SasToken));

        Resolver.Log.Info("Create session ...");
        var session = new Session(connection);

        Resolver.Log.Info("Create SenderLink ...");
        sender = new SenderLink(session, "send-link", senderAddress);
    }

    public Task SendEnvironmentalReading((Temperature? Temperature, RelativeHumidity? Humidity, Pressure? Pressure, Resistance? GasResistance) reading)
    {
        try
        {
            Resolver.Log.Info("Create payload");
            string messagePayload = $"{{"Temperature":{reading.Temperature.Value.Celsius}," +
                $""Humidity":{reading.Humidity.Value.Percent}," +
                $""Pressure":{reading.Pressure.Value.Millibar}}}";

            Resolver.Log.Info("Create message");
            var message = new Message(Encoding.UTF8.GetBytes(messagePayload));
            message.ApplicationProperties = new Amqp.Framing.ApplicationProperties();

            Resolver.Log.Info("Send message");
            sender.Send(message, null, null);

            Resolver.Log.Info($"*** DATA SENT - Temperature - {reading.Temperature.Value.Celsius}, Humidity - {reading.Humidity.Value.Percent}, Pressure - {reading.Pressure.Value.Millibar} ***");
        }
        catch (Exception ex)
        {
            Resolver.Log.Info($"-- D2C Error - {ex.Message} --");
        }

        return Task.CompletedTask;
    }
}

此類用于與 Azure IoT 中心建立連接并通過 HTU21D 傳感器發送環境讀數。

DisplayController.cs

public class DisplayController
{
    private static readonly Lazy instance =
        new Lazy(() => new DisplayController());
    public static DisplayController Instance => instance.Value;

    static Color backgroundColor = Color.FromHex("#23ABE3");
    static Color foregroundColor = Color.Black;

    CancellationTokenSource token;

    protected BufferRgb888 imgConnecting, imgConnected, imgRefreshing, imgRefreshed;
    protected MicroGraphics graphics;

    private DisplayController() { }

    public void Initialize(IGraphicsDisplay display)
    {
        imgConnected = LoadJpeg("img_wifi_connected.jpg");
        imgConnecting = LoadJpeg("img_wifi_connecting.jpg");
        imgRefreshing = LoadJpeg("img_refreshing.jpg");
        imgRefreshed = LoadJpeg("img_refreshed.jpg");

        graphics = new MicroGraphics(display)
        {
            CurrentFont = new Font12x16(),
            Stroke = 3,
        };

        graphics.Clear(true);
    }

    BufferRgb888 LoadJpeg(string fileName)
    {
        var jpgData = LoadResource(fileName);
        var decoder = new JpegDecoder();
        decoder.DecodeJpeg(jpgData);
        return new BufferRgb888(decoder.Width, decoder.Height, decoder.GetImageData());
    }

    protected void DrawBackground()
    {
        var logo = LoadJpeg("img_meadow.jpg");

        graphics.Clear(backgroundColor);

        graphics.DrawBuffer(
            x: graphics.Width / 2 - logo.Width / 2,
            y: 63,
            buffer: logo);

        graphics.DrawText(graphics.Width / 2, 160, "Azure IoT Hub", Color.Black, alignmentH: HorizontalAlignment.Center);
    }

    protected byte[] LoadResource(string filename)
    {
        var assembly = Assembly.GetExecutingAssembly();
        var resourceName = $"MeadowAzureIoTHub.{filename}";

        using Stream stream = assembly.GetManifestResourceStream(resourceName);
        using var ms = new MemoryStream();
        stream.CopyTo(ms);
        return ms.ToArray();
    }

    public void ShowSplashScreen()
    {
        DrawBackground();

        graphics.Show();
    }

    public async Task ShowConnectingAnimation()
    {
        token = new CancellationTokenSource();

        bool alternateImg = false;
        while (!token.IsCancellationRequested)
        {
            alternateImg = !alternateImg;

            graphics.DrawBuffer(204, 6, alternateImg ? imgConnecting : imgConnected);
            graphics.Show();

            await Task.Delay(500);
        }
    }

    public void ShowConnected()
    {
        token.Cancel();
        graphics.DrawBuffer(204, 6, imgConnected);

        graphics.DrawBuffer(6, 6, imgRefreshed);

        graphics.DrawRectangle(0, 32, 240, 208, backgroundColor, true);

        graphics.DrawCircle(120, 75, 50, foregroundColor);
        graphics.DrawText(120, 59, "Temp", foregroundColor, alignmentH: HorizontalAlignment.Center);

        graphics.DrawCircle(62, 177, 50, foregroundColor);
        graphics.DrawText(62, 161, "Pres", foregroundColor, alignmentH: HorizontalAlignment.Center);

        graphics.DrawCircle(178, 177, 50, foregroundColor);
        graphics.DrawText(178, 161, "Hum", foregroundColor, alignmentH: HorizontalAlignment.Center);

        graphics.Show();
    }

    public async Task StartSyncCompletedAnimation((Temperature? Temperature, RelativeHumidity? Humidity, Pressure? Pressure, Resistance? GasResistance) reading)
    {
        graphics.DrawBuffer(6, 6, imgRefreshing);
        graphics.Show();
        await Task.Delay(TimeSpan.FromSeconds(1));

        graphics.DrawRectangle(75, 78, 90, 16, backgroundColor, true);
        graphics.DrawText(120, 78, $"{reading.Temperature.Value.Celsius:N1}°C", foregroundColor, alignmentH: HorizontalAlignment.Center);

        graphics.DrawRectangle(17, 180, 90, 16, backgroundColor, true);
        graphics.DrawText(62, 180, $"{reading.Pressure.Value.StandardAtmosphere:N1}atm", foregroundColor, alignmentH: HorizontalAlignment.Center);

        graphics.DrawRectangle(133, 180, 90, 16, backgroundColor, true);
        graphics.DrawText(178, 180, $"{reading.Humidity.Value.Percent:N2}%", foregroundColor, alignmentH: HorizontalAlignment.Center);

        graphics.DrawBuffer(6, 6, imgRefreshed);
        graphics.Show();
    }
}

此類使用MicroGraphics在 ST7789 顯示屏中繪制所有 UI,例如在應用程序啟動時顯示啟動畫面、更新溫度/濕度值,以及 WiFi 和同步指示器以了解消息何時發送到 IoT 中心。

MeadowApp.cs

public class MeadowApp : App
{
    RgbPwmLed onboardLed;
    IProjectLabHardware projectLab;
    IotHubManager amqpController;

    public override Task Initialize()
    {
        onboardLed = new RgbPwmLed(
            Device.Pins.OnboardLedRed,
            Device.Pins.OnboardLedGreen,
            Device.Pins.OnboardLedBlue);
        onboardLed.SetColor(Color.Red);

        try
        {
            amqpController = new IotHubManager();

            var wifi = Device.NetworkAdapters.Primary();
            wifi.NetworkConnected += NetworkConnected;

            projectLab = ProjectLab.Create();
            projectLab.EnvironmentalSensor.Updated += EnvironmentalSensorUpdated;

            DisplayController.Instance.Initialize(projectLab.Display);
            DisplayController.Instance.ShowSplashScreen();
            DisplayController.Instance.ShowConnectingAnimation();
        }
        catch (Exception ex)
        {
            Resolver.Log.Error($"Failed to Connect: {ex.Message}");
        }

        return Task.CompletedTask;
    }

    private async void NetworkConnected(INetworkAdapter sender, NetworkConnectionEventArgs args)
    {
        DisplayController.Instance.ShowConnected();

        await amqpController.Initialize();

        projectLab.EnvironmentalSensor.StartUpdating(TimeSpan.FromSeconds(15));

        onboardLed.SetColor(Color.Green);
    }

    private async void EnvironmentalSensorUpdated(object sender, IChangeResult<(Meadow.Units.Temperature? Temperature, Meadow.Units.RelativeHumidity? Humidity, Meadow.Units.Pressure? Pressure, Meadow.Units.Resistance? GasResistance)> e)
    {
        await amqpController.SendEnvironmentalReading(e.New);
        await DisplayController.Instance.StartSyncCompletedAnimation(e.New);
    }
}

MeadowApp主類初始化 ProjectLab 上的顯示和環境傳感器,一旦 Meadow 加入 WiFi 網絡并與 Azure 建立連接,它將開始每 15 秒讀取一次室溫、濕度和壓力。

第 5 步 - 運行項目

單擊Visual Studio中的“運行”按鈕它應該類似于以下 GIF:

MeadowAzureIoTHub 項目正在運行...
?

當應用程序運行時,您應該有類似這樣的輸出:

Create connection factory...
Create connection ...
Create session ...
Create SenderLink ...
Create payload
Create message
Send message
*** DATA SENT - Temperature - 27.9073605400976, Humidity - 29.4871487326418, Pressure - 1020.90879412913 ***
Create payload
Create message
Send message
*** DATA SENT - Temperature - 28.0586979364511, Humidity - 29.1871445300884, Pressure - 1020.8916192437 ***
Create payload
Create message
Send message
*** DATA SENT - Temperature - 28.179768034583, Humidity - 28.9781536413303, Pressure - 1020.90573418024 ***
...

這可確保您已建立與Azure的連接,并且該應用每 15 秒向IoT 中心發送一次數據

您還可以轉到Azure門戶,打開IoT 中心概述部分,然后查看傳入消息的數量隨著時間的推移而增加。

?

poYBAGSBN0eAVqaSAAEfGWUvbc4799.png
IoT 中心傳入消息
?

查看 Meadow.Foundation!

就您可以使用 Meadow.Foundation 做的大量令人興奮的事情而言,這個項目只是冰山一角。

它帶有一個龐大的外設驅動程序庫,其中包含適用于最常見傳感器和外設的驅動程序。

  • 它帶有一個龐大的外設驅動程序庫,其中包含適用于最常見傳感器和外設的驅動程序。
  • 外設驅動程序封裝了核心邏輯并公開了一個簡單、干凈、現代的 API。
  • 該項目得到了不斷發展的社區的支持,該社區不斷致力于構建酷炫的互聯事物,并且總是樂于幫助新來者和討論新項目。

參考


下載該資料的人也在下載 下載該資料的人還在閱讀
更多 >

評論

查看更多

下載排行

本周

  1. 1山景DSP芯片AP8248A2數據手冊
  2. 1.06 MB  |  532次下載  |  免費
  3. 2RK3399完整板原理圖(支持平板,盒子VR)
  4. 3.28 MB  |  339次下載  |  免費
  5. 3TC358743XBG評估板參考手冊
  6. 1.36 MB  |  330次下載  |  免費
  7. 4DFM軟件使用教程
  8. 0.84 MB  |  295次下載  |  免費
  9. 5元宇宙深度解析—未來的未來-風口還是泡沫
  10. 6.40 MB  |  227次下載  |  免費
  11. 6迪文DGUS開發指南
  12. 31.67 MB  |  194次下載  |  免費
  13. 7元宇宙底層硬件系列報告
  14. 13.42 MB  |  182次下載  |  免費
  15. 8FP5207XR-G1中文應用手冊
  16. 1.09 MB  |  178次下載  |  免費

本月

  1. 1OrCAD10.5下載OrCAD10.5中文版軟件
  2. 0.00 MB  |  234315次下載  |  免費
  3. 2555集成電路應用800例(新編版)
  4. 0.00 MB  |  33566次下載  |  免費
  5. 3接口電路圖大全
  6. 未知  |  30323次下載  |  免費
  7. 4開關電源設計實例指南
  8. 未知  |  21549次下載  |  免費
  9. 5電氣工程師手冊免費下載(新編第二版pdf電子書)
  10. 0.00 MB  |  15349次下載  |  免費
  11. 6數字電路基礎pdf(下載)
  12. 未知  |  13750次下載  |  免費
  13. 7電子制作實例集錦 下載
  14. 未知  |  8113次下載  |  免費
  15. 8《LED驅動電路設計》 溫德爾著
  16. 0.00 MB  |  6656次下載  |  免費

總榜

  1. 1matlab軟件下載入口
  2. 未知  |  935054次下載  |  免費
  3. 2protel99se軟件下載(可英文版轉中文版)
  4. 78.1 MB  |  537798次下載  |  免費
  5. 3MATLAB 7.1 下載 (含軟件介紹)
  6. 未知  |  420027次下載  |  免費
  7. 4OrCAD10.5下載OrCAD10.5中文版軟件
  8. 0.00 MB  |  234315次下載  |  免費
  9. 5Altium DXP2002下載入口
  10. 未知  |  233046次下載  |  免費
  11. 6電路仿真軟件multisim 10.0免費下載
  12. 340992  |  191187次下載  |  免費
  13. 7十天學會AVR單片機與C語言視頻教程 下載
  14. 158M  |  183279次下載  |  免費
  15. 8proe5.0野火版下載(中文版免費下載)
  16. 未知  |  138040次下載  |  免費