Project

General

Profile

Features #2288 » TB_Widget_Design_Guide_CE4.2.docx

hướng dẫn thiết kế custom widget - T. Nguyen Van Thanh, 2026-03-17 12:28

📟

ThingsBoard CE 4.2.1.1

Hướng Dẫn Toàn Diện Thiết Kế Custom Widget

Từ cơ bản đến nâng cao • Ví dụ thực tế • Best Practices

Phiên bản: March 2026

5 Loại Widget Widget API Chi Tiết 10+ Ví Dụ Code Tricks & Tips

Mục Lục

[Mục Lục 1](#mục-lục)

[1. Tổng Quan Về Widget Trong ThingsBoard
1](#tổng-quan-về-widget-trong-thingsboard)

[1.1 Kiến Trúc Widget 1](#kiến-trúc-widget)

[1.2 Năm Loại Widget Chính
1](#năm-loại-widget-chính)

[2. Widget Editor — Mini IDE Của ThingsBoard
1](#widget-editor-mini-ide-của-thingsboard)

[2.1 Cấu Trúc Widget Editor
1](#cấu-trúc-widget-editor)

[2.2 Quy Trình Phát Triển Widget Cơ Bản
1](#quy-trình-phát-triển-widget-cơ-bản)

[2.3 Debugging Tips Chuyên Sâu 1](#_Toc224308867)

[Phương pháp 1: Console Log (đơn giản nhất)
1](#phương-pháp-1-console-log-đơn-giản-nhất)

[Phương pháp 2: Browser Debugger (mạnh nhất)
1](#phương-pháp-2-browser-debugger-mạnh-nhất)

[3. Widget API Chi Tiết 1](#widget-api-chi-tiết)

[3.1 Các Lifecycle Functions Quan Trọng
1](#các-lifecycle-functions-quan-trọng)

[3.2 Widget Context (self.ctx) — Chi Tiết Đầy Đủ
1](#widget-context-self.ctx-chi-tiết-đầy-đủ)

[Properties dữ liệu 1](#properties-dữ-liệu)

[Properties kích thước
1](#properties-kích-thước)

[Angular & Change Detection
1](#angular-change-detection)

[Utility APIs hữu ích 1](#utility-apis-hữu-ích)

[3.3 Cách Đọc Dữ Liệu Từ Subscription
1](#_Toc224308877)

[Latest Values Widget — Đọc giá trị mới nhất
1](#latest-values-widget-đọc-giá-trị-mới-nhất)

[Time Series Widget — Đọc chuỗi dữ liệu
1](#time-series-widget-đọc-chuỗi-dữ-liệu)

[4. Ví Dụ Thực Tế 1](#ví-dụ-thực-tế)

[Ví Dụ 1: Widget Hiển Thị Nhiệt Độ Đơn Giản (Latest Values)
1](#ví-dụ-1-widget-hiển-thị-nhiệt-độ-đơn-giản-latest-values)

[Bước 1: HTML Template
1](#bước-1-html-template)

[Bước 2: CSS 1](#bước-2-css)

[Bước 3: JavaScript 1](#bước-3-javascript)

[Bước 4: Settings Schema
1](#bước-4-settings-schema)

[Ví Dụ 2: Widget Chart.js Time Series (biểu đồ đường)
1](#_Toc224308886)

[Tab Resources — Thêm thư viện Chart.js
1](#tab-resources-thêm-thư-viện-chart.js)

[HTML 1](#html)

[JavaScript — Khởi tạo và cập nhật Chart.js
1](#javascript-khởi-tạo-và-cập-nhật-chart.js)

[Ví Dụ 3: RPC Control Widget (Nút Bật/Tắt Thiết Bị)
1](#ví-dụ-3-rpc-control-widget-nút-bậttắt-thiết-bị)

[HTML 1](#html-1)

[CSS 1](#css)

[JavaScript 1](#javascript)

[5. Settings Schema Nâng Cao
1](#settings-schema-nâng-cao)

[5.1 Các Loại Field Hỗ Trợ
1](#các-loại-field-hỗ-trợ)

[5.2 Ví Dụ Schema Phức Hợp
1](#ví-dụ-schema-phức-hợp)

[6. Tricks & Best Practices
1](#tricks-best-practices)

[6.1 Performance Tips 1](#performance-tips)

[Trick 1: Debounce onResize để tránh render quá nhiều lần
1](#trick-1-debounce-onresize-để-tránh-render-quá-nhiều-lần)

[Trick 2: Cache DOM elements trong onInit
1](#trick-2-cache-dom-elements-trong-oninit)

[Trick 3: Chart.js — update("none") để tránh animation lag
1](#trick-3-chart.js-updatenone-để-tránh-animation-lag)

[6.2 Tricks Giao Tiếp Giữa Các Widget
1](#tricks-giao-tiếp-giữa-các-widget)

[Widget gửi dữ liệu (Publisher)
1](#widget-gửi-dữ-liệu-publisher)

[Widget nhận dữ liệu (Subscriber)
1](#widget-nhận-dữ-liệu-subscriber)

[6.3 Tricks Xử Lý Lỗi & Edge Cases
1](#tricks-xử-lý-lỗi-edge-cases)

[Pattern null-safe khi đọc data
1](#pattern-null-safe-khi-đọc-data)

[Cleanup đúng cách để tránh memory leak
1](#cleanup-đúng-cách-để-tránh-memory-leak)

[6.4 Tricks Responsive Design
1](#tricks-responsive-design)

[Sử dụng onResize để responsive chart
1](#sử-dụng-onresize-để-responsive-chart)

[7. Tích Hợp Thư Viện JavaScript Bên Ngoài
1](#tích-hợp-thư-viện-javascript-bên-ngoài)

[7.1 Danh Sách Thư Viện Phổ Biến
1](#danh-sách-thư-viện-phổ-biến)

[7.2 Ví Dụ: Gauge Widget Với gauge.js
1](#ví-dụ-gauge-widget-với-gauge.js)

[Resources: Thêm URL 1](#resources-thêm-url)

[HTML 1](#html-2)

[JavaScript 1](#javascript-1)

[8. Quản Lý Widget — Import, Export, Bundle
1](#quản-lý-widget-import-export-bundle)

[8.1 Export Widget 1](#export-widget)

[8.2 Import Widget 1](#import-widget)

[8.3 Tổ Chức Widget Bundle Hiệu Quả
1](#tổ-chức-widget-bundle-hiệu-quả)

[9. Checklist Thiết Kế Widget Chuyên Nghiệp
1](#checklist-thiết-kế-widget-chuyên-nghiệp)

[9.1 Checklist Trước Khi Deploy Widget
1](#checklist-trước-khi-deploy-widget)

[9.2 Lộ Trình Học Tập Đề Xuất
1](#lộ-trình-học-tập-đề-xuất)

[9.3 Tài Nguyên Học Tập Chính Thức
1](#tài-nguyên-học-tập-chính-thức)

CHƯƠNG 1: TỔNG QUAN VỀ WIDGET TRONG THINGSBOARD

1. Tổng Quan Về Widget Trong ThingsBoard

ThingsBoard widget là các module UI tùy chỉnh được tích hợp vào IoT
Dashboard. Chúng cung cấp các chức năng cho người dùng cuối như hiển thị
dữ liệu, điều khiển thiết bị từ xa, quản lý cảnh báo và hiển thị nội
dung HTML tùy chỉnh.

1.1 Kiến Trúc Widget

Mỗi widget trong ThingsBoard được xây dựng từ 4 thành phần cốt lõi:

Thành phần Mô tả
HTML Template Cấu trúc giao diện người dùng, sử dụng Angular template syntax
CSS Styles Định nghĩa style riêng cho widget, được scoped trong container
JavaScript Logic Xử lý dữ liệu, tương tác API, cập nhật UI qua self.ctx
Settings Schema JSON Schema để tạo form cấu hình tự động cho người dùng cuối

1.2 Năm Loại Widget Chính

ThingsBoard CE 4.2 hỗ trợ 5 loại widget với chức năng khác nhau. Đây là
điều đầu tiên cần xác định trước khi bắt đầu thiết kế:

Loại Widget Datasource Use Case điển hình Ví dụ sẵn có
Latest Values Attributes / Time Series (giá trị mới nhất) Hiển thị nhiệt độ hiện tại, trạng thái thiết bị, gauge, LED indicator Digital Gauge, LED Indicator, Knob Control
Time Series Time Series (chuỗi thời gian lịch sử) Vẽ đồ thị lịch sử dữ liệu, so sánh theo thời gian Line Chart, Bar Chart, State Chart
RPC Control Target device (gửi lệnh) Nút bấm, slider, switch điều khiển thiết bị IoT qua RPC Round Switch, Knob, GPS Input
Alarm Widget Alarm datasource Hiển thị và quản lý cảnh báo từ các thiết bị Alarms Table, Alarm Count
Static Widget Không có datasource HTML/Markdown tĩnh, hướng dẫn, nhãn, logo HTML Card, Markdown Card

💡 Tip: Chọn đúng loại widget ngay từ đầu!

Loại widget quyết định cách dữ liệu được subscribe. Latest Values widget chỉ nhận giá trị mới nhất (1 điểm), còn Time Series widget nhận toàn bộ chuỗi dữ liệu trong time window. Sai loại = data sẽ không hiển thị đúng.

CHƯƠNG 2: WIDGET EDITOR — MÔI TRƯỜNG PHÁT TRIỂN

2. Widget Editor — Mini IDE Của ThingsBoard

Widget Editor là môi trường phát triển tích hợp ngay trong ThingsBoard
UI. Để truy cập: Widget Library → Chọn hoặc tạo Widgets Bundle → Nhấn
"+" → Create new widget.

2.1 Cấu Trúc Widget Editor

Widget Editor gồm các khu vực sau:

Khu vực Chức năng
Toolbar (trên cùng) Widget Title, Widget Type selector, nút Run / Undo / Save / Save As
Tab HTML Viết HTML template với Angular template syntax (*ngFor, *ngIf, {{}}...)
Tab CSS CSS styles riêng cho widget (được scoped tự động)
Tab Resources Thêm external JS/CSS libraries (URL hoặc file)
Tab JavaScript Logic widget: self.onInit, self.onDataUpdated, self.onResize,...
Tab Settings Schema JSON Schema để auto-generate form cấu hình widget
Tab Data Key Schema JSON Schema cho cấu hình từng data key
Widget Preview Preview realtime với datasource "Function" để test

2.2 Quy Trình Phát Triển Widget Cơ Bản

  1. Chọn loại widget phù hợp (Latest Values / Time Series / RPC / Alarm
    / Static)

  2. Viết
    HTML structure trong tab HTML

  3. Thêm CSS styles trong tab CSS

  4. Thêm external libraries nếu cần trong tab Resources

  5. Viết JavaScript logic trong tab JavaScript

  6. Định nghĩa Settings Schema nếu widget cần cấu hình

  7. Nhấn "Run" để xem preview, debug bằng console.log() hoặc debugger;

  8. Nhấn "Save" để lưu

2.3 Debugging Tips Chuyên Sâu

Phương pháp 1: Console Log (đơn giản nhất)

self.onDataUpdated = function() {

// Debug dữ liệu nhận được

console.log("=== DATA UPDATE ===");

console.log("ctx.data:", self.ctx.data);

console.log("datasources:", self.ctx.datasources);

// Log giá trị key đầu tiên

if (self.ctx.data[0] && self.ctx.data[0].data[0]) {

console.log("Latest value:", self.ctx.data[0].data[0][1]);

}

};

Phương pháp 2: Browser Debugger (mạnh nhất)

self.onInit = function() {

debugger; // Trình duyệt sẽ dừng tại đây

// Bạn có thể inspect toàn bộ self.ctx trong DevTools

};

🔧 Workflow Debug Hiệu Quả

Mở DevTools (F12) trước khi nhấn Run. Dùng tab Sources để xem breakpoint. Trong Console, gõ "self.ctx" để inspect toàn bộ context sau khi widget load xong. Function datasource trong preview cho phép simulate dữ liệu không cần thiết bị thật.

CHƯƠNG 3: WIDGET API — TRÁI TIM CỦA MỌI CUSTOM WIDGET

3. Widget API Chi Tiết

Tất cả logic widget được viết trong tab JavaScript. Biến self là
reference đến widget instance, và self.ctx (WidgetContext) chứa mọi API,
dữ liệu cần thiết.

3.1 Các Lifecycle Functions Quan Trọng

Đây là 5 hàm lifecycle bạn cần nắm vững:

Function Khi nào được gọi Dùng để làm gì
self.onInit() Một lần khi widget khởi tạo Khởi tạo thư viện JS, tạo DOM elements, đặt giá trị mặc định từ settings, đăng ký event listeners
self.onDataUpdated() Mỗi khi có data mới từ server Cập nhật UI với data mới, re-render chart, cập nhật giá trị hiển thị. Quan trọng nhất!
self.onResize() Khi kích thước widget thay đổi Resize chart, responsive layout, tính toán lại kích thước element
self.onEditModeChanged() Khi vào/ra edit mode dashboard Disable controls khi đang edit, hiện placeholder
self.onDestroy() Khi widget bị xóa/navigate away Cleanup: clear intervals, destroy chart instances, free memory

3.2 Widget Context (self.ctx) — Chi Tiết Đầy Đủ

self.ctx là object chứa toàn bộ thông tin và API của widget. Dưới đây là
các properties quan trọng nhất: xem hướng dẫn chi tiết tại
TB_ctx_Angular_v3_Final.docx

Properties dữ liệu

// self.ctx.data — Mảng chứa dữ liệu subscription

// Cấu trúc: [{ datasource, dataKey, data: [[timestamp, value], ...] }]

let latestValue = self.ctx.data[0].data[0][1]; // Giá trị mới nhất

let timestamp = self.ctx.data[0].data[0][0]; // Timestamp (ms)

// self.ctx.datasources — Info về các datasource đang kết nối

let deviceName = self.ctx.datasources[0].name;

// self.ctx.settings — Object chứa settings từ Settings Schema

let myColor = self.ctx.settings.primaryColor || "#1565C0";

// self.ctx.timeWindow — Time window hiện tại (chỉ Time Series widget)

let startTime = self.ctx.timeWindow.minTime; // ms

let endTime = self.ctx.timeWindow.maxTime; // ms

Properties kích thước

// self.ctx.width, self.ctx.height — Kích thước hiện tại của widget (px)

let w = self.ctx.width;

let h = self.ctx.height;

// self.ctx.$container — jQuery object của container element

self.ctx.$container.css("background-color", "#f5f5f5");

// self.ctx.$containerParent — Parent container

Angular & Change Detection

// self.ctx.$scope — Angular scope (dùng để giao tiếp HTML <-> JS)

self.ctx.$scope.myValue = 42; // Đặt biến accessible trong HTML template

self.ctx.$scope.clickHandler = () => { /* xử lý click */ };

// QUAN TRỌNG: Gọi detectChanges() sau khi update $scope

// để Angular re-render HTML template

self.ctx.detectChanges();

// Hoặc dùng ngZone để chạy code trong Angular zone

self.ctx.ngZone.run(() => {

self.ctx.$scope.value = newValue;

self.ctx.detectChanges();

});

Utility APIs hữu ích

// Translate service — dịch multilanguage

self.ctx.translate.instant("widget.no-data-found");

// Date pipe — format timestamp

let dateStr = self.ctx.date.transform(timestamp, "dd/MM/yyyy HH:mm:ss");

// Utils — nhiều helper functions

let formattedVal = self.ctx.utils.formatValue(1234.567, 2, " °C", true);

// Kết quả: "1 234,57 °C" (locale-aware)

// HTTP service — gọi API ngoài từ widget (cẩn thận CORS)

self.ctx.http.get("https://api.example.com/data").subscribe(res => {

console.log(res);

});

3.3 Cách Đọc Dữ Liệu Từ Subscription

Đây là phần gây nhầm lẫn nhiều nhất. Hiểu rõ cấu trúc data sẽ giúp bạn
tránh được 80% bug phổ biến:

Latest Values Widget — Đọc giá trị mới nhất

self.onDataUpdated = function() {

// ctx.data là mảng, mỗi phần tử là một data key

// ctx.data[keyIndex].data là mảng [[timestamp, value]]

// Latest Values chỉ có 1 phần tử trong data array: data[0]

if (!self.ctx.data || self.ctx.data.length === 0) return;

// Đọc tất cả các key được cấu hình

self.ctx.data.forEach(function(keyData) {

let keyName = keyData.dataKey.name; // Tên key (vd: "temperature")

let keyLabel = keyData.dataKey.label; // Label hiển thị

let value = null;

if (keyData.data && keyData.data.length > 0) {

value = keyData.data[0][1]; // [0] = dòng đầu, [1] = giá trị

}

// Gán vào scope để hiển thị trong HTML

self.ctx.$scope[keyName] = value;

});

self.ctx.detectChanges();

};

Time Series Widget — Đọc chuỗi dữ liệu

self.onDataUpdated = function() {

if (!self.ctx.data || self.ctx.data.length === 0) return;

let keyData = self.ctx.data[0]; // Key đầu tiên

let seriesData = keyData.data; // [[ts1, val1], [ts2, val2], ...]

// Chuyển thành format cho Chart.js

let chartLabels = seriesData.map(d => new Date(d[0]).toLocaleTimeString());

let chartValues = seriesData.map(d => parseFloat(d[1]));

// Cập nhật chart

if (self.chart) {

self.chart.data.labels = chartLabels;

self.chart.data.datasets[0].data = chartValues;

self.chart.update();

}

};

CHƯƠNG 4: VÍ DỤ THỰC TẾ — XÂY DỰNG WIDGET TỪ ĐẦU

4. Ví Dụ Thực Tế

Ví Dụ 1: Widget Hiển Thị Nhiệt Độ Đơn Giản (Latest Values)

Mục tiêu: Tạo widget hiển thị nhiệt độ hiện tại với màu sắc thay đổi
theo ngưỡng (xanh/vàng/đỏ). Đây là widget cơ bản nhất để học cấu trúc.

Bước 1: HTML Template

<div class="temp-card">

<div class="temp-title">{{ctx.$scope.title}}</div>

<div class="temp-value" [style.color]="ctx.$scope.color">

{{ctx.$scope.value !== null ? ctx.$scope.value : "--"}}

<span class="temp-unit">°C</span>

</div>

<div class="temp-status" [style.background]="ctx.$scope.color">

{{ctx.$scope.status}}

</div>

<div class="temp-time">Cập nhật: {{ctx.$scope.lastUpdate}}</div>

</div>

Bước 2: CSS

.temp-card {

display: flex; flex-direction: column; align-items: center;

justify-content: center; height: 100%; padding: 16px;

font-family: Roboto, sans-serif;

}

.temp-title { font-size: 14px; color: #666; text-transform: uppercase; letter-spacing: 1px; }

.temp-value { font-size: 56px; font-weight: 300; margin: 8px 0; transition: color 0.5s; }

.temp-unit { font-size: 28px; }

.temp-status {

padding: 4px 16px; border-radius: 12px; color: white;

font-size: 12px; font-weight: 500; margin: 8px 0;

}

.temp-time { font-size: 11px; color: #aaa; margin-top: 8px; }

Bước 3: JavaScript

self.onInit = function() {

// Đọc settings từ Settings Schema

let s = self.ctx.settings;

self.ctx.$scope.title = s.title || "Nhiệt Độ";

self.ctx.$scope.warnTemp = s.warnTemp || 30;

self.ctx.$scope.alertTemp = s.alertTemp || 40;

self.ctx.$scope.value = null;

self.ctx.$scope.color = "#4CAF50";

self.ctx.$scope.status = "Đang tải...";

};

self.onDataUpdated = function() {

if (!self.ctx.data || !self.ctx.data[0] || !self.ctx.data[0].data[0]) {

self.ctx.$scope.status = "Không có dữ liệu";

self.ctx.detectChanges();

return;

}

let raw = self.ctx.data[0].data[0];

let temp = parseFloat(raw[1]);

let ts = raw[0];

self.ctx.$scope.value = temp.toFixed(1);

self.ctx.$scope.lastUpdate = new Date(ts).toLocaleTimeString("vi-VN");

// Logic đổi màu theo ngưỡng

let warn = self.ctx.$scope.warnTemp;

let alert = self.ctx.$scope.alertTemp;

if (temp >= alert) {

self.ctx.$scope.color = "#F44336";

self.ctx.$scope.status = "⚠ CẢNH BÁO CAO";

} else if (temp >= warn) {

self.ctx.$scope.color = "#FF9800";

self.ctx.$scope.status = "⚡ Chú ý";

} else {

self.ctx.$scope.color = "#4CAF50";

self.ctx.$scope.status = "✓ Bình thường";

}

self.ctx.detectChanges();

};

Bước 4: Settings Schema

{

"schema": {

"type": "object",

"properties": {

"title": { "title": "Tiêu đề widget", "type": "string", "default": "Nhiệt Độ" },

"warnTemp": { "title": "Ngưỡng cảnh báo (°C)", "type": "number", "default": 30 },

"alertTemp": { "title": "Ngưỡng nguy hiểm (°C)", "type": "number", "default": 40 }

}

},

"form": ["title", "warnTemp", "alertTemp"]

}

Ví Dụ 2: Widget Chart.js Time Series (biểu đồ đường)

Mục tiêu: Tạo biểu đồ đường real-time sử dụng thư viện Chart.js tích hợp
qua CDN. Đây là pattern phổ biến nhất để hiển thị dữ liệu chuỗi thời
gian.

Tab Resources — Thêm thư viện Chart.js

// Thêm URL sau vào tab Resources:

https://cdnjs.cloudflare.com/ajax/libs/Chart.js/4.4.0/chart.umd.min.js

HTML

<div style="position:relative; width:100%; height:100%;">

<canvas id="myChart_{{ctx.widgetId}}"></canvas>

</div>

<!-- Lưu ý: dùng ctx.widgetId để tạo ID unique cho mỗi widget instance -->

JavaScript — Khởi tạo và cập nhật Chart.js

let chart;

self.onInit = function() {

// BUG: canvas=null vì Angular chưa render DOM khi onInit chạy

// FIX: dùng setTimeout(..., 0) để chờ Angular render xong 1 tick

setTimeout(function() {

let canvasId = "myChart_" + self.ctx.widgetId;

let canvas = document.getElementById(canvasId);

if (!canvas) {

console.error("Canvas không tìm thấy: " + canvasId);

return;

}

let settings = self.ctx.settings;

let lineColor = settings.lineColor || "#1565C0";

chart = new Chart(canvas, {

type: "line",

data: {

labels: [],

datasets: [{

label: settings.dataLabel || "Dữ liệu",

data: [],

borderColor: lineColor,

// BUG: settings.lineColor + "33" sẽ là null+"33"="null33" khi lineColor chưa có

// FIX: tính lineColor một lần rồi dùng lại

backgroundColor: lineColor + "33",

borderWidth: 2,

fill: true,

tension: 0.3,

pointRadius: 2

}]

},

options: {

responsive: true,

maintainAspectRatio: false,

animation: { duration: 300 },

scales: {

x: { ticks: { maxTicksLimit: 8 } },

y: { title: { display: true, text: settings.yAxisLabel || "" } }

},

plugins: {

legend: { display: false },

tooltip: { mode: "index", intersect: false }

}

}

});

// Nếu đã có data trước khi chart khởi tạo xong → vẽ ngay

if (self.ctx.data && self.ctx.data.length > 0) {

self.onDataUpdated();

}

}, 0); // setTimeout 0ms = chờ Angular render 1 tick

};

self.onDataUpdated = function() {

if (!chart || !self.ctx.data || self.ctx.data.length === 0) return;

let seriesData = self.ctx.data[0].data;

chart.data.labels = seriesData.map(d =>

new Date(d[0]).toLocaleTimeString("vi-VN", { hour: "2-digit", minute: "2-digit" })

);

chart.data.datasets[0].data = seriesData.map(d => parseFloat(d[1]));

chart.update("none"); // đúng cú pháp Chart.js v4 — "none" bỏ animation

};

self.onResize = function() {

if (chart) chart.resize();

};

self.onDestroy = function() {

if (chart) { chart.destroy(); chart = null; }

};

Ví Dụ 3: RPC Control Widget (Nút Bật/Tắt Thiết Bị)

Mục tiêu: Tạo widget gửi lệnh RPC đến thiết bị IoT với nút toggle
ON/OFF. Đây là loại widget điều khiển cơ bản nhất.

HTML

<div class="rpc-container">

<div class="device-name">{{ctx.$scope.deviceName}}</div>

<button class="toggle-btn"

[class.on]="ctx.$scope.isOn"

(click)="ctx.$scope.toggle()"

[disabled]="ctx.$scope.loading">

<span *ngIf="!ctx.$scope.loading">

{{ctx.$scope.isOn ? "🔴 TẮT" : "🟢 BẬT"}}

</span>

<span *ngIf="ctx.$scope.loading">⏳ Đang gửi...</span>

</button>

<div class="status-msg">{{ctx.$scope.statusMsg}}</div>

</div>

CSS

.rpc-container { display:flex; flex-direction:column; align-items:center;

justify-content:center; height:100%; gap:12px; }

.device-name { font-size:13px; color:#777; }

.toggle-btn {

padding: 14px 40px; border-radius: 30px; border: none;

font-size: 18px; font-weight: 600; cursor: pointer;

background: #E0E0E0; color: #333; transition: all 0.3s;

}

.toggle-btn.on { background: #4CAF50; color: white; }

.toggle-btn:disabled { opacity: 0.6; cursor: not-allowed; }

.status-msg { font-size: 12px; color: #999; min-height: 18px; }

JavaScript

self.onInit = function() {

let ds = self.ctx.datasources;

self.ctx.$scope.deviceName = ds && ds[0] ? ds[0].name : "Thiết bị";

self.ctx.$scope.isOn = false;

self.ctx.$scope.loading = false;

self.ctx.$scope.statusMsg = "";

// Hàm gửi lệnh RPC

self.ctx.$scope.toggle = function() {

self.ctx.$scope.loading = true;

self.ctx.$scope.statusMsg = "";

self.ctx.detectChanges();

let newState = !self.ctx.$scope.isOn;

let method = newState ? "setValue" : "setValue";

let params = { value: newState };

// Gửi One-Way RPC (không chờ phản hồi)

// Thay bằng sendTwoWayCommand nếu cần biết kết quả

self.ctx.controlApi.sendOneWayCommand(method, params, 5000).subscribe(

function() { // Success

self.ctx.$scope.isOn = newState;

self.ctx.$scope.statusMsg = newState ? "Đã bật" : "Đã tắt";

self.ctx.$scope.loading = false;

self.ctx.detectChanges();

},

function(err) { // Error

self.ctx.$scope.statusMsg = "Lỗi: Không gửi được lệnh";

self.ctx.$scope.loading = false;

self.ctx.detectChanges();

console.error("RPC error:", err);

}

);

};

};

// Nếu thiết bị gửi trạng thái về, đọc từ subscription

self.onDataUpdated = function() {

if (self.ctx.data && self.ctx.data[0] && self.ctx.data[0].data[0]) {

let val = self.ctx.data[0].data[0][1];

self.ctx.$scope.isOn = (val === true || val === "true" || val === 1 || val === "1");

self.ctx.detectChanges();

}

};

CHƯƠNG 5: SETTINGS SCHEMA — CẤU HÌNH WIDGET LINH HOẠT

5. Settings Schema Nâng Cao

Settings Schema sử dụng JSON Schema + react-schema-form để auto-generate
form cấu hình. Đây là tính năng mạnh giúp widget của bạn linh hoạt và có
thể tái sử dụng.

5.1 Các Loại Field Hỗ Trợ

Type trong form Ý nghĩa / Kết quả hiển thị
"type": "string" Text input thông thường
"type": "number" Number input với validation số
"type": "boolean" Checkbox toggle
"type": "color" Color picker
"type": "image" Image upload/selection dialog
"type": "javascript" Code editor mode (cho custom functions)
"type": "html" HTML editor mode
"type": "css" CSS editor mode
"type": "rc-select" Dropdown select (single hoặc multiple)
"type": "array" Danh sách items có thể thêm/xóa

5.2 Ví Dụ Schema Phức Hợp

Ví dụ schema đầy đủ với nhóm, dropdown, conditional fields và color
picker:

{

"schema": {

"type": "object",

"properties": {

"display": {

"title": "Cài đặt hiển thị",

"type": "object",

"properties": {

"title": { "title": "Tiêu đề", "type": "string", "default": "Widget của tôi" },

"primaryColor":{ "title": "Màu chính", "type": "string", "default": "#1565C0" },

"showLabel": { "title": "Hiện nhãn", "type": "boolean", "default": true }

}

},

"thresholds": {

"title": "Ngưỡng cảnh báo",

"type": "object",

"properties": {

"useThresholds": { "title": "Dùng ngưỡng", "type": "boolean", "default": false },

"warnValue": { "title": "Ngưỡng cảnh báo", "type": "number", "default": 70 },

"alertValue": { "title": "Ngưỡng nguy hiểm", "type": "number", "default": 90 },

"warnColor": { "title": "Màu cảnh báo", "type": "string", "default": "#FF9800" },

"alertColor": { "title": "Màu nguy hiểm", "type": "string", "default": "#F44336" }

}

},

"chartType": {

"title": "Loại biểu đồ",

"type": "string", "default": "line"

}

}

},

"form": [

{

"key": "display",

"items": [

"display.title",

{ "key": "display.primaryColor", "type": "color" },

"display.showLabel"

]

},

{

"key": "thresholds",

"items": [

"thresholds.useThresholds",

{ "key": "thresholds.warnValue", "condition": "model.thresholds.useThresholds === true" },

{ "key": "thresholds.alertValue", "condition": "model.thresholds.useThresholds === true" },

{ "key": "thresholds.warnColor", "type": "color", "condition": "model.thresholds.useThresholds === true" },

{ "key": "thresholds.alertColor", "type": "color", "condition": "model.thresholds.useThresholds === true" }

]

},

{

"key": "chartType",

"type": "rc-select",

"multiple": false,

"items": [

{ "value": "line", "label": "Đường thẳng" },

{ "value": "bar", "label": "Cột" },

{ "value": "scatter", "label": "Phân tán" }

]

}

],

"groupInfoes": [

{ "formIndex": 0, "GroupTitle": "Hiển thị" },

{ "formIndex": 1, "GroupTitle": "Ngưỡng cảnh báo" },

{ "formIndex": 2, "GroupTitle": "Biểu đồ" }

]

}

CHƯƠNG 6: TRICKS & BEST PRACTICES TỐI ƯU

6. Tricks & Best Practices

6.1 Performance Tips

⚡ Nguyên tắc hiệu năng #1: Tránh gọi detectChanges() không cần thiết

detectChanges() kích hoạt Angular re-render. Gọi quá nhiều sẽ làm chậm widget. Chỉ gọi sau khi thực sự thay đổi $scope variables.

Trick 1: Debounce onResize để tránh render quá nhiều lần

let resizeTimer;

self.onResize = function() {

clearTimeout(resizeTimer);

resizeTimer = setTimeout(function() {

// Thực hiện resize logic ở đây

if (self.chart) {

self.chart.resize();

}

}, 100); // Chờ 100ms sau lần resize cuối cùng

};

Trick 2: Cache DOM elements trong onInit

self.onInit = function() {

// Cache lại elements thay vì query lại mỗi lần update

self.valueEl = self.ctx.$container.find(".value-display")[0];

self.statusEl = self.ctx.$container.find(".status-bar")[0];

// Sau này dùng self.valueEl thay vì document.querySelector()

};

self.onDataUpdated = function() {

if (self.valueEl) {

self.valueEl.textContent = newValue; // Nhanh hơn nhiều so với Angular binding

}

};

Trick 3: Chart.js — update("none") để tránh animation lag

// BAD: Animate mỗi lần data update (gây giật với realtime data)

chart.update();

// GOOD: Bỏ animation cho realtime, chỉ dùng animation khi user tương tác

chart.update("none");

// BETTER: Chỉ update nếu data thực sự thay đổi

self.onDataUpdated = function() {

let newData = self.ctx.data[0].data.map(d => d[1]);

let hasChanged = JSON.stringify(newData) !== JSON.stringify(self.lastData);

if (hasChanged) {

self.lastData = newData;

chart.data.datasets[0].data = newData;

chart.update("none");

}

};

6.2 Tricks Giao Tiếp Giữa Các Widget

ThingsBoard cung cấp cơ chế broadcast/subscribe để các widget trên cùng
dashboard giao tiếp với nhau:

Widget gửi dữ liệu (Publisher)

// Widget 1 gửi event với dữ liệu

self.ctx.$scope.sendData = function(value) {

self.ctx.broadcast("selectedDevice", {

deviceId: value.id,

deviceName: value.name

});

};

Widget nhận dữ liệu (Subscriber)

// Widget 2 lắng nghe event từ Widget 1

self.onInit = function() {

self.ctx.on("selectedDevice", function(data) {

self.ctx.$scope.selectedId = data.deviceId;

self.ctx.$scope.selectedName = data.deviceName;

self.ctx.detectChanges();

});

};

6.3 Tricks Xử Lý Lỗi & Edge Cases

Pattern null-safe khi đọc data

function safeGetValue(ctx, keyIndex, defaultVal) {

try {

let d = ctx.data;

if (!d || !d[keyIndex] || !d[keyIndex].data || d[keyIndex].data.length === 0) {

return defaultVal;

}

return d[keyIndex].data[0][1];

} catch(e) {

console.warn("safeGetValue error:", e);

return defaultVal;

}

}

// Sử dụng:

self.onDataUpdated = function() {

let temp = safeGetValue(self.ctx, 0, "--");

let humidity = safeGetValue(self.ctx, 1, "--");

self.ctx.$scope.temp = temp !== "--" ? parseFloat(temp).toFixed(1) : "--";

self.ctx.$scope.humidity = humidity !== "--" ? parseFloat(humidity).toFixed(0) + "%" : "--";

self.ctx.detectChanges();

};

Cleanup đúng cách để tránh memory leak

let updateInterval;

let chart;

self.onInit = function() {

// Ví dụ cần polling bên ngoài subscription

updateInterval = setInterval(function() {

// some update logic

}, 5000);

};

self.onDestroy = function() {

// ALWAYS cleanup để tránh memory leak

if (updateInterval) {

clearInterval(updateInterval);

updateInterval = null;

}

if (chart) {

chart.destroy();

chart = null;

}

// Hủy broadcast listeners

self.ctx.off("selectedDevice");

};

6.4 Tricks Responsive Design

Sử dụng onResize để responsive chart

self.onResize = function() {

let w = self.ctx.width;

let h = self.ctx.height;

// Thay đổi font size theo kích thước widget

let fontSize = Math.max(10, Math.min(24, h / 8));

self.ctx.$scope.fontSize = fontSize + "px";

// Ẩn legend khi widget quá nhỏ

if (chart) {

chart.options.plugins.legend.display = (w > 300);

chart.resize();

}

self.ctx.detectChanges();

};

📱 Mobile-First Tip

ThingsBoard 4.1+ hỗ trợ Mobile Layout riêng. Dùng CSS flex/grid thay vì fixed pixel sizes. Test widget trong Dashboard Mobile Preview (icon điện thoại góc trên phải khi chỉnh sửa dashboard) trước khi deploy.

CHƯƠNG 7: TÍCH HỢP THƯ VIỆN BÊN NGOÀI

7. Tích Hợp Thư Viện JavaScript Bên Ngoài

Tab Resources cho phép load bất kỳ thư viện JavaScript hay CSS nào qua
URL. Đây là cách tạo widget phức tạp mà không cần code từ đầu.

7.1 Danh Sách Thư Viện Phổ Biến

Thư viện Dùng cho CDN URL
Chart.js 4.x Biểu đồ line, bar, pie, radar, doughnut... cdnjs.cloudflare.com/ajax/libs/Chart.js/4.4.0/chart.umd.min.js
D3.js v7 Visualizations SVG phức tạp, custom charts cdnjs.cloudflare.com/ajax/libs/d3/7.9.0/d3.min.js
Gauge.js Đồng hồ đo (gauge widget) cdnjs.cloudflare.com/ajax/libs/gauge.js/1.3.7/gauge.min.js
Leaflet.js Bản đồ tương tác unpkg.com/leaflet@1.9.4/dist/leaflet.js
ECharts Charts phong phú, hỗ trợ 3D cdnjs.cloudflare.com/ajax/libs/echarts/5.5.0/echarts.min.js
Moment.js Xử lý date/time cdnjs.cloudflare.com/ajax/libs/moment.js/2.30.1/moment.min.js

⚠️ Lưu ý quan trọng khi dùng CDN

ThingsBoard phải có thể truy cập URL CDN. Nếu cài đặt trong mạng nội bộ không có internet, hãy upload file JS vào Resources > JavaScript Library (loại Module) hoặc self-host trên server nội bộ. Ưu tiên dùng https://cdnjs.cloudflare.com vì đây là CDN phổ biến và ổn định nhất.

7.2 Ví Dụ: Gauge Widget Với gauge.js

Resources: Thêm URL

https://cdnjs.cloudflare.com/ajax/libs/gauge.js/1.3.7/gauge.min.js

HTML

<div style="display:flex; flex-direction:column; align-items:center; justify-content:center; height:100%;">

<canvas id="gauge_{{ctx.widgetId}}" width="200" height="160"></canvas>

<div style="font-size:20px; font-weight:bold; color:#333; margin-top:-20px;">

{{ctx.$scope.displayValue}}

</div>

<div style="font-size:12px; color:#999;">{{ctx.$scope.label}}</div>

</div>

JavaScript

let gauge;

self.onInit = function() {

let s = self.ctx.settings;

let canvasId = "gauge_" + self.ctx.widgetId;

// Đợi DOM render xong

setTimeout(function() {

let target = document.getElementById(canvasId);

if (!target) return;

gauge = new Gauge(target).setOptions({

angle: -0.2,

lineWidth: 0.2,

radiusScale: 1,

pointer: { length: 0.6, strokeWidth: 0.035, color: "#000000" },

limitMax: false,

limitMin: false,

colorStart: "#6FADCF",

colorStop: "#8FC0DA",

strokeColor: "#E0E0E0",

generateGradient: true,

highDpiSupport: true,

staticLabels: {

font: "10px sans-serif",

labels: [s.minValue || 0, (s.maxValue || 100) / 2, s.maxValue || 100],

color: "#666", fractionDigits: 0

},

staticZones: [

{ strokeStyle: "#30B32D", min: s.minValue || 0, max: s.warnValue || 60 },

{ strokeStyle: "#FFDD00", min: s.warnValue || 60, max: s.alertValue || 80 },

{ strokeStyle: "#F03E3E", min: s.alertValue || 80, max: s.maxValue || 100}

],

});

gauge.maxValue = s.maxValue || 100;

gauge.setMinValue(s.minValue || 0);

gauge.animationSpeed = 32;

gauge.set(0);

self.ctx.$scope.label = s.unit || "";

self.ctx.detectChanges();

}, 100);

};

self.onDataUpdated = function() {

if (!gauge || !self.ctx.data || !self.ctx.data[0] || !self.ctx.data[0].data[0]) return;

let val = parseFloat(self.ctx.data[0].data[0][1]);

gauge.set(val);

let s = self.ctx.settings;

self.ctx.$scope.displayValue = val.toFixed(s.decimals || 1) + (s.unit ? " " + s.unit : "");

self.ctx.detectChanges();

};

self.onDestroy = function() {

gauge = null;

};

CHƯƠNG 8: QUẢN LÝ, IMPORT/EXPORT WIDGET

8. Quản Lý Widget — Import, Export, Bundle

8.1 Export Widget

Mỗi widget có thể export ra file JSON để chia sẻ hoặc backup. Vào Widget
Library → chọn widget → menu 3 chấm → Export Widget Type.

File JSON chứa toàn bộ code HTML, CSS, JS, Settings Schema và metadata
của widget.

8.2 Import Widget

  1. Vào Widget Library → mở hoặc tạo Widgets Bundle

  2. Nhấn nút "+" (góc trên phải) → chọn "Import widget type"

  3. Kéo thả file JSON hoặc chọn file từ máy

  4. Widget sẽ được thêm vào bundle và sẵn sàng sử dụng

📦 Tip: Import cả Bundle

Nếu bạn có nhiều widget liên quan, export cả Widgets Bundle (bao gồm tất cả widget types). Khi import bundle vào ThingsBoard mới, chọn "Include bundle widget types in exported data" để đảm bảo không mất widget nào.

8.3 Tổ Chức Widget Bundle Hiệu Quả

  • Mỗi project/khách hàng nên có Widgets Bundle riêng để dễ quản lý

  • Đặt tên widget rõ ràng: "[ProjectName] - [Function] - [Type]"
    (vd: "SmartFactory - Temperature Gauge - Latest")

  • Thêm mô tả cho widget giúp team dễ tìm kiếm và hiểu mục đích

  • Export bundle định kỳ để backup, lưu trên git repository

  • Dùng tag/label để phân loại widget theo chức năng

CHƯƠNG 9: CHECKLIST & LỘ TRÌNH HỌC TẬP

9. Checklist Thiết Kế Widget Chuyên Nghiệp

9.1 Checklist Trước Khi Deploy Widget

✓ Hạng mục kiểm tra
☐ Đã test với datasource "Function" trong Widget Preview
☐ Xử lý trường hợp không có data (null/undefined check)
☐ Gọi self.onDestroy() để cleanup interval, chart, listeners
☐ detectChanges() được gọi sau mỗi lần update $scope
☐ Widget responsive — test với nhiều kích thước khác nhau
☐ Settings Schema có giá trị default hợp lý cho mọi field
☐ Không có console.error khi mở DevTools
☐ Widget hoạt động đúng khi refresh trang (không bị ghost state)
☐ External libraries load từ HTTPS URL (không HTTP)
☐ Widget ID được dùng cho canvas/element ID để tránh conflict
☐ Test trên mobile/tablet nếu dashboard cần responsive
☐ Export widget JSON và lưu backup

9.2 Lộ Trình Học Tập Đề Xuất

Giai đoạn Mục tiêu Thực hành
Tuần 1-2 Nắm cơ bản: Widget Editor, 5 loại widget, cấu trúc HTML/CSS/JS Tạo widget hiển thị nhiệt độ đơn giản (Ví dụ 1), thử đổi màu, cấu hình settings
Tuần 3-4 Widget API: self.ctx, lifecycle functions, đọc dữ liệu từ subscription Tạo widget hiển thị nhiều sensor cùng lúc, dùng *ngFor trong HTML template
Tuần 5-6 Time Series + External libraries: Chart.js, Gauge.js Tạo biểu đồ đường real-time (Ví dụ 2), tạo gauge widget (Ví dụ trong Chương 7)
Tuần 7-8 RPC Control: gửi lệnh đến thiết bị, xử lý response Tạo panel điều khiển ON/OFF, slider điều chỉnh ngưỡng
Tuần 9-10 Advanced: Broadcast, responsive, performance optimization Tạo dashboard phức tạp với nhiều widget giao tiếp nhau
Nâng cao ThingsBoard Extensions (Angular components, TypeScript) Tham khảo https://github.com/thingsboard/thingsboard-extensions

9.3 Tài Nguyên Học Tập Chính Thức

🎯 Lời khuyên cuối: Học từ widget có sẵn!

Cách học hiệu quả nhất là mở các widget built-in (như "Digital Gauge", "Timeseries Line Chart") bằng cách vào Widget Library → chọn bundle → click vào widget → Edit. Đọc code HTML/CSS/JS của chúng để hiểu cách ThingsBoard team viết widget production-ready. Copy và chỉnh sửa theo nhu cầu.

Chúc bạn thành công với ThingsBoard Widget Development! 🚀

Tài liệu này được biên soạn cho ThingsBoard CE 4.2.1.1 — March 2026

(2-2/3)