GUIDA PRATICA · PRECIZ
Come collegare una bilancia RAVAS 3200 a SAP tramite Wi-Fi
CloudScaleLink Neutron converte RAVAS ASCII tramite RS-232 in comandi MT-SICS selezionati su TCP/IP per collegare una bilancia esistente a SAP.
1. Una soluzione per IT e integratori
In questa installazione restano in uso la bilancia sul carrello elevatore e l’indicatore RAVAS 3200. Un’applicazione JavaScript in Neutron AppEngine converte la comunicazione per un’interfaccia di pesatura SAP che richiede MT-SICS su TCP. Neutron si collega alla rete Wi-Fi WPA3-Enterprise e opera come server TCP.
Servono un indicatore RAVAS 3200 con RS-232 bidirezionale, CloudScaleLink Neutron con AppEngine API 1 e un client TCP nel sistema di destinazione. La guida è rivolta a team IT, sviluppatori e integratori di sistemi di pesatura. A cura di PRECIZ.
La bilancia esistente rimane in uso. Neutron gestisce la rete e la conversione del protocollo.
2. Collegare RS-232 e la rete
- Impostare RAVAS 3200 su PC → bidir: 9600 baud, 8 bit dati, nessuna parità, 1 bit di stop e nessun controllo di flusso hardware. I messaggi RAVAS terminano con CR.
- Collegare CloudScaleLink Neutron alla rete Wi-Fi WPA3-Enterprise con l’autenticazione fornita dall’IT. SAP deve raggiungere l’indirizzo IP di Neutron. Manuale Neutron.
- Impostare Serial redirect → Disabled e TCP mode → Disabled, disabilitando i bridge TCP in conflitto. In Scale lasciare RS-232/UART e TCP non selezionati come interfacce di pesatura integrate. AppEngine prenderà il controllo delle porte.
RS-232: Serial redirect disabilitato; l’applicazione imposta 9600 8N1 e gestisce CR.
Modalità TCP integrata disabilitata; l’applicazione avvia il proprio server sulla porta 5000.
RS-232/UART e TCP non selezionati per il protocollo di pesatura integrato.
3. Caricare e avviare l’applicazione
Scarica l’applicazione JavaScript (.js)
Inserire in serialNumber il numero sulla targhetta, impostare l’unità fissa unit e, se necessario, modificare tcpPort (predefinito 5000). Una matricola vuota restituisce I4 I. Esempio:
tcpPort: 5000,
unit: "kg",
serialNumber: "1234"In AppEngine scegliere Upload, caricare il JS e premere Run. Dopo il test si può attivare Run automatically at device startup. L’applicazione funziona su Neutron, non nel browser. Installazione AppEngine.
AppEngine: caricamento, avvio e log con RS-232 acquisita e client TCP connesso.
4. Prima lettura da SAP o da un client TCP
Collegare il client TCP all’IP di Neutron e alla porta 5000 o configurata. Inviare I4\r\n, quindi SXI\r\n. Terminare ogni comando con CRLF e attendere la risposta completa. Per I0, la riga che inizia con I0 A conclude la risposta.
SX S G 12.5 kg N 10.0 kg T 2.5 kgSX S indica stabilità, SX D un valore dinamico. G è lordo, N netto e T tara. Lordo e netto provengono dallo stesso frame GW; la tara è la differenza. Unità e decimali seguono la configurazione dell’indicatore.
5. Comandi e risposte
Comando | Funzione | Esempio di risposta |
|---|---|---|
I0 | Elenca comandi e livelli: I0 B per righe intermedie, I0 A per l’ultima. | I0 B …; I0 A 2 "SXI" |
I4 | Restituisce la matricola inserita nella configurazione dell’applicazione. | I4 A "1234" |
S | Legge il netto stabile; dopo circa cinque secondi senza stabilità confermata restituisce S I. | S S 10.0 kg / S I |
SI | Legge il netto corrente: S S stabile, S D dinamico. | S S 10.0 kg / S D 10.0 kg |
Z | Azzera la bilancia e conferma che la tara attiva sia cancellata. | Z A |
T | Tara il carico corrente e legge la tara risultante. | T S 2.5 kg |
TA | Legge la tara; TA 2.5 kg imposta una tara predeterminata nel formato decimale supportato. | TA A 2.5 kg |
TAC | Cancella la tara attiva; TAC I indica che la cancellazione non è stata confermata. | TAC A / TAC I |
SXI | Legge lordo, netto e tara senza attendere la stabilità: SX S stabile, SX D dinamico. | SX S G 12.5 kg N 10.0 kg T 2.5 kg |
ES: comando sconosciuto o argomenti non validi. EL: coda piena. TA L: valore, precisione o unità della tara non supportati. I indica una richiesta non completata; + e - indicano sovraccarico o intervallo non valido nella lettura. L’applicazione supporta i comandi elencati.
6. Funzioni dell’applicazione
start()
Acquisisce RS-232, imposta 9600 8N1 e avvia un server TCP esclusivo.
exchange()
Invia un comando RAVAS con CR, ricompone la risposta e blocca nuove richieste dopo un timeout per non associare risposte tardive al comando sbagliato.
readWeight()
Per S e SI combina i decimali di GN con stato e valori GW verificati.
readExtendedWeight()
Per SXI usa un solo frame GW per lordo e netto, calcola la tara e controlla i decimali prima e dopo la lettura.
clearTare() / presetTare()
Verifica la cancellazione tramite il bit di stato GW e controlla unità e precisione della tara predeterminata.
respond() / drainQueue()
Mappa i comandi MT-SICS nelle operazioni RAVAS e li esegue in sequenza, senza richieste seriali sovrapposte.
7. Codice completo e download JS
Scarica l’applicazione JavaScript completa (.js)
Di seguito è riportata l’intera applicazione fornita; il download contiene lo stesso codice. Modificare la configurazione prima dell’avvio. pollMs: 100 è la pausa durante l’attesa di stabilità o conferma di un’operazione, non un flusso automatico verso SAP.
/*
* Neutron AppEngine API 1 | SAP (TCP client) <-> RAVAS 3200 (RS-232)
* RAVAS serial setup: PC -> bidir, 9600 8N1, no handshake, CR terminator.
* Neutron: disable the system RS-232 function, I_TCP weighing protocol and
* TCP bridges so AppEngine can claim both interfaces. Use an unused TCP port.
* Keep the RAVAS display unit fixed. Set unit and serialNumber below.
* SAP: send ASCII commands ending in CRLF and wait for the full reply.
*/
(function () {
"use strict";
const config = {
tcpPort: 5000,
unit: "kg",
serialNumber: "", // Enter the serial number from the indicator plate.
readTimeoutMs: 650,
operationTimeoutMs: 5500,
stableTimeoutMs: 5000,
pollMs: 100,
queueLimit: 16
};
const commands = ["I0", "I4", "S", "SI", "Z", "T", "TA", "TAC", "SXI"];
const serialPort = serial.rs232;
let pending = null;
let serialBlockedUntil = 0;
let serialLine = "";
let discardSerialLine = false;
let session = null;
let busy = false;
function receiveSerial(event) {
for (const byte of event.data) {
if (byte === 13) {
const line = serialLine.trim();
const request = pending;
if (!discardSerialLine && request &&
(request.accept(line) || /^(?:ERR|[NG]?=+|[NG]-[ -]+)$/.test(line))) {
pending = null;
request.resolve(line);
}
serialLine = "";
discardSerialLine = false;
} else if (byte !== 10 && !discardSerialLine) {
if (byte < 32 || byte > 126 || serialLine.length >= 64) {
discardSerialLine = true;
} else {
serialLine += String.fromCharCode(byte);
}
}
}
}
async function exchange(command, accept, timeoutMs = config.readTimeoutMs) {
if (Date.now() < serialBlockedUntil) {
throw new Error("RS-232 is waiting for late replies to clear");
}
serialLine = "";
discardSerialLine = false;
let timer;
const response = new Promise((resolve, reject) => {
pending = { accept, resolve };
timer = setTimeout(() => reject(new Error("No RAVAS reply to " + command)), timeoutMs);
});
try {
// Install the response handler first. The reply may arrive before write resolves.
const results = await Promise.all([
response,
serialPort.write(command + "\r", { timeoutMs: 500 })
]);
if (results[1] !== command.length + 1) throw new Error("Incomplete serial write");
return results[0];
} catch (error) {
serialBlockedUntil = Date.now() + config.operationTimeoutMs;
throw error;
} finally {
clearTimeout(timer);
pending = null;
}
}
function parseDecimal(line, prefix) {
const match = /^([NTP])([+-])(\d{1,5})(?:\.(\d{0,4}))?$/.exec(line);
if (!match || match[1] !== prefix) return null;
const integer = match[3].replace(/^0+(?=\d)/, "");
const fraction = match[4] || "";
const counts = Number(match[2] + match[3] + fraction);
return {
text: (counts < 0 ? "-" : "") + integer + (fraction ? "." + fraction : ""),
counts,
decimals: fraction.length
};
}
function parseStatus(line) {
const match = /^W([+-]\d{5})([+-]\d{5})([0-9A-F]{2})([0-9A-F]{2})$/i.exec(line);
if (!match) return null;
let sum = 0;
for (let i = 0; i < line.length - 2; i++) sum += line.charCodeAt(i);
if (((~sum) & 255) !== parseInt(match[4], 16)) return null;
return { net: Number(match[1]), gross: Number(match[2]), flags: parseInt(match[3], 16) };
}
function weightReply(id, status, value) {
return id + " " + status + " " + value.text.padStart(10, " ") + " " + config.unit;
}
async function status() {
const line = await exchange("GW", value => value.startsWith("W"));
const frame = parseStatus(line);
if (!frame) return { error: /^N?-[ -]+$/.test(line) ? "-" : "I" };
if (frame.flags & 0x04) return { error: "+" };
if (frame.flags & 0x80) return { error: "I" };
return frame;
}
async function decimal(command, prefix) {
return parseDecimal(await exchange(command, line => line.startsWith(prefix)), prefix);
}
async function readWeight(stableOnly, source) {
const deadline = Date.now() + config.stableTimeoutMs;
do {
if (session !== source) return "S I";
const before = await status();
if (before.error) return "S " + before.error;
if (!stableOnly || (before.flags & 0x10)) {
const net = await decimal("GN", "N");
if (!net) return "S I";
const after = await status();
if (after.error) return "S " + after.error;
// GN supplies the decimal point. GW supplies checked status and raw counts.
const stable = (before.flags & after.flags & 0x10) &&
before.net === net.counts && after.net === net.counts &&
before.gross === after.gross &&
((before.flags ^ after.flags) & 0x40) === 0;
if (stable) return weightReply("S", "S", net);
if (!stableOnly) return weightReply("S", "D", net);
}
const remaining = deadline - Date.now();
if (remaining <= 0) break;
await new Promise(resolve => setTimeout(resolve, Math.min(config.pollMs, remaining)));
} while (Date.now() < deadline);
return "S I";
}
async function readExtendedWeight() {
const before = await decimal("GN", "N");
const frame = await status();
if (frame.error) return "SXI " + frame.error;
const after = await decimal("GN", "N");
// GW carries gross and net in one frame. GN supplies the decimal position.
// Reject the snapshot if the displayed precision changed across the GW query.
if (!before || !after || before.decimals !== after.decimals) return "SXI I";
const stable = (frame.flags & 0x10) &&
before.counts === frame.net && after.counts === frame.net;
const scale = 10 ** after.decimals;
const fields = [["G", frame.gross], ["N", frame.net], ["T", frame.gross - frame.net]];
return "SX " + (stable ? "S" : "D") + " " + fields.map(([tag, counts]) =>
tag + " " + (counts / scale).toFixed(after.decimals).padStart(10, " ") +
" " + config.unit
).join(" ");
}
async function acknowledge(command) {
return await exchange(command, line => line === "OK", config.operationTimeoutMs) === "OK";
}
async function readTares() {
const regular = await decimal("GT", "T");
const preset = await decimal("GP", "P");
if (!regular || !preset) throw new Error("RAVAS tare is unavailable");
return { regular, preset };
}
async function currentTare() {
const { regular, preset } = await readTares();
if (regular.counts === 0) return preset;
if (preset.counts === 0 || regular.text === preset.text) return regular;
const frame = await status();
if (!frame.error) {
const active = frame.gross - frame.net;
const matchesRegular = regular.counts === active;
const matchesPreset = preset.counts === active;
if (matchesRegular !== matchesPreset) return matchesRegular ? regular : preset;
}
throw new Error("RAVAS reported two ambiguous tare values");
}
async function tareIsCleared(timeoutMs) {
const deadline = Date.now() + timeoutMs;
do {
const frame = await status();
if (!frame.error && !(frame.flags & 0x40)) return true;
const remaining = deadline - Date.now();
if (remaining <= 0) return false;
await new Promise(resolve => setTimeout(resolve, Math.min(config.pollMs, remaining)));
} while (true);
}
async function clearTare() {
if (await tareIsCleared(0)) return true;
const preset = await decimal("GP", "P");
if (preset && preset.counts !== 0) {
await acknowledge("RP");
if (await tareIsCleared(1000)) return true;
}
// A stored preset value can remain visible through GP even with no active tare.
// Use the GW tare-active bit to verify the result, allowing for the update delay.
await acknowledge("RT");
return await tareIsCleared(1000);
}
async function presetTare(argument) {
const match = /^\+?(\d{1,10})(?:\.(\d{1,8}))? +([A-Za-z]+)$/.exec(argument);
if (!match || match[3] !== config.unit) return "TA L";
const format = await decimal("GP", "P");
if (!format) return "TA I";
const integer = match[1].replace(/^0+(?=\d)/, "");
const fraction = (match[2] || "").replace(/0+$/, "");
// RAVAS requires a decimal point even when the display has no decimals.
const integerWidth = 5 - format.decimals;
if (integer.length > integerWidth || fraction.length > format.decimals) return "TA L";
const value = integer.padStart(integerWidth, "0") + "." +
fraction.padEnd(format.decimals, "0");
if (!await acknowledge("SP" + value)) return "TA I";
return weightReply("TA", "A", await currentTare());
}
async function respond(line, source) {
const match = /^([A-Z][A-Z0-9]*)(?: +(.+))?$/.exec(line.trim());
if (!match || !commands.includes(match[1])) return "ES";
const [, command, argument] = match;
if (argument && command !== "TA") return "ES";
try {
switch (command) {
case "I0":
return commands.map((name, index) =>
"I0 " + (index === commands.length - 1 ? "A" : "B") +
" " + (name === "SXI" ? "2" : index < 5 ? "0" : "1") +
' "' + name + '"').join("\r\n");
case "I4":
return config.serialNumber ? 'I4 A "' + config.serialNumber + '"' : "I4 I";
case "SI":
case "S":
return await readWeight(command === "S", source);
case "SXI":
return await readExtendedWeight();
case "Z":
if (!await acknowledge("SZ")) return "Z I";
return await clearTare() ? "Z A" : "Z I";
case "T":
if (!await acknowledge("SR")) return "T I";
return weightReply("T", "S", await currentTare());
case "TAC":
return await clearTare() ? "TAC A" : "TAC I";
case "TA":
return argument
? await presetTare(argument)
: weightReply("TA", "A", await currentTare());
}
} catch (error) {
console.warn(command + ": " + error.message);
return (command === "SI" ? "S" : command) + " I";
}
}
async function drainQueue() {
if (busy) return;
busy = true;
try {
while (session && (session.queue.length || session.rejected)) {
const source = session;
const line = source.queue.shift();
if (line === undefined) source.rejected--;
const reply = line === undefined ? "EL" : await respond(line, source);
if (source !== session) continue;
try {
await tcp.write(reply + "\r\n", { connectionId: source.id });
} catch (error) {
console.warn("TCP reply failed: " + error.message);
source.queue.length = 0;
source.rejected = 0;
}
}
} finally {
busy = false;
}
}
async function start() {
if (!/^[\x20-\x21\x23-\x7e]{0,40}$/.test(config.serialNumber) ||
!/^[A-Za-z]+$/.test(config.unit)) {
throw new Error("Check the configured MT-SICS serial number and weight unit");
}
serialPort.on("data", receiveSerial);
await serialPort.claim();
await serialPort.configure({ baudRate: 9600, dataBits: 8, stopBits: 1, parity: "none" });
tcp.on("connection", event => {
if (event.role !== "server") return;
if (event.connected) session = { id: event.connectionId, queue: [], rejected: 0 };
else if (session && session.id === event.connectionId) session = null;
});
tcp.on("line", event => {
if (!session || session.id !== event.connectionId || !event.line.trim()) return;
if (session.queue.length >= config.queueLimit || session.rejected) {
session.rejected = Math.min(session.rejected + 1, config.queueLimit);
} else {
session.queue.push(event.line);
}
drainQueue().catch(error => console.error(error.message));
});
await tcp.configure({
mode: "server",
server: { port: config.tcpPort, exclusive: true },
delimiter: "\r\n",
maxLineBytes: 128
});
await tcp.claim();
console.info("RAVAS MT-SICS bridge configured on TCP port " + config.tcpPort);
}
start().catch(error => {
console.error("RAVAS bridge startup failed: " + (error.code || "") + " " + error.message);
app.stop();
});
})();
8. Verificare la connessione
- Confermare l’identità con I4, poi confrontare peso e decimali di SXI con l’indicatore.
- Eseguire T, leggere la tara con TA e cancellarla con TAC.
- Dopo TAC A, SXI deve mostrare tara zero e lordo uguale al netto.
- Provare carichi stabili e in movimento e riconnettere il client.
Le schermate provengono da un ambiente di test. ID dispositivo, SSID, matricola 1234 e IP privato sono esempi del procedimento.
Client TCP: risposte I4, SXI, T, TA e TAC con stato stabile e dinamico.
Vuoi collegare una bilancia al tuo sistema IT?
Indicaci modello, interfaccia esistente e sistema di destinazione. PRECIZ realizza integrazioni di bilance e adattamenti della comunicazione per team IT e integratori.
Domande frequenti
È possibile collegare la bilancia tramite WebSocket?
È possibile una connessione MQTT?
La soluzione funziona con ogni sistema SAP?
La guida riguarda un’interfaccia di pesatura SAP che agisce da client TCP e richiede i comandi MT-SICS elencati. Deve supportare questi comandi, CRLF e il formato di risposta concordato. Altre interfacce SAP richiedono un adattamento.
Si possono collegare anche ERP, MES, WMS o SCADA?
Un sistema che interpreta il MT-SICS su TCP mostrato può essere il client. Per altri formati o protocolli si adatta l’applicazione AppEngine. PRECIZ può progettare la connessione in base al modello della bilancia, all’interfaccia e ai requisiti IT.
È necessario sostituire la bilancia RAVAS esistente?
No. La soluzione illustrata mantiene la bilancia e l’indicatore RAVAS 3200. CloudScaleLink Neutron aggiunge la rete e converte RAVAS ASCII da RS-232 bidirezionale nelle risposte MT-SICS indicate su TCP.
Le letture ripetute attivano stampa o subtotale?
La lettura del peso in questa applicazione usa GN e GW. Queste richieste non stampano né incrementano il subtotale. Azzeramento e operazioni di tara avvengono solo quando il client invia il comando corrispondente.
Avete bisogno di aiuto?
Vi serve aiuto con il software, la connettività o l’utilizzo di una soluzione? Descrivete il problema, così potremo aiutarvi a individuare il passo successivo.