I'm having a problem with the node-open-protocol-desoutter library in Node.js. Specifically, I'm getting the "protocol busy" error message when trying to perform screwdriving actions. What is strange is that everything goes very well for the first 5 screwing actions, but after that it fails.
I suspect that this issue may be related to the protocol being occupied or not properly closed after each action. However, I'm unsure of how to resolve this in my code.
Here's a simplified overview of my Node.js code:
const openProtocol = require('node-open-protocol-desoutter');
const { production } = require('../models');
let lastVissageData = null; // Store the last tightening data received from the controller
let opts = {
linkLayerActivate: false, // Activate the link layer
};
let globalOpts = { ip: null, port: null, pset: null, number_screw: null };
let op = null; // Store the openProtocol client
let idProductionData = null;
const updateProductionData = async (op, id, data) => {
try{
const prod = await production.findByPk(id);
if(!prod) {
return console.error(`Production with id ${id} not found`);
}
// Set the data
let newPayload = {
channelID: data.channelID,
parameterSetID: data.parameterSetID,
batchSize: data.batchSize,
batchCounter: data.batchCounter,
tighteningStatus: data.tighteningStatus,
torqueStatus: data.torqueStatus,
angleStatus: data.angleStatus,
torque: data.torque,
angle: data.angle,
timeStamp: data.timeStamp,
batchStatus: data.batchStatus,
tighteningID: data.tighteningID,
_batchStatus: data._batchStatus,
}
// Get the current payload from the production data
let payload = Array.isArray(prod.payload) ? prod.payload : [];
// Add the new payload to the production data
payload.push(newPayload)
if(data.batchCounter === data.batchSize && data._batchStatus === 1) {
await production.update({ payload: payload, status: 'ok' }, { where: { id: id }})
} else {
await production.update({ payload: payload }, { where: { id: id }})
}
} catch (err) {
console.error('Error updating production data:', err);
}
};
const connectToServer = (ip, port, pset, number_screw) => {
globalOpts = { ip, port, pset, number_screw };
op = openProtocol.createClient(port, ip, opts, (data) => {
console.log('Connected');
setupCommands(op, pset, number_screw);
});
return op;
};
const setupCommands = (op, pset, number_screw) => {
op.command("abortJob");
op.command('setPsetBatchSize', { payload: {parameterSetID: pset, batchSize: number_screw} }, (err, data) => {
if (err) {
return console.error('Error in setPsetBatchSize:', err);
}
//selectPset(op, pset);
enableTool(op);
});
};
const enableTool = (op) => {
op.command("disableTool", (err, data) => {
if (err) {
return console.log("Fail on disableTool", err);
}
op.command("enableTool", (err, data) => {
if (err) {
return console.error("Error in enableTool:", err);
}
subscribeLastTightening(op); // Subscribe to the lastTightening event after enabling the tool
});
})
};
const subscribeLastTightening = (op) => {
op.on("lastTightening", (midData) => {
console.log("Received data on subscribe", midData);
if(midData.payload.batchCounter === 1 && midData.payload._batchStatus === 1) {
lastVissageData = null; // Reset the last tightening data after the first screw has been tightened
res.send('Données de vissage réinitialisées');
}
lastVissageData = midData;
updateProductionData(op, idProductionData, midData.payload);
/*if(midData.payload.batchSize === midData.payload.batchCounter && midData.payload._batchStatus === 1) {
// Terminate the session after the last screw has been tightened
op.command('communicationStop', (err, data) => {
if (err) {
console.error("Erreur lors de l'envoi du MID d'arrêt :", err);
} else {
console.log('Session terminée proprement.');
}
});
}*/
});
op.subscribe("lastTightening", (err, data) => {
if (err) {
console.error("Error subscribing to 'lastTightening':", err);
return;
}
console.log("Subscribed to 'lastTightening'");
console.log("Data received on subscribe", data);
})
};
exports.changePset = (req, res) => {
const { ip, port, pset, number_screw, id } = req.query;
idProductionData = id;
connectToServer(ip, port, pset, number_screw); // Connect to the controller
};
exports.latestScrewing = (req, res) => {
try {
if (lastVissageData) {
res.json(lastVissageData);
// Condition pour réinitialiser ici si nécessaire
} else {
//res.status(404).send("Aucune donnée de vissage disponible.");
res.status(204).send("En attente de vissage"); // Aucune donnée de vissage disponible
}
} catch (error) {
// Gérer l'erreur ici
console.error("Une erreur s'est produite :", error);
res.status(500).send("Une erreur s'est produite lors du traitement de la demande.");
}
};
exports.resetScrewingData = (req, res) => {
/*op.command('communicationStop', (err, data) => {
if (err) {
console.error("Erreur lors de l'envoi du MID d'arrêt :", err);
} else {
op.command('disconnectTool', (err, data) => {
if (err) {
console.log('Session terminée proprement.');
}
})
}
});*/
op.on('close', (err, data) => {
if (err) {
console.error("Erreur lors de la fermeture de la connexion :", err);
} else {
console.log('Connexion fermée');
}
});
lastVissageData = null; // Réinitialiser les données de vissage
res.send(true);
idProductionData = null;
};
Could someone please advise on how to properly close the connection using the node-open-protocol-desoutter library? Any help or insights would be greatly appreciated. Thank you!