Push Notifications (FCM)

Cấu hình Firebase Cloud Messaging để gửi push notification đến VieLang Mobile.

Push Notifications (FCM)

VieLang Mobile sử dụng Firebase Cloud Messaging (FCM) để gửi thông báo đẩy khi có alarm mới, cảnh báo hệ thống hoặc thông báo tùy chỉnh.

Bước 1: Tạo Firebase Project

  1. Vào Firebase Console
  2. Click Add project
  3. Nhập tên project → Tiếp tục
  4. Enable/disable Google Analytics → Create project

Bước 2: Bật Firebase Cloud Messaging API

  1. Vào Project Settings (icon bánh răng)
  2. Tab Cloud Messaging
  3. Nếu Cloud Messaging API bị disabled → click Manage API in Google Cloud Console
  4. Bật API

Bước 3: Lấy Service Account Key

  1. Project Settings → tab Service accounts
  2. Click Generate new private key
  3. Chọn Java format
  4. Download file .json

Bước 4: Upload Key lên VieLang IoT

  1. Đăng nhập với System Admin
  2. Vào SettingsNotificationsMobile settings
  3. Upload file JSON vừa tải
  4. Click Save

Bước 5: Thêm Firebase vào Flutter App

Cài Firebase CLI

npm install -g firebase-tools firebase login

Cài FlutterFire CLI

dart pub global activate flutterfire_cli

Configure Firebase

cd vielang-mobile flutterfire configure

Chọn Firebase project → Chọn platforms (Android + iOS) → Confirm.

File lib/firebase_options.dart sẽ được tạo tự động.


Bước 6: Cấu hình iOS (APNs)

iOS cần APNs Authentication Key để gửi notification:

  1. Vào Apple Developer Center
  2. Keys+ → Tên key → Check Apple Push Notifications service (APNs)
  3. Download file .p8

Upload lên Firebase:

  1. Firebase Console → Project Settings → Cloud Messaging tab
  2. Phần Apple app configurationUpload APNs Auth Key
  3. Upload file .p8 + Team ID + Key ID

Bước 7: Chạy và kiểm tra

flutter run --dart-define-from-file configs.json

Trong log phải thấy:

Firebase initialized FCM Token: fXBM5...

Test gửi notification từ VieLang IoT

  1. Vào Notifications+ Add notification rule
  2. Trigger: Alarm → khi alarm tạo/cleared
  3. Delivery method: Mobile (Push)
  4. Target: All users hoặc user cụ thể
  5. Lưu

Tạo alarm test → kiểm tra notification trên điện thoại.


Cấu trúc Notification

{ "title": "Cảnh báo: Nhiệt độ cao", "body": "Sensor-01: 38°C vượt ngưỡng 35°C", "data": { "entityType": "ALARM", "entityId": "alarm-uuid", "severity": "CRITICAL" } }

App tự động navigate đến màn hình alarm khi người dùng tap notification.


Troubleshooting

LỗiGiải pháp
firebase_options.dart không tồn tạiChạy flutterfire configure
Không nhận notification trên iOSKiểm tra APNs key + Xcode capabilities: Push Notifications
Không nhận notification trên AndroidKiểm tra google-services.json
MissingPluginExceptionChạy lại flutter pub get + rebuild

Notification Channels (Android)

App tự tạo notification channel:

ChannelÝ nghĩa
CRITICAL_ALARMÂm thanh to, hiển thị ngay
ALARMÂm thanh thường
INFOKhông âm thanh