Created
March 19, 2024 19:02
-
-
Save kaiomagalhaes/4cb454ca21b76a3afa114c0986b6bd22 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const opcua = require("node-opcua"); | |
const { MongoClient } = require("mongodb"); | |
// MongoDB configuration with your provided URI | |
const mongoUrl = "YOUR_MONGO_URL; | |
const dbName = "YOUR_DB_NAME"; // Database name, adjusted to match your URI | |
const collectionName = "lux"; // Collection name for storing lux values | |
(async () => { | |
// Initialize OPC UA server | |
const server = new opcua.OPCUAServer({ | |
port: 4840, | |
resourcePath: "/UA/MyLittleServer", | |
}); | |
await server.initialize(); | |
const addressSpace = server.engine.addressSpace; | |
const namespace = addressSpace.getOwnNamespace(); | |
// Add a new object to the server | |
const device = namespace.addObject({ | |
organizedBy: addressSpace.rootFolder.objects, | |
browseName: "MyDevice", | |
}); | |
// Add a variable that represents the LuxValue | |
namespace.addVariable({ | |
componentOf: device, | |
nodeId: "ns=1;s=the.node.identifier", | |
browseName: "LuxValue", | |
dataType: "Double", | |
value: { | |
get: () => new opcua.Variant({ dataType: opcua.DataType.Double, value: 0 }), | |
set: async (variant) => { | |
const luxValue = variant.value; | |
const client = new MongoClient(mongoUrl); // Moved inside the set function | |
try { | |
await client.connect(); // Connect to MongoDB for each insert operation | |
console.log("Connected to MongoDB for a new insert operation."); | |
const db = client.db(dbName); | |
const collection = db.collection(collectionName); | |
await collection.insertOne({ | |
nodeId: "ns=1;s=the.node.identifier", | |
luxValue: luxValue, | |
timestamp: new Date() | |
}); | |
console.log("New Lux value inserted into MongoDB."); | |
} catch (error) { | |
console.error("Error inserting into MongoDB:", error); | |
} finally { | |
await client.close(); // Close the MongoDB connection | |
console.log("Disconnected from MongoDB after the insert operation."); | |
} | |
return opcua.StatusCodes.Good; | |
} | |
} | |
}); | |
await server.start(); | |
console.log(`Server is now listening on port ${server.endpoints[0].port}...`); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment