Files
IOT_SIM/runtime/Sim.Runner/StudentProgramHost.cs
T
xuyueandClaude Opus 5.5 6b088240da
CI/CD / test (push) Canceled after 0s
CI/CD / deploy (push) Canceled after 0s
项目 4 任务 2 网络摄像机:PictureBox、Image / Bitmap、照片列表
- 摄像头:自绘东围墙场景(Camera/scene.svg),按云台位置切成 640×480 帧(build-frames.ts);
  Pan 每次转一格,红外对射被遮挡时画面出现翻墙的人;类名、委托、事件参数与教材 dll 一致,
  ImageRead 每 250 ms 在后台线程触发
- Image / Bitmap 保存真实图片数据:Save、FromFile、FromStream,文件夹不存在时报 GDI+ 一般性错误;
  图片每张只发给浏览器一次(按内容哈希缓存)
- 程序所在目录(AppDomain.CurrentDomain.BaseDirectory,编译检查单独放行)和当前目录指向可写的 bin/Debug,
  沙箱里在沙箱的临时目录
- PictureBox(SizeMode、BorderStyle);设计器工具箱加"图片框";运行区显示程序保存的图片,点开看大图;
  实训台摄像头图标显示开启状态
- 评分规则加图片框显示图片、摄像头开关与转向、保存图片三种检查;示例 p4-t2-网络摄像机
- 测试:摄像头端到端、图片读写与程序目录、AppDomain 编译检查、评分出错情况

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 20:58:09 +08:00

145 lines
5.5 KiB
C#

using System;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Runtime.Loader;
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Threading;
using System.Windows.Forms;
using Sim.Host;
namespace Sim.Runner;
/// <summary>
/// 运行一个已编译的学生程序:在模拟的界面线程上执行 Main,主线程从标准输入读取浏览器的操作。
/// 这个类不能引用 Roslyn 的任何类型,否则运行模式也会加载编译器。
/// </summary>
internal static class StudentProgramHost
{
public static int Run(string dir)
{
var processStart = Process.GetCurrentProcess().StartTime;
SimHost.Initialize(Console.OpenStandardOutput());
var console = new ConsoleForwarder();
Console.SetOut(console);
Console.SetIn(TextReader.Null); // 标准输入用于协议,学生的 Console.ReadLine 读不到内容
// 和中文 Windows 一致:DateTime.ToString() 等按 zh-CN 格式输出
var zhCN = CultureInfo.GetCultureInfo("zh-CN");
CultureInfo.DefaultThreadCurrentCulture = zhCN;
CultureInfo.DefaultThreadCurrentUICulture = zhCN;
CultureInfo.CurrentCulture = zhCN;
CultureInfo.CurrentUICulture = zhCN;
UseWritableBaseDirectory(dir);
var assembly = AssemblyLoadContext.Default.LoadFromStream(
new MemoryStream(File.ReadAllBytes(Path.Combine(dir, CompileServer.AssemblyFile))),
new MemoryStream(File.ReadAllBytes(Path.Combine(dir, CompileServer.PdbFile))));
SimHost.StudentAssembly = assembly;
var entryPoint = assembly.EntryPoint;
if (entryPoint == null)
{
SimHost.Send(new JsonObject { ["type"] = "exception", ["message"] = "程序中找不到 Main 方法", ["detail"] = "" });
return 1;
}
AppDomain.CurrentDomain.UnhandledException += (_, e) =>
{
// 学生创建的后台线程抛出未处理异常时,和真实程序一样整个程序结束
if (e.ExceptionObject is Exception ex) SimHost.ReportException(ex);
console.Flush();
};
var uiThread = new Thread(() =>
{
SimHost.Ui.BindToCurrentThread();
SynchronizationContext.SetSynchronizationContext(new WindowsFormsSynchronizationContext());
SimHost.Send(new JsonObject { ["type"] = "started", ["ms"] = (long)(DateTime.Now - processStart).TotalMilliseconds });
try
{
var parameters = entryPoint.GetParameters().Length == 0 ? null : new object[] { Array.Empty<string>() };
entryPoint.Invoke(null, parameters);
}
catch (Exception ex)
{
SimHost.ReportException(ex);
}
finally
{
console.Flush();
SimHost.FlushChanges();
Environment.Exit(0);
}
}) { Name = "UI" };
uiThread.Start();
ReadActions();
// 服务器关闭了标准输入:结束运行
Environment.Exit(0);
return 0;
}
/// <summary>
/// 学生程序的"程序所在目录":和在 VS 里按 F5 一样是工程下的 bin/Debug/,也是当前目录,可以写文件
/// (教材把摄像头照片存到 AppDomain.CurrentDomain.BaseDirectory + "Camera/")。
/// 沙箱里工程目录只读,改用沙箱自己的临时目录;两种情况下文件都在程序结束后清掉。
/// </summary>
private static void UseWritableBaseDirectory(string projectDir)
{
string baseDir;
try
{
baseDir = Directory.CreateDirectory(Path.Combine(projectDir, "bin", "Debug")).FullName;
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
baseDir = Directory.CreateDirectory(Path.Combine(Path.GetTempPath(), "StudentApp", "bin", "Debug")).FullName;
}
baseDir = Path.TrimEndingDirectorySeparator(baseDir) + Path.DirectorySeparatorChar;
AppContext.SetData("APP_CONTEXT_BASE_DIRECTORY", baseDir);
Directory.SetCurrentDirectory(baseDir);
SimHost.AppBaseDirectory = baseDir;
}
/// <summary>读取浏览器发来的操作,排队到界面线程执行</summary>
private static void ReadActions()
{
using var input = new StreamReader(Console.OpenStandardInput(), new UTF8Encoding(false));
while (input.ReadLine() is { } line)
{
JsonObject? message;
try
{
message = JsonNode.Parse(line) as JsonObject;
}
catch (JsonException)
{
continue;
}
switch ((string?)message?["type"])
{
case "action":
if (SimHost.FindControl((string?)message!["id"] ?? "") is { } control)
{
var action = UserAction.FromJson(message);
SimHost.Ui.Post(() => control.PerformUserAction(action));
}
break;
case "board":
DeviceCtrlLibrary.TrainingBoard.Update(message!);
break;
case "reply":
SimHost.CompleteRequest((int?)message!["requestId"] ?? 0, message["result"]?.DeepClone());
break;
case "stop":
Environment.Exit(0);
break;
}
}
}
}