简体   繁体   English

Azure应用服务无法从Azure IoT中心获取数据

[英]Azure App Service can not get data from Azure IoT Hub

I want to use Azure App Service to get data from Azure IoT Hub. 我想使用Azure App Service从Azure IoT中心获取数据。

I try to register callback event to IoT Hub in the Application_Start() function. 我尝试在Application_Start()函数中向IoT中心注册回调事件。

When I can run my program with Visual Studio 2017 on my PC, event trigger normally by Azure IoT Hub and get the data. 当我可以在PC上使用Visual Studio 2017运行程序时,事件通常由Azure IoT中心触发并获取数据。

Unfortunately, when I deploy to the Azure cloud which is the service "Azure App Service", it only can get the trigger event from Azure IoT Hub when the App Service start up in few seconds. 不幸的是,当我部署到作为“ Azure App Service”服务的Azure云时,只有当App Service在几秒钟内启动时,它才能从Azure IoT中心获取触发事件。

There is no data get back from Azure IoT Hub and the event doesn't trigger anymore. 没有数据从Azure IoT中心获取,并且该事件不再触发。

I don't know the reason. 我不知道原因 Any advice will be appriciated. 任何建议都将适用。

Here is the event trigger code will run at the initial of the App Service. 这是事件触发代码,将在App Service的开头运行。 The entry point is Main() function. 入口点是Main()函数。



    using Microsoft.ServiceBus.Messaging;
    using System;
    using System.Collections.Generic;
    using System.Configuration;
    using System.Linq;
    using System.Threading.Tasks;
    using System.Web;
    using TelemetryEPHostConsoleApp;

    namespace MCM100_Dashboard.App_Start.TelemetryProcessor
    {
        public class TelemetryMain
        {
            private const string STORAGEACCOUNT_PROTOCOL = "https";// We use HTTPS to access the storage account

            public async static void Main()
            {
                var mainTask = new Task(GetAzureData);
                mainTask.Start();
                await mainTask;
            }
            public static string GetAzureData()
            {
               // IoT Hub
                string iotHubConnectionString = ConfigurationManager.AppSettings["IoTHub.ConnectionString"];
                string eventHubPath = "messages/events";// It's hard-coded for IoT Hub
                string consumerGroupName = "mcmpush";// It's hard-coded for this workshop

                // Storage Account
                string storageAccountName = ConfigurationManager.AppSettings["StorageAccount.Name"];
                string storageAccountKey = ConfigurationManager.AppSettings["StorageAccount.Key"];
                string storageAccountConnectionString = CombineConnectionString(storageAccountName, storageAccountKey);
                string eventProcessorHostName = "eventprocessorhost";
                string leaseName = eventProcessorHostName;

                EventProcessorHost eventProcessorHost = new EventProcessorHost(
                    eventProcessorHostName,
                    eventHubPath,
                    consumerGroupName,
                    iotHubConnectionString,
                    storageAccountConnectionString,
                    leaseName);


                var options = new EventProcessorOptions
                {
                    InitialOffsetProvider = (partitionId) => DateTime.UtcNow
                };
                options.ExceptionReceived += (sender, e) => { Console.WriteLine(e.Exception); };
                re: try
                {
                    eventProcessorHost.RegisterEventProcessorAsync(options).Wait();
                }
                catch (Exception e)
                {
                    System.Threading.Thread.Sleep(1000);
                    goto re;
                }


                eventProcessorHost.UnregisterEventProcessorAsync().Wait();

                return "";

            }

            private static string CombineConnectionString(string storageAccountName, string storageAccountKey)
            {
                return "DefaultEndpointsProtocol=" + STORAGEACCOUNT_PROTOCOL + ";" +
                    "AccountName=" + storageAccountName + ";" +
                    "AccountKey=" + storageAccountKey;
            }
        }
    }



    using Microsoft.ServiceBus.Messaging;
    using System;
    using System.Collections.Generic;
    using System.Diagnostics;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Net;
    using System.Configuration;
    using System.IO;
    using System.Web;

    namespace TelemetryEPHostConsoleApp
    {
        class TelemetryEventProcessor :IEventProcessor
        {
            static WebServerConnector _webSC = new WebServerConnector();

            async Task IEventProcessor.CloseAsync(PartitionContext context, CloseReason reason)
            {
                if (reason == CloseReason.Shutdown)
                {
                    await context.CheckpointAsync();
                }
            }

            Task IEventProcessor.OpenAsync(PartitionContext context)
            {
                return Task.FromResult(null);
            }

            async Task IEventProcessor.ProcessEventsAsync(PartitionContext context, IEnumerable messages)
            {
                // hope to trigger event
                foreach (EventData eventData in messages)
                {
                    string data = Encoding.UTF8.GetString(eventData.GetBytes());

                }

                //Call checkpoint every 5 minutes, so that worker can resume processing from 5 minutes back if it restarts.
                if (this.checkpointStopWatch.Elapsed > TimeSpan.FromMinutes(5))
                {
                    await context.CheckpointAsync();
                    this.checkpointStopWatch.Restart();
                }
            }

            private void ProcessMessage(string data)
            {
               return "";
            }

        }
    }

Immediately after RegisterEventProcessorAsync you are executing UnregisterEventProcessorAsync . RegisterEventProcessorAsync之后,您将立即执行UnregisterEventProcessorAsync Why is that? 这是为什么? You don't allow much time for events getting processed. 您没有太多时间来处理事件。 You might be better off using a continuous running webjob for reading data from the IoT hub. 使用连续运行的webjob从IoT中心读取数据可能会更好。

You should call UnregisterEventProcessorAsync only when you want to stop listening for incoming events. 仅当您要停止侦听传入事件时,才应调用UnregisterEventProcessorAsync The runtime will call Task IEventProcessor.ProcessEventsAsync(PartitionContext context, IEnumerable messages) any number of times after you have registered the eventprocessor and before unregistering. Task IEventProcessor.ProcessEventsAsync(PartitionContext context, IEnumerable messages)之后和注销之前,运行时将Task IEventProcessor.ProcessEventsAsync(PartitionContext context, IEnumerable messages)调用Task IEventProcessor.ProcessEventsAsync(PartitionContext context, IEnumerable messages)

Also, what is up with the return ""; 同样, return ""; I see a couple of times? 我见过几次吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM