node-opcua @ https://github.com/node-opcua/node-opcua上的例子表明,我需要为添加到OPC服务器的每个变量重写代码,这是通过调用‘addressSpace.addVariable()’实现的……但如果我有1000个变量,这可能是一项艰巨的任务……最终,每个自定义用户都想要重写代码,这可能会很乏味……所以我试着动态地做。
opc从另一个自定义服务器(不是OPC)读取“标记”。
有了这个“标签”,opc服务器需要将它们添加到节点“设备”中。
当OPC服务器node-opcua找到来自网络的get或set变量时,它调用正确变量的get或set:
for (var i = 0; i < tags.GetTags.length; i++)
{
variables[tags.GetTags[i].Tag] = {"value" : 0.0, "is_set" : false};
addressSpace.addVariable({
componentOf: device, // Parent node
browseName: tags.GetTags[i].Tag, // Variable name
dataType: "Double", // Type
value: {
get: function () {
//console.log(Object.getOwnPropertyNames(this));
return new opcua.Variant({dataType: opcua.DataType.Double, value: variables[this["browseName"]].value }); // WORKS
},
set: function (variant) {
//console.log(Object.getOwnPropertyNames(this));
variables[this["browseName"]].value = parseFloat(variant.value); // this["browseName"] = UNDEFINED!!!
variables[this["browseName"]].is_set = true;
return opcua.StatusCodes.Good;
}
}
});
console.log(tags.GetTags[i].Tag);
}正如我所说的,我试图在get和set函数中使用'this‘,get有一个'this.browseName’(标记名)属性,可以用来动态读取我的变量,目前它可以工作。
问题出在集合上,集合中的'this.browseName‘和'this.nodeId’不存在!所以它会给出“未定义”的错误。它也不存在于变量变量中。
你知道在上面的代码中使用动态变量的变通方法吗?我需要有一个for循环,其中一个get和一个set定义用于所有变量(标签),读写一个多属性对象或一个对象数组,就像在n个记录数组中写入正确变量的1get和1set定义一样。
PS:我在堆栈溢出上发现了这个:
var foo = { a: 5, b: 6, init: function() { this.c = this.a + this.b; return this; } }
但在我的例子中,node-opcua变量没有'this‘这样的工作方式。在'set‘中(如init):this.browseName (如a)和this.nodeId (如b)是不可达的。
发布于 2016-10-17 01:21:03
抓到你了,
您需要将get和set属性转换为如下函数:
addressSpace.addVariable({
componentOf: device,
browseName: _vars[i].Tag,
dataType: "Double",
value: {
get: CastGetter(i),
set: CastSetter(i)
}
});使用
function CastGetter(index) {
return function() {
return new opcua.Variant({dataType: opcua.DataType.Double, value: opc_vars[index].Value });
};
}
function CastSetter(index) {
return function (variant) {
opc_vars[index].Value = parseFloat(variant.value);
opc_vars[index].IsSet = true;
return opcua.StatusCodes.Good;
};
}您将使用索引来获取和设置数组中的值,像这样的强制转换函数将在这些get和set属性中提供“硬编码”的索引。
https://stackoverflow.com/questions/39965968
复制相似问题