• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

TypeScript node-opcua-client.OPCUAClient类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了TypeScript中node-opcua-client.OPCUAClient的典型用法代码示例。如果您正苦于以下问题:TypeScript OPCUAClient类的具体用法?TypeScript OPCUAClient怎么用?TypeScript OPCUAClient使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了OPCUAClient类的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的TypeScript代码示例。

示例1: startOnGoingConnection

    async function startOnGoingConnection(endpointUri: string) {
        onGoingClient = OPCUAClient.create({
            certificateFile: clientCertificateFile,
            privateKeyFile: clientPrivateKeyFile,

            securityMode: MessageSecurityMode.SignAndEncrypt,
            securityPolicy: SecurityPolicy.Basic256
        });
        onGoingClient.on("start_reconnection", () => {
            debugLog(chalk.bgWhite.red(" !!!!!!!!!!!!!!!!!!!!!!!!  Starting Reconnection !!!!!!!!!!!!!!!!!!!"));
        });
        onGoingClient.on("backoff", (retry: number, delay: number) => {
            debugLog(chalk.bgWhite.yellow("backoff  attempt #"), retry, " retrying in ", delay / 1000.0, " seconds");
        });
        onGoingClient.on("connection_reestablished", () => {
            debugLog(chalk.bgWhite.red(" !!!!!!!!!!!!!!!!!!!!!!!!  CONNECTION RE-ESTABLISHED !!!!!!!!!!!!!!!!!!!"));
            debugLog("    Server certificate is now ", makeSHA1Thumbprint(onGoingClient.serverCertificate!).toString("base64"));
        });
        onGoingClient.on("connection_lost", () => {
            debugLog(chalk.bgWhite.red("Client has lost connection ..."));
            debugLog(chalk.bgWhite.red("    Server certificate was ", makeSHA1Thumbprint(onGoingClient.serverCertificate!).toString("base64")));
        });

        onGoingClient.on("close", () => {
            debugLog(chalk.bgWhite.red("client has CLOOOOOOOOOOSSSSSED"));
        });

        await onGoingClient.connect(endpointUri);
        onGoingSession = await onGoingClient.createSession();

        const subscription = await onGoingSession.createSubscription2({
            requestedPublishingInterval: 500,

            maxNotificationsPerPublish: 1000,
            publishingEnabled: true,
            requestedLifetimeCount: 100,
            requestedMaxKeepAliveCount: 10
        });

        const monitoredItem = await subscription.monitor({
              attributeId: AttributeIds.Value,
              nodeId: "i=2258" // Current Time
          },
          { samplingInterval: 500 }, TimestampsToReturn.Both);

        count = 0;
        monitoredItem.on("changed", (dataValue: DataValue) => {
            debugLog(" ", chalk.cyan(dataValue.value.toString()));
            count++;
        });

        await new Promise((resolve) => setTimeout(resolve, 1500));

    }
开发者ID:node-opcua,项目名称:node-opcua,代码行数:54,代码来源:test_server_with_push_certificate_management.ts


示例2: main

async function main() {

    const connectionStrategy: ConnectionStrategyOptions = {
        initialDelay: 1000,
        maxRetry: 1
    };
    const options: OPCUAClientOptions = {
        applicationName: "ClientWithCustomDataTypeSupport",
        connectionStrategy,
        securityMode: MessageSecurityMode.None,
        // securityPolicy: SecurityPolicy.Basic256Sha256
        securityPolicy: SecurityPolicy.None
    };

    const client = OPCUAClient.create(options);

    console.log(" about to connect");
    await client.connect("opc.tcp://" + os.hostname() + ":48010");
    console.log("connected");

    client.on("backoff", () => {
        console.log("Backoff");
    });

    const session = await client.createSession();

    const variableNodeID = "ns=2;s=Demo.WorkOrder.WorkOrderVariable";

    const dataValueDataType = await session.read({ nodeId: variableNodeID, attributeId: AttributeIds.DataType });
    console.log(" DataType =", dataValueDataType.value.value.toString());
    const dataTypeNodeId = dataValueDataType.value.value as NodeId;

    await getDataTypeDefinition(session, dataTypeNodeId);

    const dataValueDataTypeBrowseName = await session.read({
        attributeId: AttributeIds.BrowseName,
        nodeId: dataValueDataType.value.value
    });
    console.log(" DataType BrowseName", dataValueDataTypeBrowseName.value.value.toString());

    const dataValue = await session.read({ nodeId: variableNodeID, attributeId: AttributeIds.Value });
    console.log(dataValue.toString());

    await session.close();

    await client.disconnect();

    console.log("Done !");
}
开发者ID:node-opcua,项目名称:node-opcua,代码行数:49,代码来源:client_with_custom_datatype.ts


示例3: testWithSimpleClient

    async function testWithSimpleClient(endpointUri: string) {

        const client = OPCUAClient.create({
            certificateFile: clientCertificateFile,
            privateKeyFile: clientPrivateKeyFile,
            securityMode: MessageSecurityMode.SignAndEncrypt,
            securityPolicy: SecurityPolicy.Basic256
        });
        try {
            await client.connect(endpointUri);
            const session = await client.createSession();

            await session.close();
        } catch (err) {
            errorLog("Cannot reconnect a client !!!! ", err.message, "\n", err);
        } finally {
            await client.disconnect();
        }

    }
开发者ID:node-opcua,项目名称:node-opcua,代码行数:20,代码来源:test_server_with_push_certificate_management.ts


示例4:

}

const connectionStrategy: ConnectionStrategyOptions = {
    initialDelay: 1000,
    maxRetry: 1
};
const options: OPCUAClientOptions = {
    applicationName: "HelloSample2",
    connectionStrategy,
    defaultSecureTokenLifetime: 10000,
    keepPendingSessionsOnDisconnect: false,
    securityMode: MessageSecurityMode.None,
    securityPolicy: SecurityPolicy.None
};

const client = OPCUAClient.create(options);

client.on("backoff", (count: number, delay: number) => {
    console.log("backoff ");
});

async function test1() {

    try {

        await client.connect("opc.tcp://opcuademo.sterfive.com:26543");

        const session: ClientSession = await client.createSession({
            type: UserTokenType.UserName,

            password: "password1",
开发者ID:node-opcua,项目名称:node-opcua,代码行数:31,代码来源:sample2Subscriptions.ts


示例5: main

async function main() {

    const connectionStrategy: ConnectionStrategyOptions = {
        initialDelay: 1000,
        maxDelay: 20000, // retry every 20 seconds
        maxRetry: 2, // maxRetry: 0xFFFFF // we need a large number here
    };

    const options: OPCUAClientOptions = {
        applicationName: "ClientBrowseNextDemo",
        connectionStrategy,
        endpoint_must_exist: false,
        keepSessionAlive: false,
        requestedSessionTimeout: 60000, // 1 minute
        securityMode: MessageSecurityMode.None,
        securityPolicy: SecurityPolicy.None,
    };

    const client = OPCUAClient.create(options);

    client.on("backoff", (retry: number, delay: number) => {
        console.log("Backoff ", retry, " next attempt in ", delay, "ms");
    });

    client.on("connection_lost", () => {
        console.log("Connection lost");
    });

    client.on("connection_reestablished", () => {
        console.log("Connection re-established");
    });

    client.on("connection_failed", () => {
        console.log("Connection failed");
    });
    client.on("start_reconnection", () => {
        console.log("Starting reconnection");
    });

    client.on("after_reconnection", (err) => {
        console.log("After Reconnection event =>", err);
    });

    await client.connect(endpointUri);

    const session = await client.createSession();

    // Note: this example demonstrate how polling can be used in OPCUA ,
    // Note that Pooling is **not** the recommended way to monitored
    // change of a UA Variable! Use Subscription instead ....
    const timerId = setInterval(async () => {

        if (client.isReconnecting) {
            console.log(" suspending OPCUA read while connection is lost");
            return;
        }
        try {
            const dataValue = await session.read({
                attributeId: AttributeIds.Value,

                nodeId: "i=2258"
            });
            console.log(dataValue.statusCode.toString(), dataValue.value.toString());
            console.log(" now un-plug and re-plug the network cable to test node-opcua automatic reconnection");
        } catch (err) {
            console.log(" Error while reading value", err.message);
        }

    }, 2000);

    setTimeout(async () => {
        clearInterval(timerId);

        await session.close();
        await client.disconnect();
        console.log("Done !");
    }, 10 * 60 * 1000);
}
开发者ID:node-opcua,项目名称:node-opcua,代码行数:78,代码来源:polling_client.ts


示例6: main

async function main() {

    const connectionStrategy: ConnectionStrategyOptions = {
        initialDelay: 1000,
        maxRetry: 1
    };
    const options: OPCUAClientOptions = {
        applicationName: "ClientBrowseNextDemo",
        connectionStrategy,
        securityMode: MessageSecurityMode.None,
        securityPolicy: SecurityPolicy.None
    };

    const client = OPCUAClient.create(options);

    await client.connect(endpointUri);

    client.on("backoff", () => {
        console.log("Backoff");
    });

    const session = await client.createSession();

    const result = await session.call({
        inputArguments: [
            new Variant({
                dataType: DataType.UInt32,
                value: 100000
            })
        ],
        methodId: addNodeMethodNodeId,
        objectId: "ns=2;s=Demo.Massfolder_Static"

    });
    console.log(result.toString());

    // now browse the 10 thousands nodes
    const nodeToBrowse: BrowseDescriptionLike = {
        nodeId: "ns=2;s=Demo.Massfolder_Static"
    };

    try {

        let browseResult = await session.browse(nodeToBrowse);
        console.log("BrowseResult = ", browseResult.toString());
        if (browseResult.statusCode === StatusCodes.Good) {
            // console.log(browseResult.toString());
            console.log("reading initial ", browseResult.references!.length, "elements");
            let continuationPoint = browseResult.continuationPoint;
            while (continuationPoint) {

                browseResult = await session.browseNext(continuationPoint, false);
                console.log("reading extra ", browseResult.references!.length);

                continuationPoint = browseResult.continuationPoint;
            }
        } else {
            console.log("BrowseResult = ", browseResult.statusCode.toString());
        }
    } catch (err) {
        console.log("err", err.message);
        console.log(err);
    }

    await session.close();

    await client.disconnect();

    console.log("Done !");
}
开发者ID:node-opcua,项目名称:node-opcua,代码行数:70,代码来源:client_browse_next_example.ts


示例7: describe

describe("Testing server configured with push certificate management", () => {

    const fakePKI = path.join(_tempFolder, "FakePKI");
    const certificateManager = new OPCUACertificateManager({
        rootFolder: fakePKI
    });

    const fakeClientPKI = path.join(_tempFolder, "FakeClientPKI");
    const clientCertificateManager = new OPCUACertificateManager({
        rootFolder: fakeClientPKI
    });
    let clientCertificateFile = "";
    let clientPrivateKeyFile = "";

    before(async () => {
        await initializeHelpers();
        await certificateManager.initialize();
    });
    before(async () => {
        await clientCertificateManager.initialize();
        clientCertificateFile = path.join(clientCertificateManager.rootDir, "certificate.pem");
        await clientCertificateManager.createSelfSignedCertificate({
            applicationUri: "ClientApplication",
            subject: "CN=Test",

            dns: [os.hostname()],
            ip: [],

            startDate: new Date(),
            validity: 10,

            outputFile: clientCertificateFile
        });
        clientPrivateKeyFile = clientCertificateManager.privateKey;
    });

    it("SCT-1 should modify a server to support push certificate management", async () => {

        const server = new OPCUAServer({
            port: 20000,
            serverCertificateManager: certificateManager,
            userCertificateManager: certificateManager
        });

        await server.initialize();

        await installPushCertificateManagementOnServer(server);

        const privateKey1PEM = await promisify(fs.readFile)(server.serverCertificateManager.privateKey, "utf8");
        const privateKey1 = convertPEMtoDER(privateKey1PEM);
        const privateKey2 = convertPEMtoDER(server.getPrivateKey());
        privateKey1.toString("base64").should.eql(privateKey2.toString("base64"));

        // now start the server
        await server.start();

        // now stop the server
        await server.shutdown();
    });

    function verifyServer(server: OPCUAServer) {

        debugLog("---------------------------------------------------------------");
        const certificateChain1 = server.getCertificateChain();
        debugLog("server.getCertificateChain() =",
          makeSHA1Thumbprint(certificateChain1).toString("hex") + " l=" + certificateChain1.length);
        const privateKey1 = convertPEMtoDER(server.getPrivateKey());
        debugLog("server.getPrivateKey()       =",
          makeSHA1Thumbprint(privateKey1).toString("hex"));

        const match = certificateMatchesPrivateKey(certificateChain1, privateKey1);
        debugLog("math                         =", match);

        for (const endpoint of server.endpoints) {
            debugLog("endpoint ", endpoint.toString());

            for (const e of endpoint.endpointDescriptions()) {
                const certificateChain3 = e.serverCertificate;
                debugLog("endpoint certificate =",
                  makeSHA1Thumbprint(certificateChain3).toString("hex") + " l=" + certificateChain3.length);
                // xx console.log(e.toString());
            }

        }
        debugLog("---------------------------------------------------------------");

    }

    async function replaceServerCertificateUsingPushCertificateManagerMethod(endpointUrl: string): Promise<Certificate> {

        const client = OPCUAClient.create({
            certificateFile: clientCertificateFile,
            privateKeyFile: clientPrivateKeyFile,

            securityMode: MessageSecurityMode.SignAndEncrypt,
            securityPolicy: SecurityPolicy.Basic256

        });

        try {
//.........这里部分代码省略.........
开发者ID:node-opcua,项目名称:node-opcua,代码行数:101,代码来源:test_server_with_push_certificate_management.ts


示例8: it

    it("SCT-3 - Client reconnection should work if server changes its private key", async () => {

        // Given a server with push management
        const server = await constructServerWithPushCertificate();
        // Given that the server is started
        await server.start();

        // Given the server connection endpoint
        const endpointUrl = server.endpoints[0].endpointDescriptions()[0].endpointUrl!;

        // Given a connected client
        const client = OPCUAClient.create({
            certificateFile: clientCertificateFile,
            privateKeyFile: clientPrivateKeyFile,

            securityMode: MessageSecurityMode.SignAndEncrypt,
            securityPolicy: SecurityPolicy.Basic256
        });

        client.on("start_reconnection", () => {
            debugLog(chalk.bgWhite.red(" !!!!!!!!!!!!!!!!!!!!!!!!  Starting Reconnection !!!!!!!!!!!!!!!!!!!"));
        });
        client.on("backoff", (retry: number, delay: number) => {
            debugLog(chalk.bgWhite.yellow("backoff  attempt #"), retry, " retrying in ", delay / 1000.0, " seconds");
        });
        client.on("connection_reestablished", () => {
            debugLog(chalk.bgWhite.red(" !!!!!!!!!!!!!!!!!!!!!!!!  CONNECTION RE-ESTABLISHED !!!!!!!!!!!!!!!!!!!"));
            debugLog("    Server certificate is now ", makeSHA1Thumbprint(client.serverCertificate!).toString("base64"));
        });
        client.on("connection_lost", () => {
            debugLog(chalk.bgWhite.red("Client has lost connection ..."));
            debugLog(chalk.bgWhite.red("    Server certificate was ", makeSHA1Thumbprint(client.serverCertificate!).toString("base64")));
        });
        client.on("close", () => {
            debugLog(chalk.bgWhite.red("Client has CLOOOOOOOOOOSSSSSED"));
        });

        await client.connect(endpointUrl);

        // When Server changes certificates
        const certificateBefore: Certificate = server.getCertificate();
        const privateKeyBefore: PrivateKeyPEM = server.getPrivateKey();

        await simulateCertificateAndPrivateKeyChange(server);

        const certificateAfter: Certificate = server.getCertificate();
        const privateKeyAfter: PrivateKeyPEM = server.getPrivateKey();

        makeSHA1Thumbprint(certificateBefore).should.not.eql(makeSHA1Thumbprint(certificateAfter));
        privateKeyBefore.should.not.eql(privateKeyAfter);

        // then I should see the client being reconnected
        await new Promise((resolve) => setTimeout(resolve, 6000));

        client.isReconnecting.should.eql(false);

        // Tear down
        await client.disconnect();
        // now stop the server
        await server.shutdown();
    });
开发者ID:node-opcua,项目名称:node-opcua,代码行数:61,代码来源:test_server_with_push_certificate_management.ts


示例9: replaceServerCertificateAndPrivateKeyUsingPushCertificateManagerMethod

    async function replaceServerCertificateAndPrivateKeyUsingPushCertificateManagerMethod(
      endpointUrl: string
    ): Promise<{ certificate: Certificate, privateKey: PrivateKey }> {

        // create a new key pair
        const { certificate, privateKey } = await produceCertificateAndPrivateKey();

        const client = OPCUAClient.create({
            certificateFile: clientCertificateFile,
            privateKeyFile: clientPrivateKeyFile,

            securityMode: MessageSecurityMode.SignAndEncrypt,
            securityPolicy: SecurityPolicy.Basic256

        });

        try {

            await client.connect(endpointUrl);

            const userIdentityToken: UserIdentityInfoUserName = {
                type: UserTokenType.UserName,

                password: "secret",
                userName: "admin"
            };

            const session = await client.createSession(userIdentityToken);

            const pm = new ClientPushCertificateManagement(session);

            const privateKeyFormat = "PEM"; // or PFX
            const issuerCertificates: Certificate[] = [];

            // generate some certificate
            const response2 = await pm.updateCertificate(
              "DefaultApplicationGroup",
              NodeId.nullNodeId,
              certificate,
              issuerCertificates,
              privateKeyFormat,
              privateKey
            );
            debugLog(" updateCertificate  status", response2.statusCode.toString());

            if (response2.statusCode === StatusCodes.Good) {
                await pm.applyChanges();
            }

            await session.close();

            if (response2.statusCode !== StatusCodes.Good) {
                throw new Error("Cannot updateCertificate " + response2.statusCode.toString());
            }

        } catch (err) {
            console.log("err =", err);
            throw err;
        } finally {
            await client.disconnect();
        }

        return { certificate, privateKey };

    }
开发者ID:node-opcua,项目名称:node-opcua,代码行数:65,代码来源:test_server_with_push_certificate_management.ts


示例10: stopOnGoingConnection

    async function stopOnGoingConnection() {

        debugLog("stopping");
        await new Promise((resolve) => setTimeout(resolve, 5000));
        debugLog("stopOnGoingConnection - Server certificate is now ",
          makeSHA1Thumbprint(onGoingClient.serverCertificate!).toString("base64"));
        await onGoingSession.close();
        await onGoingClient.disconnect();
    }
开发者ID:node-opcua,项目名称:node-opcua,代码行数:9,代码来源:test_server_with_push_certificate_management.ts



注:本文中的node-opcua-client.OPCUAClient类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap