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.

MqttSubscriptionInterceptor.cs 1.8 KiB

преди 5 години
преди 5 години
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. using System;
  2. using System.Threading.Tasks;
  3. using IronPython.Runtime;
  4. using Microsoft.Extensions.Logging;
  5. using MQTTnet.Server.Scripting;
  6. namespace MQTTnet.Server.Mqtt
  7. {
  8. public class MqttSubscriptionInterceptor : IMqttServerSubscriptionInterceptor
  9. {
  10. private readonly PythonScriptHostService _pythonScriptHostService;
  11. private readonly ILogger _logger;
  12. public MqttSubscriptionInterceptor(PythonScriptHostService pythonScriptHostService, ILogger<MqttSubscriptionInterceptor> logger)
  13. {
  14. _pythonScriptHostService = pythonScriptHostService ?? throw new ArgumentNullException(nameof(pythonScriptHostService));
  15. _logger = logger ?? throw new ArgumentNullException(nameof(logger));
  16. }
  17. public Task InterceptSubscriptionAsync(MqttSubscriptionInterceptorContext context)
  18. {
  19. try
  20. {
  21. var pythonContext = new PythonDictionary
  22. {
  23. { "accept_subscription", context.AcceptSubscription },
  24. { "close_connection", context.CloseConnection },
  25. { "client_id", context.ClientId },
  26. { "topic", context.TopicFilter.Topic },
  27. { "qos", (int)context.TopicFilter.QualityOfServiceLevel }
  28. };
  29. _pythonScriptHostService.InvokeOptionalFunction("on_intercept_subscription", pythonContext);
  30. context.AcceptSubscription = (bool)pythonContext["accept_subscription"];
  31. context.CloseConnection = (bool)pythonContext["close_connection"];
  32. }
  33. catch (Exception exception)
  34. {
  35. _logger.LogError(exception, "Error while intercepting subscription.");
  36. }
  37. return Task.CompletedTask;
  38. }
  39. }
  40. }