参数配置文件的创建和保存
一、启动序列脚本
添加启动序列容器,并添加脚本。
脚本的作用是读取项目的配置文件,并赋值到各个变量。
下面的例子给出了,读取项目配置文件,自动启动上一次的串口,并配置变量。
- 在BeginExecute(IStepContext context, IStep step)函数中添加代码:
// 打开项目配置文件,以便读取上一次保存的设备参数
IMemento config = this.Context.OpenProjectConfiguration();
//获取串口部分参数
IMemento devConfig = config.GetChild("Devices");
IDeviceSession dev = this.Context.GetDeviceSession("串口");
if (devConfig != null)
{
IMemento dev1Config = devConfig.GetChild("串口");
dev.Address = dev1Config.GetString("Address");
dev.Parameters = dev1Config.GetString("Parameters");
}
dev.Open();
// 获取变量值
devConfig = config.GetChild("Params");
IMemento parameterCfg = devConfig.GetChild("数据1");
Context.Variants["变量容器/数据1"] = parameterCfg.GetString("Value");
parameterCfg = devConfig.GetChild("数据2");
Context.Variants["变量容器/数据2"] = parameterCfg.GetString("Value");
二、停止序列脚本
添加停止序列容器,并添加脚本。
下面的例子给出了,停止序列脚本中写项目配置文件,保存本次启动的串口,并保存变量值。
- 在BeginExecute(IStepContext context, IStep step)函数中添加代码:
// 创建和保存项目配置文件
IMemento config = this.Context.CreateProjectConfiguration();
// 保存通信接口信息
IMemento devConfig = config.CreateChild("Devices");
IMemento dev1Config = devConfig.CreateChild("串口");
IDeviceSession dev = this.Context.GetDeviceSession("串口");
dev1Config.PutString("Address",dev.Address);
dev1Config.PutString("Parameters",dev.Parameters);
//保存变量参数
devConfig = config.CreateChild("Params");
IMemento parameterConfig = devConfig.CreateChild("数据1");
Variant var = this.Context.GetVariant("变量容器/数据1");
parameterConfig.PutString("Value",var.Value.ToString());
parameterConfig = devConfig.CreateChild("数据2");
var = this.Context.GetVariant("变量容器/数据2");
parameterConfig.PutString("Value",var.Value.ToString());
devConfig = config.GetChild("Params");
// 保存文件
this.Context.SaveProjectConfiguration(config);
三、生成的配置文件
配置文件代码:
<?xml version="1.0" encoding="utf-8"?>
<Configuration>
<Devices>
<串口 Address="COM1" Parameters="Baud=9600,Parity=None,DataBits=8,StopBits=One,FlowControl=None,DtrState=False,RtsState=False" />
</Devices>
<Params>
<数据1 Value="12" />
<数据2 Value="22.2" />
</Params>
</Configuration>