public async Task <bool> AbandonAsync(Message message) { try { CreateDeviceClient(); deviceClient.OperationTimeoutInMilliseconds = 30000; setRetry(true); Logger.Log(DevEUI, $"abbandoning c2d message", Logger.LoggingLevel.Full); await deviceClient.AbandonAsync(message); Logger.Log(DevEUI, $"done abbandoning c2d message", Logger.LoggingLevel.Full); setRetry(false); return(true); } catch (Exception ex) { Logger.Log(DevEUI, $"could not abbandon c2d with error: {ex.Message}", Logger.LoggingLevel.Error); return(false); } }
private async void cmd07SubscribeAndWaitForMessage_Click(object sender, RoutedEventArgs e) { DeviceClient dc = DeviceClient.CreateFromConnectionString(m_devConnection, Microsoft.Azure.Devices.Client.TransportType.Amqp); //MQTT - ok, but no AbadonAsync await dc.OpenAsync(); Debug.WriteLine("Waiting for message!"); bool end = false; while (!end) { var msg = await dc.ReceiveAsync(TimeSpan.FromSeconds(500)); if (msg != null) { Debug.WriteLine($"{msg.MessageId} - {Encoding.ASCII.GetString(msg.GetBytes())}"); if (msg.DeliveryCount > 1) { await dc.CompleteAsync(msg); end = true; Debug.WriteLine($"{msg.MessageId} - OK"); } else { await dc.AbandonAsync(msg); //Not working in MQTT (due to protocol characteristics) // dc.RejectAsync - doszło ale odrzycamy Debug.WriteLine($"{msg.MessageId} - AbadonAsync"); } } } }
/// <summary> /// Starts message receiver loop. /// </summary> /// <param name="onReceiveMsg"></param> /// <param name="cancelationToken"></param> /// <param name="args"></param> /// <returns></returns> public Task OnMessage(Func <object, bool> onReceiveMsg, CancellationToken cancelationToken, Dictionary <string, object> args = null) { TimeSpan timeout = TimeSpan.FromMilliseconds(60000); if (args != null) { if (args.ContainsKey("TimeoutInMs")) { timeout = TimeSpan.FromMilliseconds((int)args["TimeoutInMs"]); } } return(Task.Run(() => { while (cancelationToken.IsCancellationRequested == false) { try { var msg = m_DeviceClient.ReceiveAsync().Result; bool completionState = (bool)onReceiveMsg?.Invoke(msg == null ? null : msg.GetBytes()); if (msg != null) { if (completionState) { m_DeviceClient.CompleteAsync(msg).Wait(); } else { m_DeviceClient.AbandonAsync(msg).Wait(); } } else { Task.Delay(timeout).Wait(); } } catch (Exception ex) { Debug.WriteLine(ex.Message); } } }, cancelationToken)); }
public async Task RiceviDatiAsync() { while (true) { Microsoft.Azure.Devices.Client.Message persona = await _client.ReceiveAsync(); // Se non arrivano messaggi nell'ultimo minuto (default value) il messaggio risulta NULL. if (persona == null) { continue; } // Le operazioni sul messaggio dovranno avere la logica di IDEMPOTENZA. // L'esecuzione dell'azione potrebbe fallire e il messaggio potrebbe essere ripristinato try { string messaggio = Encoding.ASCII.GetString(persona.GetBytes()); _pinBlueLed.SetDriveMode(GpioPinDriveMode.Output); _pinBlueLed.Write(GpioPinValue.Low); if (messaggio == null) { _pinRedLed.SetDriveMode(GpioPinDriveMode.Output); _pinRedLed.Write(GpioPinValue.High); await ErrorReadAsync(); } else { _pinGreenLed.SetDriveMode(GpioPinDriveMode.Output); _pinGreenLed.Write(GpioPinValue.High); Person personaPresente = JsonConvert.DeserializeObject <Person>(messaggio); await SuccesReadAsync(personaPresente); if (!string.IsNullOrEmpty(personaPresente.Uri)) { await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { PersonImage.Source = new BitmapImage(new Uri(personaPresente.Uri)); }); } await ResetAsync(); } await _client.CompleteAsync(persona); // sblocco il messaggio e notifico che è stato ricevuto correttamente } catch (Exception) { await _client.AbandonAsync(persona); } await ResetAsync(); } }
/// <summary> /// Retrieves the next message from the IoT Hub /// </summary> /// <param name="device">The device to retieve the IoT Hub message for</param> /// <returns>Returns a DeserializableCommand that wraps the byte array of the message from IoT Hub</returns> public async Task <DeserializableCommand> ReceiveAsync() { Client.Message message = await AzureRetryHelper.OperationWithBasicRetryAsync( async() => { Exception exp; Client.Message msg; exp = null; msg = null; try { msg = await _deviceClient.ReceiveAsync(); } catch (Exception exception) { exp = exception; } if (exp != null) { _logger.LogError( "{0}{0}*** Exception: ReceiveAsync ***{0}{0}{1}{0}{0}", Console.Out.NewLine, exp); if (msg != null) { await _deviceClient.AbandonAsync(msg); } } return(msg); }); if (message != null) { return(new DeserializableCommand(message)); } return(null); }
public AzureIoTModule(string azureIoTHubConnectionString, params MessageTag[] tags) : base(tags) { azureDeviceClient = DeviceClient.CreateFromConnectionString(azureIoTHubConnectionString); this.MessageClientRegistered += AzureIoTModule_MessageClientRegistered; messageReceiveTask = Task.Run(async() => { while (true) { var message = await azureDeviceClient.ReceiveAsync(); if (message != null) { var eventArgs = new IoTHubMessageReceivedEventArgs(message); IoTHubMessageReceived?.Invoke(this, eventArgs); switch (eventArgs.ResponseAction) { case ResponseAction.Complete: await azureDeviceClient.CompleteAsync(message); break; case ResponseAction.Reject: await azureDeviceClient.RejectAsync(message); break; case ResponseAction.Abandon: await azureDeviceClient.AbandonAsync(message); break; default: throw new NotImplementedException(); } } } ; }); }
static async Task HandleMessageAsync(DeviceClient deviceClient, Config config, string[] args) { WriteLine("CTRL+C to interrupt the read operation"); while (true) { var message = await deviceClient.ReceiveAsync(); try { var messageBytes = message.GetBytes(); var messageText = Encoding.UTF8.GetString(messageBytes); WriteLine($"Received {messageText}"); await deviceClient.CompleteAsync(message); } catch (Exception ex) { await deviceClient.AbandonAsync(message); } } }
public async Task SignalAbandonedCommand(DeserializableCommand command) { if (command == null) { throw new ArgumentNullException("command"); } Debug.Assert( !string.IsNullOrEmpty(command.LockToken), "command.LockToken is a null reference or empty string."); await AzureRetryHelper.OperationWithBasicRetryAsync( async() => { try { await _deviceClient.AbandonAsync(command.LockToken); } catch (Exception ex) { _logger.LogError($"Abandon Command failed, device: {_device.DeviceID}, exception: {ex.Message}"); } }); }
/// <summary> /// Receive the event from cloud /// User can auto Commit, Abandon or None of them, user will be asked 'a' for Abandon and 'c' for Commit /// </summary> /// <returns></returns> private async Task starReceivingCommands() { bool isColor = true; Helper.WriteLine("\nStarted Receiving cloud to device messages from service", ConsoleColor.White); while (true) { Message receivedMessage = await m_DeviceClient.ReceiveAsync(); if (receivedMessage == null) { Helper.WriteLine("Commend receiver timed out. Reconnected...", ConsoleColor.Gray); continue; } var bytes = receivedMessage.GetBytes(); if (isColor) { Helper.WriteLine($"Message Receiving ...{Environment.NewLine}Message ID: {receivedMessage.MessageId}{Environment.NewLine}Message: {Encoding.UTF8.GetString(bytes)}", ConsoleColor.DarkMagenta); } else { Helper.WriteLine($"Message Receiving ...{Environment.NewLine}Message ID: {receivedMessage.MessageId}{Environment.NewLine}Message: {Encoding.UTF8.GetString(bytes)}", ConsoleColor.Green); } // switch color isColor = !isColor; try { switch (Action) { case CommandAction.Complete: await m_DeviceClient.CompleteAsync(receivedMessage); Console.ForegroundColor = m_FeedbackClr; Console.WriteLine("Command completed successfully (AutoCommit) :)!"); Console.ResetColor(); break; case CommandAction.Abandon: await m_DeviceClient.AbandonAsync(receivedMessage); Console.ForegroundColor = m_FeedbackClr; Console.WriteLine("Command abandoned successfully :)!"); Console.ResetColor(); break; case CommandAction.None: default: Console.WriteLine(); Console.ForegroundColor = m_FeedbackClr; Console.WriteLine("Enter 'a' for Abandon or 'c' for Complete"); Console.ResetColor(); string whatTodo = Console.ReadLine(); if (whatTodo == "a") { await m_DeviceClient.AbandonAsync(receivedMessage); Console.ForegroundColor = m_FeedbackClr; Console.WriteLine("Command abandoned successfully :)!"); Console.ResetColor(); } else if (whatTodo == "c") { await m_DeviceClient.CompleteAsync(receivedMessage); Console.ForegroundColor = m_FeedbackClr; Console.WriteLine("Command completed successfully :)!"); Console.ResetColor(); } else { Console.ForegroundColor = m_FeedbackClr; Console.WriteLine("Receiving of commands has been stopped!"); Console.ResetColor(); } break; } } catch (Exception) { throw; } } }
public async Task AbandonAsync(Message message) { await deviceClient.AbandonAsync(message); }
private static async void DoReceive(object status) { try { while (true) { DeviceClient deviceClient = (DeviceClient)status; using (Message message = await deviceClient.ReceiveAsync()) { if (message != null) { Console.WriteLine(); Console.WriteLine($"MessageID:{message.MessageId}"); Console.WriteLine($"ComponentName:{message.ComponentName}"); Console.WriteLine($"ConnectionDeviceId:{message.ConnectionDeviceId}"); Console.WriteLine($"ConnectionModuleId:{message.ConnectionModuleId}"); Console.WriteLine($"ContentEncoding:{message.ContentEncoding}"); Console.WriteLine($"ContentType:{message.ContentType}"); Console.WriteLine($"CorrelationId:{message.CorrelationId}"); Console.WriteLine($"CreationTimeUtc:{message.CreationTimeUtc}"); Console.WriteLine($"DeliveryCount:{message.DeliveryCount}"); Console.WriteLine($"EnqueuedTimeUtc:{message.EnqueuedTimeUtc}"); Console.WriteLine($"ExpiryTimeUtc:{message.ExpiryTimeUtc}"); Console.WriteLine($"CreationTimeUtc:{message.InputName}"); Console.WriteLine($"IsSecurityMessage:{message.IsSecurityMessage}"); Console.WriteLine($"MessageSchema:{message.MessageSchema}"); Console.WriteLine($"SequenceNumber:{message.SequenceNumber}"); Console.WriteLine($"To:{message.To}"); Console.WriteLine($"UserId:{message.UserId}"); string messageBody = Encoding.UTF8.GetString(message.GetBytes()); Console.WriteLine($"Body:{messageBody}"); if (messageBody.EndsWith("R", StringComparison.InvariantCultureIgnoreCase)) { Console.WriteLine($"RejectAsync"); await deviceClient.RejectAsync(message); } if (messageBody.EndsWith("C", StringComparison.InvariantCultureIgnoreCase)) { Console.WriteLine($"CompleteAsync"); await deviceClient.CompleteAsync(message); } if (messageBody.EndsWith("A", StringComparison.InvariantCultureIgnoreCase)) { Console.WriteLine($"AbandonAsync"); await deviceClient.AbandonAsync(message); } foreach (var property in message.Properties) { Console.WriteLine($"Key:{property.Key} Value:{property.Value}"); } Console.WriteLine(); } } } } catch (Exception ex) { Console.WriteLine($"Receive loop {ex.Message}"); } }