Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.
 
 
 
 

67 рядки
2.7 KiB

  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. }