Skip to content

BuniDev-coding/Tigersoft-project-SPU

Repository files navigation

Tigersoft Smart Office — IoT Platform

ระบบ Smart Office สำหรับตรวจสอบและควบคุมอุปกรณ์ IoT แบบ Real-time พร้อม AI Analytics, การแสดงผลแผนผังชั้น และระบบ Multi-tenant

alt text


ภาพรวมระบบ

Service Technology Port
Frontend Next.js 16 + React 19 + TypeScript :3000
Backend Go 1.24 + Chi + MongoDB :8080
AI Python + FastAPI + XGboot :8000

Infrastructure (Docker):

Service Port
MQTT (Mosquitto) 1883, 9001
Kafka 9092
Zookeeper 2181
Zigbee2MQTT 8085

🌟 ฟีเจอร์เด่นสำหรับผู้ใช้งาน (Key Features)

ระบบ Tigersoft Smart Office ถูกออกแบบมาเพื่อให้ผู้ใช้งาน (User) และผู้ดูแลอาคาร (Admin) ใช้งานได้อย่างสะดวกสบาย โดยมีฟังก์ชันเด่นดังนี้:

  • 🏢 ระบบสาขา (Multi-Tenant): รองรับการแยกข้อมูลของแต่ละสาขา/อาคาร ออกจากกันอย่างเด็ดขาด ปลอดภัยและเป็นส่วนตัว
  • 📊 แดชบอร์ดเรียลไทม์ (Live Dashboard): ดูสรุปการใช้พลังงาน (KPI), จัดอันดับอุปกรณ์กินไฟสูงสุด, และเช็คสถานะอุปกรณ์ (Online/Offline) แบบทันที
  • 🕹️ การควบคุมอุปกรณ์ (Device Control): สั่งเปิด-ปิดสวิตช์ แอร์ ปลั๊ก หรือเบรกเกอร์ผ่านหน้าเว็บได้ทันที (Real-time) และนำเข้าอุปกรณ์จากระบบ Tuya Cloud หรือค้นหาในเครือข่ายภายในได้ง่ายๆ
  • 🕒 ระบบตั้งเวลาอัตโนมัติ (Schedules): ตั้งเวลาเปิด-ปิดอุปกรณ์ล่วงหน้า เลือกทำซ้ำตามวันเวลา หรือตั้งเงื่อนไขขั้นสูง
  • 🗺️ แผนผังอาคาร (Floor Plans): อัปโหลดรูปแปลนตึก และปักหมุดไอคอนอุปกรณ์ไว้ตามห้องต่างๆ เพื่อให้ผู้ใช้กดสั่งการจากภาพแผนผังได้เลย
  • 📈 พยากรณ์พลังงานล่วงหน้า (AI Forecasting): AI คาดการณ์แนวโน้มค่าไฟฟ้าล่วงหน้า 30 วัน จากประวัติการใช้งาน (ด้วยโมเดล XGBoost)
  • 🚨 ระบบดักจับไฟผิดปกติ (Anomaly Detection): AI ทำหน้าที่ดักจับพฤติกรรมใช้ไฟที่สูงผิดปกติ หากพบว่ามีความเสี่ยงจะขึ้นแจ้งเตือนทันที
  • 💡 ผู้ช่วยที่ปรึกษา AI (Gemini Insights): มีระบบ Google Gemini คอยวิเคราะห์กราฟและสรุปเป็นคำแนะนำภาษาคน เพื่อช่วยประหยัดไฟในแต่ละเดือน
  • 💬 แชทบอทพลังงาน (Energy Chatbot): สามารถพิมพ์แชทสอบถามสถานะพลังงานในออฟฟิศได้จากหน้าจอ โดย AI จะไปดึงข้อมูลมาตอบให้
  • 🔔 ระบบแจ้งเตือนฉุกเฉิน (Notifications & Alerts): แจ้งเตือนเหตุการณ์บนหน้าเว็บ (In-app) และสามารถ ส่งแจ้งเตือนเข้า Line / Email ทันทีเมื่อเกิดไฟกระชาก หรือโหลดกระแสไฟเกินพิกัดวิกฤต

สถาปัตยกรรมระบบ

                          ┌─────────────────────────────────┐
                          │      Next.js Frontend (:3000)   │
                          │  Dashboard · Control · Analytics │
                          └──────────┬──────────┬───────────┘
                                     │ REST API  │ WebSocket
                          ┌──────────▼──────────▼───────────┐
                          │      Go Backend (:8080)          │
                          │  Hexagonal Architecture          │
                          │  JWT Auth · RBAC · Swagger       │
                          └───┬─────────┬──────────┬────────┘
                              │         │           │
               ┌──────────────▼─┐  ┌────▼────┐  ┌──▼──────────┐
               │  MongoDB Atlas  │  │  MQTT   │  │    Kafka    │
               │  3 Databases   │  │ Broker  │  │   :9092     │
               └────────────────┘  └────┬────┘  └──┬──────────┘
                                        │           │
               ┌────────────────────────▼─┐  ┌─────▼────────────┐
               │  IoT Devices             │  │  AI Service       │
               │  Tuya Cloud / Local      │  │  FastAPI + Prophet│
               │  Zigbee2MQTT             │  │  Forecasting      │
               └──────────────────────────┘  └──────────────────┘

โครงสร้างโปรเจกต์

Tigersoft-project-SPU/
├── Frontend/          # Next.js 16 — Dashboard & UI
├── Backend/           # Go 1.24 — API & IoT Bridge
├── Ai/                # Python FastAPI — AI Analytics
├── Readme.md          # ไฟล์นี้
└── image.png

Frontend

Tech Stack

Library Version ใช้สำหรับ
Next.js (App Router) 16.1.7 Framework หลัก
React 19.2.3 UI Library
TypeScript 5.9.3 Type Safety
Tailwind CSS 4.2.2 Styling (primary: #C10016)
Three.js 0.182.0 3D Visualization
Zustand 5.0.12 Global State
Recharts 3.8.0 Charts & Graphs
Framer Motion 12.38.0 Animations
react-use-websocket 4.13.0 Real-time WebSocket

โครงสร้าง

Frontend/
├── app/                      # Pages (App Router)
│   ├── login/
│   ├── dashboard/
│   ├── control/
│   ├── devicemanagement/[id]/
│   ├── schedule/
│   ├── analyticspower/
│   ├── analyticsai/
│   ├── settings/
│   │   ├── general/
│   │   ├── profile/
│   │   ├── security/password/
│   │   └── connection/       # MQTT, Tuya, Zigbee config
│   └── tenants/[id]/
├── components/               # Reusable UI Components
│   └── ui/
│       ├── common/           # Notification, Pagination, RoleGuard, Search
│       ├── modal/            # CRUD Modals
│       ├── navigation/       # Sidebar, Navbar, SubMenu
│       └── tables/           # Device, User, Tenant tables
├── features/                 # Feature-based Business Logic
│   ├── Analytics/            # 3D + AI Predictions
│   ├── AnalyticsAI/          # Energy Charts & Anomaly Alerts
│   ├── Control/              # Device Control
│   ├── DeviceManagement/     # Device CRUD
│   ├── Monitoring/           # Dashboard KPI & Summary
│   ├── Schedule/             # Automation Scheduling
│   ├── Settings/             # System Config
│   └── UserManagement/       # User CRUD
├── lib/
│   ├── api/api-client.ts     # Centralized API client
│   ├── hooks/useSensorSocket.ts
│   ├── stores/useSensorStore.ts
│   └── types/
└── context/
    └── AuthContext.tsx

ติดตั้งและรัน

cd Frontend
pnpm install    # หรือ npm install

# สร้างไฟล์ .env.local
NEXT_PUBLIC_API_URL=http://localhost:8080
NEXT_PUBLIC_WS_URL=ws://localhost:8080/ws

pnpm dev        # Development — http://localhost:3000
pnpm build      # Production build
pnpm start      # Start production server
pnpm lint       # Run ESLint

Backend

Tech Stack

Library Version ใช้สำหรับ
Go 1.24.0 Language
Chi 5.2.0 HTTP Router
MongoDB Driver 1.13.1 Database
Gorilla WebSocket 1.5.0 Real-time communication
JWT (golang-jwt) 5.2.0 Authentication
Paho MQTT 1.4.3 IoT Messaging
Kafka-go 0.4.47 Event Streaming
Swag 1.16.6 Swagger Doc Generation
Cron v3 3.0.1 Job Scheduling

สถาปัตยกรรม (Hexagonal)

internal/
├── core/
│   ├── domain/      # Business Entities (Device, User, Schedule, ...)
│   ├── services/    # Business Logic
│   └── ports/       # Interface Contracts
└── adapters/
    ├── http/        # HTTP Handlers & Routing (~30+ endpoints)
    ├── auth/        # JWT, Microsoft OAuth, Middleware
    ├── repository/  # MongoDB Implementations
    ├── tuya/        # Tuya Cloud API + Local Control
    ├── mqtt/        # MQTT Client
    ├── websocket/   # WebSocket Real-time
    ├── queue/       # Kafka Adapter
    └── bridge/      # MQTT → Kafka Bridge

ความต้องการของระบบ

ซอฟต์แวร์ เวอร์ชัน
Go 1.24.0+
MongoDB Atlas (cloud) หรือ local
MQTT Broker (Mosquitto) localhost:1883
Python 3.x สำหรับ Tuya local control
Kafka optional — สำหรับ AI pipeline
Zigbee2MQTT optional — สำหรับ Zigbee devices

Environment Variables

สร้างไฟล์ .env ใน Backend/:

# MongoDB
MONGO_URI=mongodb+srv://<user>:<pass>@<cluster>.mongodb.net
MONGO_DB_AUTH=smart_office_auth
MONGO_DB_DASHBOARD=smart_office_dashboard
MONGO_DB_RAW=smart_office_raw
MONGO_FLUSH_INTERVAL=10m

# JWT
JWT_SECRET=<256-bit-secret>
JWT_EXPIRY=30m
SUPER_ADMIN_EMAIL=[email protected]

# MQTT
MQTT_BROKER=localhost
MQTT_PORT=1883

# Device Polling
POLL_INTERVAL=2
POLL_DELAY=100ms

# Microsoft OAuth (optional)
OAUTH_CLIENT_ID=
OAUTH_CLIENT_SECRET=
OAUTH_REDIRECT_URL=http://localhost:8080/api/auth/oauth/callback

# Kafka (optional)
KAFKA_BROKER=127.0.0.1:9092
ENABLE_MQTT_KAFKA_BRIDGE=true
KAFKA_AI_BROKER=localhost:9092
KAFKA_AI_TOPIC=smart_office_device_data

# Zigbee (optional)
ZIGBEE2MQTT_ENABLED=false
ZIGBEE_MQTT_BROKER=localhost
ZIGBEE_MQTT_PORT=1883
ZIGBEE_BASE_TOPIC=zigbee2mqtt

# Tuya Local Control
TUYA_USE_LOCAL=true
TUYA_WRAPPER_PATH=tools/tuya_local_wrapper.py

ติดตั้งและรัน

cd Backend

# 1. ตั้งค่า Environment
cp .env.example .env

# 2. รัน Infrastructure (Docker)
docker-compose up -d

# 3. รัน Backend
go run ./cmd/server
# หรือ build binary
go build -o tuya-bridge.exe ./cmd/server && ./tuya-bridge.exe
# หรือ Windows batch script
run_bridge.bat

Server รันบน port 8080

Batch Scripts (Windows)

Script หน้าที่
run_bridge.bat Build และรัน backend server
run_docker.bat รัน Docker infrastructure
run_swag.bat สร้าง Swagger docs
run_scan.bat Scan/discover devices
run_get_keys.bat ดึง Tuya device keys

API Endpoints

Base URL: http://localhost:8080/api

Authentication (Public)

Method Path คำอธิบาย
POST /auth/login Login ด้วย Email/Password
GET /auth/oauth/microsoft เริ่ม Microsoft OAuth
GET /auth/oauth/callback OAuth Callback
POST /auth/logout Logout
GET /auth/me ข้อมูล User ปัจจุบัน

User Management (Admin)

Method Path คำอธิบาย
GET /users รายชื่อ Users ทั้งหมด
POST /users สร้าง User ใหม่
PUT /users/update แก้ไข User
DELETE /users/delete ลบ User
PUT /users/role เปลี่ยน Role
PUT /users/permissions แก้ไข Permissions
POST /users/change-password เปลี่ยนรหัสผ่าน

Devices (Authenticated)

Method Path คำอธิบาย
GET /devices รายการ Devices พร้อม Live Status
POST /devices เพิ่ม Device ด้วยตนเอง
PUT /devices แก้ไข Device
DELETE /devices ลบ Device
POST /devices/control ส่งคำสั่งควบคุม Device
POST /devices/import Import Devices จาก Tuya
GET /devices/discover ค้นหา Devices ในเครือข่าย

Analytics & Telemetry

Method Path คำอธิบาย
GET /telemetry/stats สถิติการใช้พลังงาน
GET /telemetry/logs Raw Telemetry Logs
GET /analytics/overview ภาพรวมระบบ
GET /analytics/energy พลังงานวันนี้
GET /analytics/top อุปกรณ์ที่ใช้พลังงานสูงสุด
GET /analytics/dashboard Dashboard Metrics

Schedules

Method Path คำอธิบาย
GET /schedules รายการ Schedules
POST /schedules สร้าง Schedule
PUT /schedules แก้ไข Schedule
DELETE /schedules ลบ Schedule

Floor Plans

Method Path คำอธิบาย
GET /floorplans รายการผังชั้น
POST /floorplans/create สร้างผังชั้นใหม่
POST /floorplans อัปโหลดรูปผังชั้น
DELETE /floorplans ลบผังชั้น
GET /floorplans/image ดึงรูปผังชั้น
PUT /floorplans/rename เปลี่ยนชื่อผังชั้น
PUT /floorplans/widgets บันทึก Widgets บนผังชั้น

WebSocket

ws://localhost:8080/ws

รับ Real-time updates: สถานะ Devices, Notifications, Telemetry

ดู Swagger UI ที่ http://localhost:8080/swagger/ สำหรับ Endpoints ทั้งหมด

Database (MongoDB)

Database Collections หน้าที่
smart_office_auth users, sessions, tenants Authentication
smart_office_dashboard devices, schedules, floorplans, notifications, groups, daily_usage Application Data
smart_office_raw device_raw_data (TTL 180 วัน) Raw Telemetry

Services หลัก

Service หน้าที่
BridgeService Poll devices ทุก 2 วินาที, คำนวณพลังงาน, ส่งคำสั่ง
NotificationService แจ้งเตือน Events ผ่าน WebSocket
SchedulerService รัน Automation Cron Jobs
ZigbeeService จัดการ Zigbee Devices ผ่าน MQTT
DiscoveryService ค้นหา Devices ในเครือข่าย

Role-Based Access Control

Role สิทธิ์
super_admin เข้าถึงทุกอย่าง รวมถึง Tenant management
admin จัดการ Users, Devices, Settings ของ Tenant ตัวเอง
user ดูข้อมูลและควบคุม Devices ตาม Permissions

AI Service

Tech Stack

Library Version ใช้สำหรับ
FastAPI 0.104.1 Web Framework
XGBoost 2.1.0 Time Series Forecasting
scikit-learn 1.4.0 Anomaly Detection (Isolation Forest)
Pandas 2.2.0 Data Processing
NumPy 1.26.0 Numerical Computation
PyMongo 4.6.1 MongoDB Client
kafka-python-ng 2.0.3 Kafka Consumer
asyncio-mqtt 0.16.1 Async MQTT Client
google-generativeai 0.5.0 AI Insight & Chatbot (Gemini)

โครงสร้าง

Ai/
├── main.py                    # FastAPI Server + Background Jobs
├── forecast_electricity.py    # XGBoost-based Electricity Forecasting
├── anomaly_detection.py       # Isolation Forest Anomaly Detection
├── kafka_consumer.py          # Kafka Consumer + MongoDB Persistence
├── cache_manager.py           # In-memory Cache with TTL
└── requirements.txt

Features

Feature คำอธิบาย
Electricity Forecast พยากรณ์การใช้พลังงาน 1/7/30 วันล่วงหน้าด้วย XGBoost
Anomaly Detection ตรวจจับพฤติกรรมผิดปกติของอุปกรณ์แบบ Real-time
AI Insights (Gemini) วิเคราะห์พฤติกรรมการใช้ไฟและให้คำแนะนำภาษาคน
Energy Chatbot ตอบคำถามเรื่องพลังงานและสรุปสถานะอุปกรณ์
Dashboard Cache Pre-compute Dashboard Data ทุก 10 นาที
Daily Job สร้าง 1-day Forecast อัตโนมัติทุกเที่ยงคืน

API Endpoints (AI Service)

Method Path คำอธิบาย
GET /forecast พยากรณ์การใช้พลังงาน
GET /anomalies รายการ Anomalies ที่ตรวจพบ
GET /dashboard Dashboard Metrics (Cached)
GET /health Health Check

ติดตั้งและรัน

cd Ai
pip install -r requirements.txt
python main.py   # http://localhost:8000

Quick Start (ทั้งระบบ)

# 1. รัน Infrastructure
cd Backend
docker-compose up -d

# 2. รัน Backend
go run ./cmd/server
# Server: http://localhost:8080

# 3. รัน AI Service (Terminal ใหม่)
cd ../Ai
python main.py
# AI API: http://localhost:8000

# 4. รัน Frontend (Terminal ใหม่)
cd ../Frontend
pnpm install
pnpm dev
# App: http://localhost:3000

IoT Integrations

Integration Protocol คำอธิบาย
Tuya Cloud HTTPS จัดการและ Import อุปกรณ์ผ่าน Tuya Cloud API
Tuya Local TCP ควบคุมอุปกรณ์ในเครือข่ายโดยตรง (Python wrapper)
MQTT MQTT รับ-ส่งข้อมูลอุปกรณ์ผ่าน Mosquitto Broker
Zigbee Zigbee รองรับอุปกรณ์ Zigbee ผ่าน Zigbee2MQTT
Kafka TCP ส่งข้อมูลอุปกรณ์ไปยัง AI Pipeline

Swagger Documentation

# สร้าง Swagger Docs
cd Backend
run_swag.bat
# หรือ
swag init -g cmd/server/main.go -o docs

# เปิด Swagger UI
http://localhost:8080/swagger/

About

Final-Project of SPU : Bachelor’s degree Conputer Engineering

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors