1 //
2 // Copyright (c) 2010-2022 Antmicro
3 // Copyright (c) 2011-2015 Realtime Embedded
4 //
5 // This file is licensed under the MIT License.
6 // Full license text is available in 'licenses/MIT.txt'.
7 //
8 using System;
9 using Antmicro.Renode.Core;
10 using Antmicro.Renode.Logging;
11 using Antmicro.Renode.Peripherals.CPU;
12 using Antmicro.Renode.Peripherals.UART;
13 using Antmicro.Renode.Exceptions;
14 using Antmicro.Migrant.Hooks;
15 using Microsoft.Scripting.Hosting;
16 using Antmicro.Migrant;
17 
18 namespace Antmicro.Renode.Hooks
19 {
20     public sealed class UartPythonEngine : PythonEngine
21     {
UartPythonEngine(IMachine machine, IUART uart, string script)22         public UartPythonEngine(IMachine machine, IUART uart, string script)
23         {
24             Script = script;
25             Uart = uart;
26             Machine = machine;
27 
28             InnerInit();
29 
30             Hook = line =>
31             {
32                 Scope.SetVariable("line", line);
33                 Execute(code, error =>
34                 {
35                     Uart.Log(LogLevel.Error, "Python runtime error: {0}", error);
36                 });
37             };
38         }
39 
40         [PostDeserialization]
InnerInit()41         private void InnerInit()
42         {
43             Scope.SetVariable(Core.Machine.MachineKeyword, Machine);
44             Scope.SetVariable("uart", Uart);
45             Scope.SetVariable("self", Uart);
46             var source = Engine.CreateScriptSourceFromString(Script);
47             code = Compile(source);
48         }
49 
50         public Action<string> Hook { get; private set; }
51 
52         [Transient]
53         private CompiledCode code;
54         private readonly string Script;
55         private readonly IUART Uart;
56         private readonly IMachine Machine;
57     }
58 }
59 
60