We will use the scripting module to build a custom REST API server. This server will be designed to accept POST requests sent from the URL of a web browser. Upon receiving the request, we will parse the sent data and process it in vNode. This information will be stored both in individual tags and in a JSON-formatted tag within vNode. This approach allows us to efficiently capture and manage data coming from POST requests in a structured manner.
Code:
const http = require('http');
const { URLSearchParams } = require('url');
const serverConfig = {
host: "0.0.0.0",
port: 3000,
user: "admin",
pass: "vnode"
};
const server = http.createServer((request, response) => {
const { headers, method, url } = request;
request.setTimeout(10000, function() {
response.end("Timeout!!");
request.abort();
});
// Ignore favicon.ico requests
if (url === '/favicon.ico') {
response.writeHead(404, { 'Content-Type': 'text/plain' });
response.end();
return;
}
const params = new URLSearchParams(url.split('/')[1]);
$.logger.debug("This is the URL: " + url);
// Get date and time:
const dateTime = params.get('dateTime');
$.logger.debug("The date and time is: " + dateTime);
// Log parameters on the server
const equipment = params.get('equipment');
$.logger.debug("The equipment is: " + equipment);
$.api.tag.update('/TAGS_URL/equipment', "" + equipment, 192, dateTime);
const netWeight = params.get('netWeight');
$.logger.debug("The net weight is: " + netWeight);
$.api.tag.update('/TAGS_URL/netWeight', netWeight, 192, dateTime);
const maxWeight = params.get('maxWeight');
$.logger.debug("The max weight is: " + maxWeight);
$.api.tag.update('/TAGS_URL/maxWeight', maxWeight, 192, dateTime);
const minWeight = params.get('minWeight');
$.logger.debug("The min weight is: " + minWeight);
$.api.tag.update('/TAGS_URL/minWeight', minWeight, 192, dateTime);
const tareWeight = params.get('tareWeight');
$.logger.debug("The tare weight is: " + tareWeight);
$.api.tag.update('/TAGS_URL/tareWeight', tareWeight, 192, dateTime);
const sku = params.get('sku');
$.logger.debug("The SKU is: " + sku);
$.api.tag.update('/TAGS_URL/sku', sku, 192, dateTime);
// Send acknowledgment message to the browser
response.writeHead(200, { 'Content-Type': 'text/plain' });
response.end("OK!!");
// Convert parameters into a JSON object
const paramsJson = {};
params.forEach((value, key) => {
paramsJson[key] = value;
});
const jsonParams = JSON.stringify(paramsJson);
$.logger.debug("The JSON is: " + jsonParams);
// Update a tag with the JSON string
$.api.tag.update('/TAGS_URL/JSONTAG', jsonParams, 192, dateTime);
});
server.listen(serverConfig.port, function() {
$.logger.debug('Server listening on port ' + serverConfig.port);
});
Created by JF Solano