/*The PipeMessage method is what will connect to the IoT Edge Hub and will queue the shelf data * for processing. * * It will be registered as an inputMessageHandler with the IoT Edge Hub in the ExecuteAsync method * that follows. */ public async Task <MessageResponse> PipeMessage(Message message, object userContext) { var moduleClient = userContext as ModuleClient; if (moduleClient == null) { throw new InvalidOperationException("UserContext doesn't contain " + "expected values"); } /*This section receives the data from the IoT Edge Hub and converts it to a Shelf object * for processing through signalR to the WebApp module. */ byte[] messageBytes = message.GetBytes(); string messageString = Encoding.UTF8.GetString(messageBytes); if (!string.IsNullOrEmpty(messageString)) { try { _logger.LogInformation($"Receiving Message: {messageString.TrimStart('"').TrimEnd('"').Replace('\\', ' ')}"); Payload productData = JsonConvert.DeserializeObject <Payload> (messageString.TrimStart('"').TrimEnd('"').Replace("\\", String.Empty)); PayloadQueue.QueuePayload(productData); if (PayloadQueue.Count() > 1) { while (PayloadQueue.Count() > 1) { await PayloadQueue.DequeueAsync(new CancellationToken()); //throw away result _logger.LogInformation("Dequeue extra data"); } } // catch and swallow exceptions } catch (AggregateException ex) { _logger.LogError($"Error processing message: {ex.Flatten()}"); } catch (Exception ex) { _logger.LogError($"Error processing message: {ex}"); } } return(MessageResponse.Completed); }
protected override async Task ExecuteAsync(CancellationToken stoppingToken) { /*hubContext allows ClientNotifier to act as a part of the signalR hub and send messages. See this * for more information: https://docs.microsoft.com/en-us/aspnet/core/signalr/hubcontext?view=aspnetcore-2.1 */ var notifytask = Task.Run(async() => { while (!stoppingToken.IsCancellationRequested) { if (PayloadQueue.Count() > 0) { await this.HubContext.Clients.All.SendAsync("NewData"); } await Task.Delay(TimeSpan.FromSeconds(1)); } }, stoppingToken); await Task.WhenAll(notifytask); }