Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

MqttApplicationMessageInterceptor.cs 2.3 KiB

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