No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.
 
 
 
 

48 líneas
1.6 KiB

  1. using System;
  2. using System.Collections.Generic;
  3. using Microsoft.Extensions.Logging;
  4. namespace MQTTnet.Server.Scripting.DataSharing
  5. {
  6. public class DataSharingService
  7. {
  8. private readonly Dictionary<string, object> _storage = new Dictionary<string, object>();
  9. private readonly PythonScriptHostService _pythonScriptHostService;
  10. private 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. }