本文整理汇总了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));
}
示例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 !");
}
示例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();
}
}
示例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",
示例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);
}
示例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 !");
}
示例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 {
//.........这里部分代码省略.........
示例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();
});
示例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 };
}
示例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();
}