You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

69 lines
2.5 KiB

  1. using System;
  2. using System.Threading;
  3. using System.Threading.Tasks;
  4. using MQTTnet.Packets;
  5. namespace MQTTnet
  6. {
  7. public sealed class MqttApplicationMessageReceivedEventArgs : EventArgs
  8. {
  9. readonly Func<MqttApplicationMessageReceivedEventArgs, CancellationToken, Task> _acknowledgeHandler;
  10. int _isAcknowledged;
  11. public MqttApplicationMessageReceivedEventArgs(
  12. string clientId,
  13. MqttApplicationMessage applicationMessage,
  14. MqttPublishPacket publishPacket,
  15. Func<MqttApplicationMessageReceivedEventArgs, CancellationToken, Task> acknowledgeHandler)
  16. {
  17. ClientId = clientId;
  18. ApplicationMessage = applicationMessage ?? throw new ArgumentNullException(nameof(applicationMessage));
  19. PublishPacket = publishPacket;
  20. _acknowledgeHandler = acknowledgeHandler;
  21. }
  22. internal MqttPublishPacket PublishPacket { get; }
  23. /// <summary>
  24. /// Gets the client identifier.
  25. /// Hint: This identifier needs to be unique over all used clients / devices on the broker to avoid connection issues.
  26. /// </summary>
  27. public string ClientId { get; }
  28. public MqttApplicationMessage ApplicationMessage { get; }
  29. public bool ProcessingFailed { get; set; }
  30. public MqttApplicationMessageReceivedReasonCode ReasonCode { get; set; } = MqttApplicationMessageReceivedReasonCode.Success;
  31. /// <summary>
  32. /// Gets or sets whether this message was handled.
  33. /// This value can be used in user code for custom control flow.
  34. /// </summary>
  35. public bool IsHandled { get; set; }
  36. /// <summary>
  37. /// Gets ir sets whether the library should send MQTT ACK packets automatically if required.
  38. /// </summary>
  39. public bool AutoAcknowledge { get; set; } = true;
  40. public object Tag { get; set; }
  41. public Task AcknowledgeAsync(CancellationToken cancellationToken)
  42. {
  43. if (_acknowledgeHandler == null)
  44. {
  45. throw new NotSupportedException("Deferred acknowledgement of application message is not yet supported in MQTTnet server.");
  46. }
  47. if (Interlocked.CompareExchange(ref _isAcknowledged, 1, 0) == 0)
  48. {
  49. return _acknowledgeHandler(this, cancellationToken);
  50. }
  51. throw new InvalidOperationException("The application message is already acknowledged.");
  52. }
  53. }
  54. }