首页 > 解决方案 > 使用 XML 并向其中添加 c# 逻辑以进行配置

问题描述

我正在开发软件来配置设备以通过 CANOpen 进行通信。在 CANOpen 中有一个对象字典 (OD) 的概念,它在消费者和生产者之间共享。它充当通信端点之间的合同。

为了自定义我们想要在应用程序中可视化的内容,我们正在构建一个 XML 配置文件。一个例子是可以在设备上执行的命令。例如,您需要将机器人的手臂向上移动 500 毫米。然后我希望能够将此命令定义为“移动臂 Z 轴”并指定具有特定约束(最小值、最大值等)的特定类型的参数。

我想采用的方法是使用每个设备的 xml 文件,其中可以定义所有这些步骤。然而,它确实需要我使用特定的解析规则在 xml 中编写 c# 代码,例如任何代码都应该在“{{”“}}”括号之间或使用特定元素(例如<SetVariable>)。

<?xml version="1.0" encoding="UTF-8"?>
<DeviceConfiguration>
  <Device name="CanOpenDevice1" />
  <ParameterConfiguration>
    <EntreesToExclude>
      <EntryToExclude Index="0x206B" />
      <EntryToExclude Index="0x2050" />
      <EntryToExclude Index="0x20F1" />
      <EntryToExclude Index="0x20F4" />
    </EntreesToExclude>
    <WriteToFlashCommand>
      <WriteCommand Label="Write to Flash" Index="0x3000" SubIndex="0x0F" Value="0x000000FF" />
    </WriteToFlashCommand>
  </ParameterConfiguration>
  <CommandConfiguration>
    <Commands>
      <WriteCommand Label="Connect Request ON" Index="0x20F2" Value="true" DataType="bool" />
      <WriteCommand Label="Connect Request OFF" Index="0x20F2" Value="false" DataType="bool" />
      <WriteCommand Label="Clear Faults" Index="0x2050" SubIndex="0x01" Value="0x66726c63" DataType="uint" />
      <WriteCommand Label="Reboot" Index="0x2050" SubIndex="0x02" Value="0x00747372" DataType="uint" />
      <!-- Executes in sequential order -->
      <CommandInstructionSet Label="Sync RTC">
        <SetVariable Name="now" Value="{{System.Datetime.UtcNow}}" />
        <WriteCommand Index="0x206B" SubIndex="0x05" Value="{{$now.Second}}" DataType="ushort" />
        <WriteCommand Index="0x206B" SubIndex="0x06" Value="{{$now.Minute}}" DataType="ushort" />
        <WriteCommand Index="0x206B" SubIndex="0x07" Value="{{$now.Hour}}" DataType="ushort" />
        <WriteCommand Index="0x206B" SubIndex="0x08" Value="{{$now.Day}}" DataType="ushort" />
        <WriteCommand Index="0x206B" SubIndex="0x09" Value="{{$now.Month}}" DataType="ushort" />
        <WriteCommand Index="0x206B" SubIndex="0x0A" Value="{{$now.Year - 2000}}" DataType="ushort" />
        <WriteCommand Index="0x206B" SubIndex="0x0B" Value="{{System.DateTime.IsLeapYear($now.Year)}}" DataType="ushort" />
        <WriteCommand Index="0x206B" SubIndex="0x0C" Value="{{$now.DayOfWeek}}" DataType="ushort" />
        <WriteCommand Index="0x206B" SubIndex="0x0E" Value="0x12345678" DataType="uint" />
      </CommandInstructionSet>

      <ReadCommand Label="Reboot" Index="0x2050" SubIndex="0x02" DataType="uint" />
    </Commands>
  </CommandConfiguration>
</DeviceConfiguration>

这个想法是在解析语法后使用 Roslyn 脚本 api 来执行和评估代码。

我想知道您的想法,以及您是否知道处理此案的更好方法。我有一个问题是我有有限的方法来防止恶意代码潜入。然而,代码只能在本地机器上运行,而不是在云或另一台服务器上,所以你只会弄乱你自己的设备.

标签: c#xmlparsingroslyncanopen

解决方案


推荐阅读