УРЛАГ
ГОО САЙХАН БА ЭРҮҮЛ МЭНД
ГАРААР ХИЙСЭН
СОЁЛ БА ТҮҮХ
ҮЗВЭР НААДАМ
БАЙГАЛЬ ОРЧИН
ХООЛ БА УНДАА
УРВУУ ИНЖЕНЕРЧЛЭЛ
ШИНЖЛЭХ УХААН
СПОРТ
ТЕХНОЛОГИ
ӨМСДӨГ ХЭРЭГСЭЛ
Temperature Logger in a Web Page: Web Bluetooth Reads, Plots and Saves a BLE Thermometer
Ed

Зохиогч

Ed

4. Арван хоёрдугаар сар 2026FI
0
0
0
0
0

Temperature Logger in a Web Page: Web Bluetooth Reads, Plots and Saves a BLE Thermometer

One HTML file that turns a browser into a temperature logger: it connects to any Bluetooth LE thermometer using the standard Environmental Sensing service, shows the reading, draws the history and saves it as a CSV file. No install and no server code.
Анхан шат
20 minutes

Зааварчилгаа

1

The page

Save this as thermo-logger.html.
thermo-logger.htmlhtml
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>BLE temperature logger</title>
<style>
  body { font-family: system-ui, sans-serif; margin: 1.5rem; max-width: 760px; }
  #now { font-size: 3rem; font-weight: bold; margin: .5rem 0; }
  canvas { width: 100%; height: 260px; border: 1px solid #ccc; }
  button { font-size: 1rem; padding: .5rem 1rem; margin-right: .5rem; }
</style>
</head>
<body>
<h1>BLE temperature logger</h1>
<p>Reads any device with the Environmental Sensing service (0x181A) and its Temperature characteristic (0x2A6E).</p>
<button id="connect">Connect</button><button id="csv" disabled>Download CSV</button>
<div id="now">-- °C</div>
<div id="status">Not connected.</div>
<canvas id="chart" width="1200" height="400"></canvas>
<script>
const ESS = 0x181A, TEMP = 0x2A6E;
const log = [];                                   // [time (ms), °C]
const $ = id => document.getElementById(id);

function onValue(event) {
  const raw = event.target.value.getInt16(0, true); // sint16, little-endian, 0.01 °C
  if (raw === -32768) { $('status').textContent = 'Device says: value not known (0x8000).'; return; }
  const c = raw / 100;
  log.push([Date.now(), c]);
  $('now').textContent = c.toFixed(2) + ' °C';
  $('csv').disabled = false;
  draw();
}

function draw() {
  const cv = $('chart'), g = cv.getContext('2d'), W = cv.width, H = cv.height;
  g.clearRect(0, 0, W, H);
  if (log.length < 2) return;
  const ys = log.map(p => p[1]), lo = Math.min(...ys) - 0.5, hi = Math.max(...ys) + 0.5;
  const t0 = log[0][0], t1 = log[log.length - 1][0];
  g.strokeStyle = '#c0392b'; g.lineWidth = 3; g.beginPath();
  log.forEach(([t, c], i) => {
    const x = 40 + (W - 60) * (t - t0) / (t1 - t0), y = H - 30 - (H - 60) * (c - lo) / (hi - lo);
    i ? g.lineTo(x, y) : g.moveTo(x, y);
  });
  g.stroke();
  g.fillStyle = '#333'; g.font = '22px sans-serif';
  g.fillText(hi.toFixed(1) + ' °C', 4, 24); g.fillText(lo.toFixed(1) + ' °C', 4, H - 6);
}

$('connect').onclick = async () => {
  try {
    const device = await navigator.bluetooth.requestDevice({ filters: [{ services: [ESS] }] });
    device.addEventListener('gattserverdisconnected', () => { $('status').textContent = 'Disconnected.'; });
    $('status').textContent = 'Connecting to ' + device.name + '…';
    const server = await device.gatt.connect();
    const service = await server.getPrimaryService(ESS);
    const ch = await service.getCharacteristic(TEMP);
    ch.addEventListener('characteristicvaluechanged', onValue);
    await ch.startNotifications();
    $('status').textContent = 'Connected to ' + device.name + '; logging.';
  } catch (e) {
    $('status').textContent = 'Error: ' + e.message;
  }
};

$('csv').onclick = () => {
  const rows = ['time,temperature_c', ...log.map(([t, c]) => new Date(t).toISOString() + ',' + c.toFixed(2))];
  const a = document.createElement('a');
  a.href = URL.createObjectURL(new Blob([rows.join('\n')], { type: 'text/csv' }));
  a.download = 'temperature.csv'; a.click();
};
</script>
</body>
</html>

Шаардлагатай багаж:

Ширээний компьютерШирээний компьютер
2

Serve it and connect

Web Bluetooth only runs on secure pages: open the file through https or from localhost, for example run python3 -m http.server in its folder and open http://localhost:8000/thermo-logger.html in a browser that supports Web Bluetooth. Press Connect, pick the thermometer, and leave the page open while it logs. Download CSV saves every reading with its time.

Шаардлагатай багаж:

Ширээний компьютерШирээний компьютер
Ухаалаг утасУхаалаг утас
Bluetooth термометрBluetooth термометр

Шаардлагатай багаж

3

CC0 Нийтийн домэйн

Энэ загвар CC0 дор гаргагдсан. Та зөвшөөрөл авахгүйгээр хуулах, өөрчлөх, түгээх, ашиглах боломжтой.

Загвараар дамжуулан бүтээгдэхүүн худалдаж авч Бүтээгчийг дэмжээрэй Бүтээгчийн шимтгэл Борлуулагчаар тогтоосон, эсвэл энэ загварын шинэ хувилбар үүсгэж орлогоо хуваахын тулд өөрийн загварт холбоос болгон оруулна уу.

Хэлэлцүүлэг

(0)

Нэвтрэх хэлэлцүүлэгт нэгдэхийн тулд

Сэтгэгдлүүдийг ачаалж байна...