WEIGHING TECHNOLOGY · IN-HOUSE DEVELOPMENT · SUPPORT
+386 2 320 33 46info@preciz.si

PRACTICAL GUIDE · PRECIZ

How to connect Neutron scales using Bluetooth BLE

Neutron NS/NT · Bluetooth BLE · JavaScript

1. What you need and how the example is organized

Connect Neutron NS and NT scales to a browser using Bluetooth Low Energy (BLE), then exchange commands and responses using CSCP. This example is for developers, integrators and anyone building their own scale application.

Use a Web Bluetooth browser and serve the page over HTTPS or localhost. Enable Bluetooth and select the scale from a button click. Disconnect it from another application first if that application is using it.

The examples below use the NeutronBle class. The variable ble is one instance shared by all methods. The class handles the BLE connection, CSCP commands and response parsing.

  • Service: 49535343-fe7d-4ae5-8fa9-9fafd205e455
  • Write, application → scale: 49535343-8841-43f4-a8d4-ecbe34729bb3
  • Notify, scale → application: 49535343-1e4d-4bd9-ba61-23c647249616

Include the class first. Download the neutron-ble.js class and save the file in the same folder as app.js. Add this at the start of app.js:

import { NeutronBle } from './neutron-ble.js';

// Create one shared instance for all seven methods.
const ble = new NeutronBle();

In HTML, include <script type="module" src="./app.js"></script>. No npm installation or external dependencies are needed. Keep the filename neutron-ble.js. Use one ble instance for all functions below. The complete class source is also shown in chapter 14.

2. connect() — connect the scale

Before using this method: Download the neutron-ble.js class, import it with import { NeutronBle } from './neutron-ble.js' and create const ble = new NeutronBle() once, as shown in chapter 1. Add the function to the same app.js.

This method opens the device chooser, establishes GATT and enables BLE notifications. Call it from a button click; the browser does not open device selection automatically on page load.

async function connect() {
  // Open the browser device chooser from a button click.
  return ble.connect();
}

The transport performs three connection steps: getPrimaryService(), getCharacteristic() for write and notify, and startNotifications(). The receiver is attached before notifications are enabled so the first response is not lost.

3. disconnect() — close the connection

Before using this method: Download the neutron-ble.js class, import it with import { NeutronBle } from './neutron-ble.js' and create const ble = new NeutronBle() once, as shown in chapter 1. Add the function to the same app.js.

Stop repeated requests first, then close GATT. Disconnecting does not change scale settings. Mark the displayed measurements as last readings rather than current values after disconnection.

function disconnect() {
  // Close the Bluetooth GATT connection.
  ble.disconnect();
}

4. read() — net, gross, tare and stability

Before using this method: Download the neutron-ble.js class, import it with import { NeutronBle } from './neutron-ble.js' and create const ble = new NeutronBle() once, as shown in chapter 1. Add the function to the same app.js.

read() sends QASI1C followed by CRLF and waits for one response. The returned object contains net, gross, tare, unit, stability, channel, range and error.

async function read() {
  // QASI1C: read net, gross, tare, unit and stability together.
  const value = await ble.read();
  console.log(value.net, value.gross, value.tare, value.unit, value.stability);
  return value;
}

Display net, gross and tare from the same response, without recalculating or changing decimal precision. S means stable, D dynamic, + overload and - underload. Scale status 1 means no error. See the QASI1/QASI1C reference for the full field order and units.

5. tare() — tare the current load

Before using this method: Download the neutron-ble.js class, import it with import { NeutronBle } from './neutron-ble.js' and create const ble = new NeutronBle() once, as shown in chapter 1. Add the function to the same app.js.

Place the container on the scale and call tare(). It sends T, waits for confirmation and returns a new measurement. T S 0.50 kg is an example of successful stable tare. T I is not success: the scale cannot execute the command now or did not stabilize within its command window.

async function tare() {
  // T: use the current load as tare, then read the new values.
  await ble.tare();
  return ble.read();
}

See T – tare for every response.

6. clearTare() — clear tare

Before using this method: Download the neutron-ble.js class, import it with import { NeutronBle } from './neutron-ble.js' and create const ble = new NeutronBle() once, as shown in chapter 1. Add the function to the same app.js.

clearTare() sends TAC. It removes the current tare, whether measured or preset. TAC A confirms completion; TAC I means the command is not executable now. read() then refreshes net, gross and tare.

async function clearTare() {
  // TAC: clear the tare value, then read the new values.
  await ble.clearTare();
  return ble.read();
}

7. setTare(value, unit) — enter a known tare

Before using this method: Download the neutron-ble.js class, import it with import { NeutronBle } from './neutron-ble.js' and create const ble = new NeutronBle() once, as shown in chapter 1. Add the function to the same app.js.

For a known container mass use setTare("0.5", "kg") when the scale reports kg. This sends TA 0.5 kg. The example accepts a decimal point or comma and transmits a decimal point.

async function setTare(value, unit = 'kg') {
  // TA: preset a tare value, for example setTare(0.5, 'kg').
  await ble.setTare(String(value), unit);
  return ble.read();
}

TA A with value and unit confirms the applied tare. The scale may round it to its division, so refresh with read(). TA L means the command is not executable, for example due to syntax, value or unit. See TA for details.

8. zero() — zero the scale

Before using this method: Download the neutron-ble.js class, import it with import { NeutronBle } from './neutron-ble.js' and create const ble = new NeutronBle() once, as shown in chapter 1. Add the function to the same app.js.

Remove the load and call zero(). Z respects the scale zeroing range and stability conditions. Z A confirms success. Read a new measurement after confirmation.

async function zero() {
  // Z: zero the scale, then read the new values.
  await ble.zero();
  return ble.read();
}

9. Continuous reading: default 50 ms delay

The application sends QASI1C, processes the response, waits 50 ms and then sends the next request. Only one request is in flight. The switch enables or disables the loop; switching off does not discard a response to an already sent request.

function stopReading() {
  polling = false;
  generation++;
  clearTimeout(timer);
  $('continuous').checked = false;
  controls();
}
async function loop(token) {
  if (!polling || token !== generation) return;
  try {
    await read(); // Finish the reply before the next 50 ms delay starts.
    if (polling && token === generation) timer = setTimeout(() => loop(token), POLL_DELAY_MS);
  } catch (error) { fail(error); }
}
function startReading() {
  polling = true;
  $('continuous').checked = true;
  controls();
  void loop(++generation);
}

POLL_DELAY_MS = 50 is the delay after a response, not the response timeout. The transport waits up to 5 s for a read reply and 30 s for tare/zero operations. These are separate application settings and do not change scale configuration. The actual cycle also includes processing and BLE transmission time.

10. What ES, T I and other responses mean

  • ES: syntax error or unknown command. General error message.
  • T S …: successful tare with a stable value. T I: not executable now or the stability wait expired. T +: tare exceeds capacity; T -: negative tare. T responses.
  • TAC A: tare cleared. TAC I: cannot clear tare now. TAC responses.
  • TA A …: preset tare confirmed. TA I: not executable now. TA L: invalid syntax, value or unit. TA responses.
  • QASI I: the scale cannot return data now. QASI1C response.

Every command and response ends with \r\n (CRLF, ASCII 13 and 10). Spaces in examples are real spaces; ˽ in the manual denotes a space. QASI1C data fields are comma-separated. See CSCP command/response structure. Sending a command alone is not proof of success: the scale must confirm it.

11. Complete demo application (ZIP) and index.html

Download the complete demo application (ZIP). The package contains index.html, neutron.css, app.js, neutron-ble.js and README.txt with startup instructions.

Extract the ZIP into one folder. Start a local web server in that folder, for example with Python 3: python3 -m http.server 8000 --bind 127.0.0.1 (on Windows you can use py -m http.server 8000 --bind 127.0.0.1). Open http://127.0.0.1:8000 in a Web Bluetooth browser, enable Bluetooth and click Connect. You can also host the application over HTTPS. Do not open the files directly using file://.

To assemble the example manually, create four files: index.html, neutron.css, app.js and neutron-ble.js. The HTML below defines the display and buttons; CSS, application logic and the class follow in separate chapters.

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width,initial-scale=1">
  <title>Neutron BLE · CSCP</title>
  <link rel="stylesheet" href="neutron.css">
</head>
<body>
  <main class="demo-site">
    <h1>Neutron BLE · CSCP</h1>
    <div class="ble-console">
      <section>
        <h2>Connection</h2>
        <p id="status" role="status">Disconnected</p>
        <div class="ble-actions">
          <button class="button" id="connect">Connect</button>
          <button class="button secondary" id="disconnect" data-scale>Disconnect</button>
        </div>
      </section>
      <section>
        <h2>Measurements</h2>
        <dl id="measurements" class="ble-readings ble-stale">
          <div><dt>Net</dt><dd id="net">—</dd></div>
          <div><dt>Gross</dt><dd id="gross">—</dd></div>
          <div><dt>Tare</dt><dd id="tare">—</dd></div>
        </dl>
        <p id="stability" class="ble-stability" role="status">—</p>
        <div class="ble-actions">
          <button class="button secondary" id="once" data-scale>Read once</button>
          <label class="ble-switch"><input id="continuous" type="checkbox" data-scale>Continuous QASI1C · 50 ms delay</label>
        </div>
      </section>
      <section>
        <h2>Scale operations</h2>
        <div class="ble-actions">
          <button class="button secondary" id="zero" data-scale>Zero</button>
          <button class="button secondary" id="tare-current" data-scale>Tare current load</button>
          <button class="button secondary" id="clear-tare" data-scale>Clear tare</button>
        </div>
        <form id="tare-form">
          <label class="ble-field">Tare value <input id="tare-value" inputmode="decimal" pattern="[0-9]+([.,][0-9]+)?" required data-scale></label>
          <p>Unit: <span id="unit">—</span></p>
          <button class="button" data-scale>Set tare</button>
        </form>
      </section>
      <section>
        <h2>CSCP console</h2>
        <div class="ble-log-legend"><span class="ble-tx">TX · Sent</span><span class="ble-rx">RX · Received</span></div>
        <button class="button secondary" id="clear-log">Clear console</button>
        <div id="log" class="ble-log" role="region" tabindex="0" aria-label="CSCP console"></div>
      </section>
    </div>
  </main>
  <script type="module" src="app.js"></script>
</body>
</html>

12. neutron.css — readable display and TX/RX colors

The CSS styles the three weight displays, stability state and console. TX is blue and RX green; both text labels remain visible for users who do not distinguish the colors. Cards stack vertically on phones.

body{font:1rem/1.65 system-ui;margin:0;background:#f4f8fb;color:#123654}*{box-sizing:border-box}.demo-site{max-width:80rem;margin:0 auto;padding:2rem 1rem}button,input{font:inherit}
.ble-console{--ble-ink:#102f46;--ble-blue:#0074b6;display:grid;gap:1.25rem;min-width:0;padding:clamp(.75rem,2vw,1.5rem);background:linear-gradient(145deg,#e9f4fb,#f5f8fc 55%,#e9f5f2);border:1px solid #cbdde9;border-radius:1.5rem;color:var(--ble-ink)}.ble-console section{background:#fff;border:1px solid #d4e1eb;border-radius:1rem;padding:clamp(1rem,2.5vw,1.75rem);min-width:0;box-shadow:0 8px 24px #12365406}.ble-console h3{margin:0 0 1rem;font-size:1.35rem}.ble-connection{border-top:4px solid #0074b6!important}.ble-actions{display:flex;flex-wrap:wrap;gap:.75rem;align-items:center}.ble-console .button{min-height:46px;white-space:normal;font:inherit;font-weight:600;line-height:1.4;background:#006da8;border:1px solid #006da8;border-radius:.6rem;padding:.75rem 1.2rem;color:#fff;cursor:pointer}.ble-console .button.secondary{background:#fff;color:#123654;border-color:#6a8499}.ble-console .button:hover:not(:disabled){background:#084e74;color:#fff}.ble-console button:disabled{opacity:.5;cursor:not-allowed}.ble-readings{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:1rem;margin:1.25rem 0}.ble-readings>div{padding:clamp(1rem,2.5vw,1.5rem);border-radius:.9rem;background:#f1f7fb;border:1px solid #d3e5f0;min-width:0}.ble-readings>div:first-child{background:#103951;border-color:#103951;color:#fff}.ble-readings dt{font-size:1rem;font-weight:600}.ble-readings dd{font-size:clamp(1.7rem,3.6vw,3.25rem);font-weight:700;margin:.5rem 0 0;overflow-wrap:anywhere;font-variant-numeric:tabular-nums;letter-spacing:-.035em}.ble-readings small{font-size:1rem;letter-spacing:0}.ble-stale dd{opacity:.55}.ble-help{font-size:1rem;line-height:1.65;color:#365067}.ble-field{display:grid;gap:.5rem;max-width:24rem;margin:1rem 0;font-weight:600}.ble-console input:not([type=checkbox]){font:inherit;font-weight:400;padding:.75rem;border:1px solid #71899b;border-radius:.5rem;width:100%;min-width:0;background:#fff;color:#102f46}.ble-switch{display:flex;gap:.75rem;align-items:center;min-height:46px;padding:.65rem 1rem;border:1px solid #b7d3e6;border-radius:.6rem;background:#eff7fc;font-weight:600}.ble-switch input{width:1.5rem;height:1.5rem;accent-color:#006da8}.ble-console :focus-visible{outline:3px solid #1765bc;outline-offset:4px}.ble-stability{display:inline-flex;flex-wrap:wrap;gap:.3rem;align-items:center;border-radius:.55rem;padding:.7rem 1rem;border:1px solid #7f94a4;background:#eff3f6;font-weight:650}.ble-stability-stable{background:#e5f5ec;color:#145436;border-color:#58a77b}.ble-stability-dynamic{background:#fff2d8;color:#714800;border-color:#b58a34}.ble-stability-overload,.ble-stability-underload{background:#fee9e8;color:#8a2623;border-color:#ca7976}.ble-log{background:#0e2538;color:#eef6ff;padding:.75rem;max-height:28rem;overflow:auto;border-radius:.7rem;margin:1rem 0 0;font: .9rem/1.65 ui-monospace,SFMono-Regular,Consolas,monospace;min-width:0}.ble-log-line{display:grid;grid-template-columns:6.5rem 2rem minmax(0,1fr);gap:.75rem;padding:.55rem .65rem;border-bottom:1px solid #284355;align-items:start}.ble-log-line time{color:#bbccdb;font-size:.8rem}.ble-log-line code{font:inherit;white-space:pre-wrap;overflow-wrap:anywhere;background:transparent;color:inherit}.ble-log-line.ble-tx{border-left:3px solid #7acbff;background:#17394f;color:#a9ddff}.ble-log-line.ble-rx{border-left:3px solid #6cdeb2;background:#123b36;color:#9bf0cc}.ble-log-legend{display:flex;gap:1rem;flex-wrap:wrap;margin:1rem 0}.ble-log-legend span{padding:.35rem .7rem;border-radius:.4rem;font-weight:650}.ble-log-legend .ble-tx{color:#07517e;background:#dff2ff}.ble-log-legend .ble-rx{color:#12583e;background:#e0f5eb}.ble-console form{margin-top:1rem}.ble-console>div[role=alert]{border:1px solid #d69790;background:#fff0ee;padding:1rem;border-radius:.7rem}.ble-console>div[role=alert] code{overflow-wrap:anywhere}@media(max-width:700px){.ble-readings{grid-template-columns:1fr}.ble-actions>*{width:100%}.ble-console{padding:.65rem;border-radius:1rem}.ble-log-line{grid-template-columns:2rem minmax(0,1fr);gap:.4rem}.ble-log-line time{grid-column:1/-1}.ble-log-line strong{grid-column:1}}@media print{.ble-console button,.ble-console form,.ble-switch{display:none}.ble-console{background:#fff;box-shadow:none}.ble-log{max-height:none;overflow:visible}}

13. app.js — connect methods to buttons

This complete example uses the same NeutronBle class; Download the neutron-ble.js class and save it next to app.js. All display and button helpers are defined in the code below.

This is the complete application logic: the seven methods explained above, data display, colored console and a 50 ms polling delay. perform() pauses polling during an operation and resumes after success. Device values are inserted using textContent, so a reply cannot become HTML.

import {NeutronBle} from './neutron-ble.js';

// Delay AFTER a response. The response timeout is a separate transport setting.
const POLL_DELAY_MS = 50;
const $ = id => document.getElementById(id);
let polling = false;
let timer;
let generation = 0;
let busy = false;
const ble = new NeutronBle({
  line: log,
  disconnected: () => {
    stopReading();
    $('status').textContent = 'Disconnected — last readings are stale';
    $('measurements').classList.add('ble-stale');
    controls();
  }
});

// METHOD connect
async function connect() {
  // Called by a button click: let the user select a Neutron BLE device.
  const name = await ble.connect();
  $('status').textContent = 'Connected: ' + name;
  controls();
  return read(); // QASI1C: show the first measurement.
}
// END connect

// METHOD disconnect
function disconnect() {
  stopReading(); // Do not schedule another QASI1C request.
  ble.disconnect(); // Close GATT; no scale setting is changed.
}
// END disconnect

// METHOD read
async function read() {
  const value = await ble.read(); // Send QASI1C + CRLF and wait for one reply.
  show(value); // Update net, gross, tare, unit and stability together.
  return value;
}
// END read

// METHOD tare
async function tare() {
  const reply = await ble.tare(); // T: tare the current stable load.
  await read(); // T S confirms success; T I means not executable now.
  return reply;
}
// END tare

// METHOD clearTare
async function clearTare() {
  const reply = await ble.clearTare(); // TAC: remove the current tare.
  await read(); // TAC A confirms success. Display the actual updated values.
  return reply;
}
// END clearTare

// METHOD setTare
async function setTare(value, unit) {
  const reply = await ble.setTare(value, unit); // Example: TA 0.5 kg + CRLF.
  await read(); // TA A confirms the applied value; it may be rounded by the scale.
  return reply;
}
// END setTare

// METHOD zero
async function zero() {
  const reply = await ble.zero(); // Z: zero the scale within its allowed range.
  await read(); // Z A confirms success; I, + and - are not success responses.
  return reply;
}
// END zero

function show(value) {
  for (const key of ['net', 'gross', 'tare']) $(key).textContent = value[key] + ' ' + value.unit;
  const names = {S: 'Stable', D: 'Dynamic', '+': 'Overload', '-': 'Underload'};
  const tones = {S: 'stable', D: 'dynamic', '+': 'overload', '-': 'underload'};
  $('stability').textContent = names[value.stability] ?? value.stability;
  $('stability').className = 'ble-stability ble-stability-' + (tones[value.stability] ?? 'unknown');
  $('unit').textContent = value.unit;
  $('measurements').classList.remove('ble-stale');
}
function log(direction, value) {
  const row = document.createElement('div');
  row.className = 'ble-log-line ble-' + direction.toLowerCase();
  for (const [tag, text] of [['time', new Date().toISOString().slice(11, 23)], ['strong', direction], ['code', value]]) {
    const node = document.createElement(tag);
    node.textContent = text; // Never interpret a device reply as HTML.
    row.append(node);
  }
  $('log').append(row);
  while ($('log').children.length > 150) $('log').firstElementChild.remove();
}
function controls() {
  document.querySelectorAll('[data-scale]').forEach(node => node.disabled = !ble.connected || busy);
  $('connect').disabled = ble.connected || busy || !NeutronBle.supported();
  $('once').disabled = !ble.connected || busy || polling;
}
function stopReading() {
  polling = false;
  generation++;
  clearTimeout(timer);
  $('continuous').checked = false;
  controls();
}
async function loop(token) {
  if (!polling || token !== generation) return;
  try {
    await read(); // Finish the reply before the next 50 ms delay starts.
    if (polling && token === generation) timer = setTimeout(() => loop(token), POLL_DELAY_MS);
  } catch (error) { fail(error); }
}
function startReading() {
  polling = true;
  $('continuous').checked = true;
  controls();
  void loop(++generation);
}
function fail(error) {
  stopReading();
  $('measurements').classList.add('ble-stale');
  // ES = syntax/unknown command. T I = tare not executable now or stability wait expired.
  $('status').textContent = error.message;
}
async function perform(method) {
  if (busy) return;
  const resume = polling;
  stopReading();
  busy = true;
  controls();
  try {
    const reply = await method();
    if (typeof reply === 'string') $('status').textContent = 'Confirmed by scale: ' + reply;
    if (resume && ble.connected) startReading();
  } catch (error) { fail(error); }
  finally { busy = false; controls(); }
}
$('connect').onclick = () => perform(connect);
$('disconnect').onclick = disconnect;
$('once').onclick = () => perform(read);
$('zero').onclick = () => perform(zero);
$('tare-current').onclick = () => perform(tare);
$('clear-tare').onclick = () => perform(clearTare);
$('tare-form').onsubmit = event => {
  event.preventDefault();
  void perform(() => setTare($('tare-value').value, $('unit').textContent));
};
$('continuous').onchange = event => event.target.checked ? startReading() : stopReading();
$('clear-log').onclick = () => $('log').replaceChildren();
controls();
if (!NeutronBle.supported()) $('status').textContent = 'Use a Web Bluetooth browser on HTTPS or localhost';
window.addEventListener('pagehide', disconnect);

14. NeutronBle class — download neutron-ble.js

Download the neutron-ble.js class

This helper file contains the transport details. You do not need to edit it to use the seven methods: it handles service/characteristic selection, notifications, CRLF buffering and serialized commands. Fragments from several notifications are assembled into one line. A response timeout closes the connection so a late reply cannot be mistaken for a reply to a new request.

export const BLE_UUID = {
    service: '49535343-fe7d-4ae5-8fa9-9fafd205e455',
    write: '49535343-8841-43f4-a8d4-ecbe34729bb3',
    notify: '49535343-1e4d-4bd9-ba61-23c647249616',
};
export function parseQasi(line) {
    const fields = line.trim().split(',').map(value => value.trim());
    // Some firmware joins the QASI prefix and the numeric scale status.
    if (fields.length === 11 && /^QASI\d+$/.test(fields[0]))
        fields.splice(0, 1, 'QASI', fields[0].slice(4));
    if (!['QASI', 'QASI1', 'QASI1C'].includes(fields[0]) || fields.length !== 12)
        return null;
    const [, error, channel, range, stability, gross, net, tare, , , , unit] = fields;
    if (![gross, net, tare].every(value => /^[-+]?\d+(?:\.\d+)?$/.test(value)))
        return null;
    return { error, channel, range, stability, gross, net, tare, unit };
}
export class NeutronBle {
    hooks;
    device;
    tx;
    rx;
    session = 0;
    buffer = '';
    decoder = new TextDecoder();
    queue = Promise.resolve();
    pending;
    constructor(hooks = {}) {
        this.hooks = hooks;
    }
    get connected() { return !!this.device?.gatt.connected && !!this.tx; }
    static supported() { return typeof navigator !== 'undefined' && globalThis.isSecureContext && 'bluetooth' in navigator; }
    async connect() {
        if (!NeutronBle.supported())
            throw new Error('unsupported');
        if (this.device)
            this.disconnect();
        const bluetooth = navigator.bluetooth;
        this.device = await bluetooth.requestDevice({ filters: [{ services: [BLE_UUID.service] }], optionalServices: [BLE_UUID.service] });
        this.device.addEventListener('gattserverdisconnected', this.onDisconnect);
        try {
            const server = await this.device.gatt.connect();
            const service = await server.getPrimaryService(BLE_UUID.service);
            this.tx = await service.getCharacteristic(BLE_UUID.write);
            this.rx = await service.getCharacteristic(BLE_UUID.notify);
            this.rx.addEventListener('characteristicvaluechanged', this.onNotification);
            await this.rx.startNotifications();
            return this.device.name ?? '';
        }
        catch (error) {
            this.disconnect();
            throw error;
        }
    }
    onNotification = (event) => {
        const value = event.target.value;
        if (!value)
            return;
        this.buffer += this.decoder.decode(value, { stream: true });
        if (this.buffer.length > 8192) {
            this.disconnect();
            return;
        }
        let end;
        while ((end = this.buffer.indexOf('\r\n')) !== -1) {
            const line = this.buffer.slice(0, end).trim();
            this.buffer = this.buffer.slice(end + 2);
            if (!line)
                continue;
            this.hooks.line?.('RX', line);
            if (this.pending?.accept(line)) {
                const pending = this.pending;
                this.pending = undefined;
                clearTimeout(pending.timer);
                pending.resolve(line);
            }
        }
    };
    onDisconnect = () => {
        this.session++;
        this.rx?.removeEventListener('characteristicvaluechanged', this.onNotification);
        this.device?.removeEventListener('gattserverdisconnected', this.onDisconnect);
        this.tx = undefined;
        this.rx = undefined;
        this.buffer = '';
        this.decoder = new TextDecoder();
        if (this.pending) {
            clearTimeout(this.pending.timer);
            this.pending.reject(new Error('disconnected'));
            this.pending = undefined;
        }
        this.hooks.disconnected?.();
    };
    disconnect() { this.device?.gatt.disconnect(); this.onDisconnect(); this.device = undefined; }
    request(command) {
        // This client exposes weighing operations only, with no configuration commands.
        if (!/^(QASI1C|Z|T|TAC|TA \d+(?:\.\d+)? [A-Za-z]{1,8})$/.test(command))
            return Promise.reject(new Error('command'));
        const session = this.session;
        const action = this.queue.catch(() => undefined).then(async () => {
            if (session !== this.session || !this.connected || !this.tx)
                throw new Error('disconnected');
            const prefix = command === 'QASI1C' ? 'QASI' : command.split(' ')[0];
            const response = new Promise((resolve, reject) => {
                this.pending = { resolve, reject, accept: line => (prefix === 'QASI' ? /^QASI(?:1C?|\d+)?(?:[ ,]|$)/.test(line) : new RegExp('^' + prefix + '(?:[ ,]|$)').test(line)) || /^ES(?:\s|$)/.test(line), timer: setTimeout(() => {
                        if (this.pending) {
                            this.pending = undefined;
                            reject(new Error('timeout'));
                            this.disconnect();
                        }
                    }, command === 'QASI1C' ? 5000 : 30000) };
            });
            // Attach a rejection handler before an asynchronous BLE write.
            void response.catch(() => undefined);
            try {
                this.hooks.line?.('TX', command);
                const bytes = new TextEncoder().encode(command + '\r\n');
                const tx = this.tx;
                for (let offset = 0; offset < bytes.length; offset += 20) {
                    const chunk = bytes.slice(offset, offset + 20);
                    if (tx.properties.write)
                        await tx.writeValueWithResponse(chunk);
                    else if (tx.properties.writeWithoutResponse)
                        await tx.writeValueWithoutResponse(chunk);
                    else
                        throw new Error('write');
                }
            }
            catch (error) {
                this.disconnect();
                await response.catch(() => undefined);
                throw error;
            }
            const line = await response;
            if (/^ES(?:\s|$)/.test(line))
                throw new Error('rejected:' + line);
            if (command === 'QASI1C') {
                const reading = parseQasi(line);
                if (!reading)
                    throw new Error('response:' + line);
                if (reading.error !== '1')
                    throw new Error('scale:' + line);
            }
            else if (!new RegExp('^' + prefix + '\\s+(A|S|D)(?:\\s|$)').test(line))
                throw new Error('rejected:' + line);
            return line;
        });
        this.queue = action;
        return action;
    }
    async read() { return parseQasi(await this.request('QASI1C')); }
    zero() { return this.request('Z'); }
    // T: apply the current stable load as tare; T I means not executable now.
    tare() { return this.request('T'); }
    // TAC: clear tare; only TAC A confirms completion.
    clearTare() { return this.request('TAC'); }
    setTare(value, unit) {
        const normalized = value.trim().replace(',', '.');
        if (!/^\d+(?:\.\d+)?$/.test(normalized) || !Number.isFinite(Number(normalized)))
            return Promise.reject(new Error('tare'));
        return this.request('TA ' + normalized + ' ' + unit);
    }
}

15. Try it and build your own application

Open the Neutron BLE test application. Connect a scale, read once or enable continuous reading. Try T, TAC, TA and Z; the console shows each sent command and actual reply.

You can also use this example when developing with AI: specify the method, its CSCP command and the expected response. This keeps both the method purpose and scale communication explicit.

Full CSCP reference · Neutron family

Content and responsibility: PRECIZ.

Frequently asked questions

Do I need to install an application to connect?

Use a browser that supports Web Bluetooth for this web example. JavaScript connects directly to the scale from the browser.

How does the application read scale data continuously?

The application repeats QASI1C. After each response it waits for the selected delay and sends the next request. The user can turn continuous reading on or off.

How do I set a known tare value over Bluetooth?

Send TA with the value and unit, for example TA 0.5 kg, followed by CRLF. After the scale confirms it, read QASI1C to display the actual applied tare.

Need help?

Need help with software, connectivity or using a solution? Describe the issue so we can help with the next step.

Prepare a request →