当前位置: 首页>>代码示例>>TypeScript>>正文


TypeScript OPCUAClient.create方法代码示例

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


在下文中一共展示了OPCUAClient.create方法的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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: test1

}

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: 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

示例8: 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

示例9: replaceServerCertificateUsingPushCertificateManagerMethod

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

        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 response = await pm.createSigningRequest(
              "DefaultApplicationGroup",
              NodeId.nullNodeId,
              "CN=MyApplication");

            debugLog(" cert request status",
              response.statusCode.toString());
            if (response.statusCode !== StatusCodes.Good) {
                throw new Error("Cannot get signing request from server : " + response.statusCode.toString());
            }
            debugLog(" cert request       ",
              response.certificateSigningRequest!.toString("base64"));

            const certificateFull = await produceCertificate(response.certificateSigningRequest!);

            const certificateChain = split_der(certificateFull);
            const certificate = certificateChain[0];
            const issuerCertificates = certificateChain.slice(1);

            // generate some certificate
            const response2 = await pm.updateCertificate(
              "DefaultApplicationGroup",
              NodeId.nullNodeId,
              certificate,
              issuerCertificates
            );
            debugLog(" updateCertificate  status", response2.statusCode.toString());
            if (response2.statusCode !== StatusCodes.Good) {
                throw new Error("Cannot updateCertificate " + response2.statusCode.toString());
            }

            await pm.applyChanges();

            await session.close();

            return certificateFull;

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

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


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