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.

MqttApplicationMessageInterceptor.cs 2.7 KiB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. using System;
  2. using System.Threading.Tasks;
  3. using IronPython.Runtime;
  4. using Microsoft.Extensions.Logging;
  5. using MQTTnet.Protocol;
  6. using MQTTnet.Server.Scripting;
  7. namespace MQTTnet.Server.Mqtt
  8. {
  9. public class MqttApplicationMessageInterceptor : IMqttServerApplicationMessageInterceptor
  10. {
  11. private readonly PythonScriptHostService _pythonScriptHostService;
  12. private readonly ILogger _logger;
  13. public MqttApplicationMessageInterceptor(PythonScriptHostService pythonScriptHostService, ILogger<MqttApplicationMessageInterceptor> logger)
  14. {
  15. _pythonScriptHostService = pythonScriptHostService ?? throw new ArgumentNullException(nameof(pythonScriptHostService));
  16. _logger = logger ?? throw new ArgumentNullException(nameof(logger));
  17. }
  18. public Task InterceptApplicationMessagePublishAsync(MqttApplicationMessageInterceptorContext context)
  19. {
  20. try
  21. {
  22. var pythonContext = new PythonDictionary
  23. {
  24. { "accept_publish", context.AcceptPublish },
  25. { "close_connection", context.CloseConnection },
  26. { "client_id", context.ClientId },
  27. { "topic", context.ApplicationMessage.Topic },
  28. { "qos", (int)context.ApplicationMessage.QualityOfServiceLevel },
  29. { "retain", context.ApplicationMessage.Retain }
  30. };
  31. _pythonScriptHostService.InvokeOptionalFunction("on_intercept_application_message", pythonContext);
  32. context.AcceptPublish = (bool)pythonContext.get("accept_publish", context.AcceptPublish);
  33. context.CloseConnection = (bool)pythonContext.get("close_connection", context.CloseConnection);
  34. context.ApplicationMessage.Topic = (string)pythonContext.get("topic", context.ApplicationMessage.Topic);
  35. context.ApplicationMessage.QualityOfServiceLevel = (MqttQualityOfServiceLevel)(int)pythonContext.get("qos", (int)context.ApplicationMessage.QualityOfServiceLevel);
  36. }
  37. catch (Exception exception)
  38. {
  39. _logger.LogError(exception, "Error while intercepting application message.");
  40. }
  41. return Task.CompletedTask;
  42. }
  43. // TODO: Create dump(object) method in wrapper (creates JSON and prints it).
  44. public class PythonMqttApplicationMessageInterceptorContext
  45. {
  46. public bool accept_connection;
  47. public bool accept_publish;
  48. public string client_id;
  49. public string topic;
  50. public int qos;
  51. public bool retain;
  52. }
  53. }
  54. }