25'ten fazla konu seçemezsiniz Konular bir harf veya rakamla başlamalı, kısa çizgiler ('-') içerebilir ve en fazla 35 karakter uzunluğunda olabilir.
 
 
 
 

131 satır
4.5 KiB

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Dynamic;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Text;
  7. using Microsoft.Extensions.Logging;
  8. using Microsoft.Scripting;
  9. using Microsoft.Scripting.Hosting;
  10. namespace MQTTnet.Server.Scripting
  11. {
  12. public class PythonScriptHostService
  13. {
  14. private readonly IDictionary<string, object> _proxyObjects = new ExpandoObject();
  15. private readonly List<PythonScriptInstance> _scriptInstances = new List<PythonScriptInstance>();
  16. private readonly ILogger<PythonScriptHostService> _logger;
  17. private readonly ScriptEngine _scriptEngine;
  18. public PythonScriptHostService(PythonIOStream pythonIOStream, ILogger<PythonScriptHostService> logger)
  19. {
  20. _logger = logger ?? throw new ArgumentNullException(nameof(logger));
  21. _scriptEngine = IronPython.Hosting.Python.CreateEngine();
  22. _scriptEngine.Runtime.IO.SetOutput(pythonIOStream, Encoding.UTF8);
  23. }
  24. public void Configure()
  25. {
  26. AddSearchPaths(_scriptEngine);
  27. var scriptsDirectory = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Scripts");
  28. foreach (var filename in Directory.GetFiles(scriptsDirectory, "*.py", SearchOption.AllDirectories).OrderBy(file => file))
  29. {
  30. TryInitializeScript(filename);
  31. }
  32. }
  33. public void RegisterProxyObject(string name, object @object)
  34. {
  35. if (name == null) throw new ArgumentNullException(nameof(name));
  36. if (@object == null) throw new ArgumentNullException(nameof(@object));
  37. _proxyObjects.Add(name, @object);
  38. }
  39. public void InvokeOptionalFunction(string name, object parameters)
  40. {
  41. if (name == null) throw new ArgumentNullException(nameof(name));
  42. lock (_scriptInstances)
  43. {
  44. foreach (var pythonScriptInstance in _scriptInstances)
  45. {
  46. try
  47. {
  48. pythonScriptInstance.InvokeOptionalFunction(name, parameters);
  49. }
  50. catch (Exception exception)
  51. {
  52. _logger.LogError(exception, $"Error while invoking function '{name}' at script '{pythonScriptInstance.Name}'.");
  53. }
  54. }
  55. }
  56. }
  57. private void TryInitializeScript(string filename)
  58. {
  59. try
  60. {
  61. var scriptName = new FileInfo(filename).Name;
  62. _logger.LogTrace($"Initializing Python script '{scriptName}'...");
  63. var code = File.ReadAllText(filename);
  64. var scriptInstance = CreateScriptInstance(scriptName, code);
  65. scriptInstance.InvokeOptionalFunction("initialize");
  66. _scriptInstances.Add(scriptInstance);
  67. _logger.LogInformation($"Initialized script '{scriptName}'.");
  68. }
  69. catch (Exception exception)
  70. {
  71. _logger.LogError(exception, $"Error while initializing script '{new FileInfo(filename).Name}'.");
  72. }
  73. }
  74. private PythonScriptInstance CreateScriptInstance(string name, string code)
  75. {
  76. var scriptScope = _scriptEngine.CreateScope();
  77. var source = scriptScope.Engine.CreateScriptSourceFromString(code, SourceCodeKind.File);
  78. var compiledCode = source.Compile();
  79. scriptScope.SetVariable("mqtt_net_server", _proxyObjects);
  80. compiledCode.Execute(scriptScope);
  81. return new PythonScriptInstance(name, scriptScope);
  82. }
  83. private void AddSearchPaths(ScriptEngine scriptEngine)
  84. {
  85. var paths = new List<string>
  86. {
  87. Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Lib"),
  88. "/usr/lib/python2.7",
  89. @"C:\Python27\Lib"
  90. };
  91. AddSearchPaths(scriptEngine, paths);
  92. }
  93. private void AddSearchPaths(ScriptEngine scriptEngine, IEnumerable<string> paths)
  94. {
  95. var searchPaths = scriptEngine.GetSearchPaths();
  96. foreach (var path in paths)
  97. {
  98. if (Directory.Exists(path))
  99. {
  100. searchPaths.Add(path);
  101. _logger.LogInformation($"Added Python lib path: {path}");
  102. }
  103. }
  104. scriptEngine.SetSearchPaths(searchPaths);
  105. }
  106. }
  107. }