當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。