Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.
 
 
 
 

48 linhas
1.6 KiB

  1. using Microsoft.Extensions.Logging;
  2. using System;
  3. using System.Collections.Generic;
  4. namespace MQTTnet.Server.Scripting.DataSharing
  5. {
  6. public class DataSharingService
  7. {
  8. readonly Dictionary<string, object> _storage = new Dictionary<string, object>();
  9. readonly PythonScriptHostService _pythonScriptHostService;
  10. readonly ILogger<DataSharingService> _logger;
  11. public DataSharingService(PythonScriptHostService pythonScriptHostService, ILogger<DataSharingService> logger)
  12. {
  13. _pythonScriptHostService = pythonScriptHostService ?? throw new ArgumentNullException(nameof(pythonScriptHostService));
  14. _logger = logger ?? throw new ArgumentNullException(nameof(logger));
  15. }
  16. public void Configure()
  17. {
  18. _pythonScriptHostService.RegisterProxyObject("write_shared_data", new Action<string, object>(Write));
  19. _pythonScriptHostService.RegisterProxyObject("read_shared_data", new Func<string, object, object>(Read));
  20. }
  21. public void Write(string key, object value)
  22. {
  23. lock (_storage)
  24. {
  25. _storage[key] = value;
  26. _logger.LogInformation($"Shared data with key '{key}' updated.");
  27. }
  28. }
  29. public object Read(string key, object defaultValue)
  30. {
  31. lock (_storage)
  32. {
  33. if (!_storage.TryGetValue(key, out var value))
  34. {
  35. return defaultValue;
  36. }
  37. return value;
  38. }
  39. }
  40. }
  41. }