TEHNOLOGIJA VAGANJA · VLASTITI RAZVOJ · PODRŠKA
+386 2 320 33 46info@preciz.si

PRAKTIČNI VODIČ · PRECIZ

Kako povezati vage Neutron putem Bluetootha BLE

Neutron NS/NT · Bluetooth BLE · JavaScript

1. Što je potrebno i kako je primjer podijeljen

Povežite vage Neutron NS i NT s preglednikom putem Bluetootha Low Energy (BLE), a naredbe i odgovore razmjenjujte protokolom CSCP. Primjer je namijenjen razvijateljima, integratorima i svima koji žele izraditi vlastitu aplikaciju za rad s vagom.

Upotrijebite preglednik s podrškom Web Bluetooth i stranicu putem HTTPS-a ili localhosta. Uključite Bluetooth i odaberite vagu klikom na gumb. Ako je koristi druga aplikacija, najprije je tamo odspojite.

Primjeri koriste klasu NeutronBle. Varijabla ble jedna je instanca koju dijele sve metode. Klasa upravlja BLE vezom, naredbama CSCP i obradom odgovora.

  • Usluga: 49535343-fe7d-4ae5-8fa9-9fafd205e455
  • Pisanje, aplikacija → vaga: 49535343-8841-43f4-a8d4-ecbe34729bb3
  • Obavijesti, vaga → aplikacija: 49535343-1e4d-4bd9-ba61-23c647249616

Najprije uključite klasu. Preuzmite klasu neutron-ble.js i spremite datoteku u istu mapu kao app.js. Na početak app.js dodajte:

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

const ble = new NeutronBle();

U HTML uključite <script type="module" src="./app.js"></script>. Nisu potrebni npm instalacija ni vanjske ovisnosti. Zadržite naziv neutron-ble.js. Koristite jednu instancu ble za sve funkcije. Cijeli izvorni kod klase nalazi se i u 14. poglavlju.

2. connect() — povežite vagu

Prije uporabe ove metode: Preuzmite klasu neutron-ble.js, uključite je s import { NeutronBle } from './neutron-ble.js' i jednom izradite const ble = new NeutronBle(), kao u prvom poglavlju. Dodajte funkciju u isti app.js.

Metoda otvara odabir uređaja, uspostavlja GATT vezu i uključuje BLE obavijesti. Pozovite je klikom na gumb; preglednik ne otvara odabir automatski pri učitavanju stranice.

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

Povezivanje koristi getPrimaryService(), getCharacteristic() za pisanje i obavijesti te startNotifications(). Primatelj se registrira prije uključivanja obavijesti kako se prvi odgovor ne bi izgubio.

3. disconnect() — zatvorite vezu

Prije uporabe ove metode: Preuzmite klasu neutron-ble.js, uključite je s import { NeutronBle } from './neutron-ble.js' i jednom izradite const ble = new NeutronBle(), kao u prvom poglavlju. Dodajte funkciju u isti app.js.

Najprije zaustavite ponovljene upite, zatim zatvorite GATT. Odspajanje ne mijenja postavke vage. Nakon odspajanja označite prikazane vrijednosti kao posljednja očitanja, a ne trenutačna mjerenja.

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

4. read() — neto, bruto, tara i stabilnost

Prije uporabe ove metode: Preuzmite klasu neutron-ble.js, uključite je s import { NeutronBle } from './neutron-ble.js' i jednom izradite const ble = new NeutronBle(), kao u prvom poglavlju. Dodajte funkciju u isti app.js.

read() šalje QASI1C sa završetkom CRLF i čeka jedan odgovor. Vraćeni objekt sadrži net, gross, tare, unit, stability, channel, range, 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;
}

Prikažite neto, bruto i taru iz istog odgovora, bez vlastitog izračuna ili promjene broja decimala. S znači stabilno, D nestabilno, + preopterećenje, a - mjerenje ispod raspona. Status 1 znači da nema pogreške. Redoslijed polja i jedinice: referenca QASI1/QASI1C.

5. tare() — tarirajte trenutačno opterećenje

Prije uporabe ove metode: Preuzmite klasu neutron-ble.js, uključite je s import { NeutronBle } from './neutron-ble.js' i jednom izradite const ble = new NeutronBle(), kao u prvom poglavlju. Dodajte funkciju u isti app.js.

Stavite posudu na vagu i pozovite tare(). Metoda šalje T, čeka potvrdu i vraća novo mjerenje. T S 0.50 kg primjer je uspješnog tariranja sa stabilnom vrijednošću. T I znači da naredba trenutačno nije izvršiva ili se vaga nije stabilizirala unutar predviđenog vremena.

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

Sve odgovore opisuje referenca T.

6. clearTare() — izbrišite taru

Prije uporabe ove metode: Preuzmite klasu neutron-ble.js, uključite je s import { NeutronBle } from './neutron-ble.js' i jednom izradite const ble = new NeutronBle(), kao u prvom poglavlju. Dodajte funkciju u isti app.js.

clearTare() šalje TAC i briše trenutačnu taru, izmjerenu ili unaprijed unesenu. TAC A potvrđuje izvršenje; TAC I znači da naredba trenutačno nije izvršiva. read() zatim vraća nove vrijednosti neto, bruto i tare.

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

7. setTare(value, unit) — unesite poznatu taru

Prije uporabe ove metode: Preuzmite klasu neutron-ble.js, uključite je s import { NeutronBle } from './neutron-ble.js' i jednom izradite const ble = new NeutronBle(), kao u prvom poglavlju. Dodajte funkciju u isti app.js.

Za poznatu masu posude koristite setTare("0.5", "kg") kada vaga javlja kg. Time se šalje TA 0.5 kg. Primjer prihvaća decimalnu točku ili zarez, a šalje decimalnu točku.

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 s vrijednošću i jedinicom potvrđuje primijenjenu taru. Vaga je može zaokružiti prema svojoj podjeli pa ponovno očitajte s read(). TA L znači neizvršivu naredbu, primjerice zbog sintakse, vrijednosti ili jedinice. Pojedinosti: TA.

8. zero() — nulirajte vagu

Prije uporabe ove metode: Preuzmite klasu neutron-ble.js, uključite je s import { NeutronBle } from './neutron-ble.js' i jednom izradite const ble = new NeutronBle(), kao u prvom poglavlju. Dodajte funkciju u isti app.js.

Uklonite opterećenje i pozovite zero(). Z poštuje raspon nuliranja i uvjete stabilnosti. Z A potvrđuje uspjeh. Nakon potvrde očitajte novo mjerenje.

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

9. Kontinuirano čitanje: zadana stanka 50 ms

Aplikacija šalje QASI1C, obrađuje odgovor, čeka 50 ms i tek tada šalje sljedeći upit. Istodobno je otvoren samo jedan zahtjev. Prekidač uključuje ili isključuje petlju; isključivanje ne odbacuje odgovor na već poslani zahtjev.

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 stanka je nakon odgovora, a ne vrijeme čekanja odgovora. Prijenos čeka najviše 5 s za čitanje i 30 s za tariranje i nuliranje. To su odvojene postavke aplikacije, a ne promjene konfiguracije vage. Stvarni ciklus uključuje obradu i BLE prijenos.

10. Što znače ES, T I i drugi odgovori

  • ES: sintaktička pogreška ili nepoznata naredba. Opća poruka pogreške.
  • T S …: uspješno tariranje sa stabilnom vrijednošću. T I: trenutačno nije izvršivo ili je isteklo čekanje stabilnosti. T +: tara prelazi kapacitet; T -: negativna tara. Odgovori T.
  • TAC A: tara izbrisana. TAC I: brisanje trenutačno nije moguće. Odgovori TAC.
  • TA A …: unesena tara potvrđena. TA I: trenutačno nije izvršivo. TA L: neispravna sintaksa, vrijednost ili jedinica. Odgovori TA.
  • QASI I: vaga trenutačno ne može vratiti podatke. Odgovor QASI1C.

Svaka naredba i odgovor završavaju s \r\n (CRLF, ASCII 13 i 10). Razmaci u primjerima stvarni su razmaci; ˽ u priručniku označava razmak. Polja QASI1C odvojena su zarezima. Pogledajte strukturu naredbi i odgovora CSCP. Samo slanje ne dokazuje uspjeh: vaga mora potvrditi izvršenje.

11. Cijela demo aplikacija (ZIP) i index.html

Preuzmite cijelu demo aplikaciju (ZIP). Paket sadrži index.html, neutron.css, app.js, neutron-ble.js i README.txt s uputama za pokretanje.

Raspakirajte ZIP u jednu mapu. U toj mapi pokrenite lokalni web-poslužitelj, primjerice s Pythonom 3: python3 -m http.server 8000 --bind 127.0.0.1 (u Windowsu možete koristiti py -m http.server 8000 --bind 127.0.0.1). Otvorite http://127.0.0.1:8000 u pregledniku s podrškom Web Bluetooth, uključite Bluetooth i kliknite Connect. Aplikaciju možete posluživati i putem HTTPS-a. Ne otvarajte datoteke izravno putem file://.

Za ručno sastavljanje primjera izradite četiri datoteke: index.html, neutron.css, app.js i neutron-ble.js. HTML u nastavku određuje prikaz i gumbe; CSS, aplikacijska logika i klasa slijede u odvojenim poglavljima.

<!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 — čitljiv prikaz i boje TX/RX

CSS oblikuje tri prikaza mase, stanje stabilnosti i konzolu. TX je plav, a RX zelen; tekstualne oznake ostaju vidljive i korisnicima koji ne razlikuju boje. Na telefonima se kartice slažu okomito.

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 — povežite metode s gumbima

Cijeli primjer koristi istu klasu NeutronBle; Preuzmite klasu neutron-ble.js i spremite je pokraj app.js. Sve pomoćne funkcije za prikaz i gumbe definirane su u kodu u nastavku.

Cijela aplikacijska logika uključuje sedam metoda, prikaz podataka, konzolu u boji i stanku upita od 50 ms. perform() zaustavlja upite tijekom radnje i nastavlja ih nakon uspjeha. Vrijednosti se umeću s textContent, pa se odgovor ne može tumačiti kao 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. Klasa NeutronBle — preuzmite neutron-ble.js

Preuzmite klasu neutron-ble.js

Ova pomoćna datoteka sadrži pojedinosti prijenosa. Za sedam metoda nije je potrebno mijenjati: upravlja uslugama i karakteristikama, obavijestima, CRLF međuspremnikom i slijednim naredbama. Dijelovi više obavijesti sastavljaju se u jedan redak. Istek vremena zatvara vezu kako zakašnjeli odgovor ne bi bio zamijenjen odgovorom na novi upit.

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. Isprobajte i izradite vlastitu aplikaciju

Otvorite testnu aplikaciju Neutron BLE. Povežite vagu, pročitajte jednom ili uključite kontinuirano čitanje. Isprobajte T, TAC, TA i Z; konzola prikazuje svaku poslanu naredbu i stvarni odgovor.

Primjer možete koristiti i pri razvoju s pomoću AI-ja: navedite metodu, naredbu CSCP i očekivani odgovor kako bi zadatak i komunikacija s vagom bili jasno opisani.

Cijela referenca CSCP · Obitelj Neutron

Sadržaj i odgovornost: PRECIZ.

Česta pitanja

Moram li instalirati aplikaciju za povezivanje?

Za ovaj web-primjer koristite preglednik s podrškom Web Bluetooth. JavaScript se povezuje izravno s vagom iz preglednika.

Kako aplikacija kontinuirano čita podatke vage?

Aplikacija ponavlja QASI1C. Nakon svakog odgovora čeka odabranu stanku i šalje sljedeći upit. Korisnik može uključiti ili isključiti kontinuirano čitanje.

Kako postaviti poznatu taru putem Bluetootha?

Pošaljite TA s vrijednošću i jedinicom, primjerice TA 0.5 kg, sa završetkom CRLF. Nakon potvrde vage očitajte QASI1C za prikaz stvarno primijenjene tare.

Trebate pomoć?

Trebate pomoć sa softverom, povezivošću ili uporabom rješenja? Opišite problem kako bismo vam pomogli odrediti sljedeći korak.

Pripremite zahtjev →