Создать переменную в Kepserver с помощью узла-opcua

У меня есть Siemens 1200 PLC. С помощью node-opcua Клиент и Kepserver Я могу читать переменные и изменять значения. Теперь я хотел бы создать новую переменную в ПЛК из node-opcua в KepServer.

Я попытался использовать сервер node-opcua, потому что в примерах я видел, как создавать переменные, но я получаю ошибку, потому что я пытаюсь подключиться к тому же порту, что и KepServer.

var server = new opcua.OPCUAServer({
    port: 49320, // the port of the listening socket of the server
    resourcePath: "", // this path will be added to the endpoint resource name
     buildInfo : {
        productName: "MySampleServer1",
        buildNumber: "7658",
        buildDate: new Date(2014,5,2)
    }
});

Как я могу иметь дело с созданием новой переменной? а создать групповой тег из node-opcua?

Возможно ли иметь сервер opcua в Kepserver и создавать переменные, подключающиеся к этому серверу напрямую? Мой Kepserver находится в: opc.tcp://localhost:49320 Для подключения к этому Kepserver я использую клиент nodeopcua:

var opcua = require("node-opcua");
var client = new opcua.OPCUAClient();
var endpointUrl = "opc.tcp://127.0.0.1:49320";
var the_session = null;
async.series([


    // step 1 : connect to
    function(callback)  {

        client.connect(endpointUrl,function (err) {

            if(err) {
                console.log(" cannot connect to endpoint :" , endpointUrl );
            } else {
                console.log("connected !");
            }
            callback(err);
        });
    },
    // step 2 : createSession
    function(callback) {
        client.createSession( function(err,session) {
            if(!err) {
                the_session = session;
            }
            callback(err);
        });

    },
    // step 3 : browse
    function(callback) {

        the_session.browse("RootFolder", function(err,browse_result,diagnostics){
            if(!err) {
                browse_result[0].references.forEach(function(reference) {
                    console.log( reference.browseName);
                });
            }
            callback(err);
        });
    },
    // step 4 : read a variable
    function(callback) {
        the_session.readVariableValue("ns=2;s=S7.1200.nombre", function(err,dataValue) {
            if (!err) {
                console.log(" temperature = " , dataValue.toString());
            }
            callback(err);
        })
    },

    // step 5: install a subscription and monitored item
    //
    // -----------------------------------------
    // create subscription
    function(callback) {

        the_subscription=new opcua.ClientSubscription(the_session,{
            requestedPublishingInterval: 1000,
            requestedLifetimeCount: 10,
            requestedMaxKeepAliveCount: 200,
            maxNotificationsPerPublish: 10,
            publishingEnabled: true,
            priority: 10
        });
        the_subscription.on("started",function(){
            console.log("subscription started for 2 seconds - subscriptionId=",the_subscription.subscriptionId);
        }).on("keepalive",function(){
            console.log("keepalive");
        }).on("terminated",function(){
            callback();
        });
        setTimeout(function(){
            the_subscription.terminate();
        },100000);


        // install monitored item
        //
        var monitoredItem  = the_subscription.monitor({
            nodeId: opcua.resolveNodeId("ns=2;s=S7.1200.nombre"),
            attributeId: 13
          //, dataEncoding: { namespaceIndex: 0, name:null }
        },
        { 
            samplingInterval: 100,
            discardOldest: true,
            queueSize: 10 
        });
        console.log("-------------------------------------");

        // subscription.on("item_added",function(monitoredItem){
        //xx monitoredItem.on("initialized",function(){ });
        //xx monitoredItem.on("terminated",function(value){ });


        monitoredItem.on("changed",function(value){
           console.log(" New Value = ",value.toString());
        });

    },

    // ------------------------------------------------
    // closing session
    //
    function(callback) {
        console.log(" closing session");
        the_session.close(function(err){

            console.log(" session closed");
            callback();
        });
    },


],
    function(err) {
        if (err) {
            console.log(" failure ",err);
        } else {
            console.log("done!")
        }
        client.disconnect(function(){});
});

Я хотел бы создать новые переменные из кода в моем Kepserver. Я видел, что с помощью кода сервера nodeopcua есть способ создания переменных: создание простого сервера

Я хотел бы использовать что-то, например, в KepServer:

server.engine.addressSpace.addVariable

Что я мог сделать, чтобы решить мою проблему?

3 ответа

Вы не можете создать тег с помощью клиента opc, но вы можете попробовать использовать инструмент Kepserverex Configuration Api Service в kepserverex. Это местоположение; Администрирование -> Настройки -> Служба конфигурации API

Вы должны включить http или https или оба из них, что вы хотите. Затем вы можете использовать устройство канала и теги с HTTPS для получения, отправки и размещения запросов.

В URL-адресе в разделе просмотра браузера также доступен документ API.

Пример;

например конечная точка для API;

http://127.0.0.1:57412/config/v1/project/channels/Channel1/devices/Device1/tags/basinc [GET]

Ответ

Когда вы отправляете результат json из запроса на получение в ту же конечную точку, что и запрос на публикацию, он добавит новый тег. (Вам нужно удалить PROJECT_ID и изменить имя тега common.ALLTYPES_NAME)

Вы не можете создавать переменные в KEPServerEx из узла- клиента opcua.

Но вам даже не нужно их создавать. Вы можете использовать функцию KEPServerEx для туннелирования переменных прямо в ПЛК. Это означает, что если вы попытаетесь прочитать переменную, которая не определена в списке серверных переменных, KEPServerEx попытается найти их в ПЛК. Таким образом, вам не нужно создавать или даже поддерживать список переменных в KEPServerEx. Просто прочитайте это клиентом с правильным адресом переменной:

session.readVariableValue("ns=2;s=Channel1.Device1.MB0", function(err,dataValue) {
   if (!err) {
      console.log("value=", dataValue.toString());
   }
}
      var server = new opcua.OPCUAServer({
    port: 49320, // the port of the listening socket of the server
    resourcePath: "", // this path will be added to the endpoint resource name
     buildInfo : {
        productName: "MySampleServer1",
        buildNumber: "7658",
        buildDate: new Date(2014,5,2)
    }
});
Другие вопросы по тегам