-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
251 lines (213 loc) · 7.18 KB
/
Copy pathmain.js
File metadata and controls
251 lines (213 loc) · 7.18 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
const BACKEND_URL = "https://floralen-backend.vercel.app";
const DEVICE_ID = "FLORA_01";
let currentSessionId = null;
let videoTrack = null; // Biến lưu track video để bật flash
// 1. Camera Init & Flashlight Setup
async function initCamera() {
try {
const stream = await navigator.mediaDevices.getUserMedia({
video: {
facingMode: "environment",
// Yêu cầu nâng cao để lấy quyền điều khiển đèn flash
advanced: [{ torch: true }],
},
});
const video = document.getElementById("video");
video.srcObject = stream;
// Lưu track để dùng cho Flash
videoTrack = stream.getVideoTracks()[0];
// Kiểm tra xem máy có hỗ trợ Flash không để hiện nút
const capabilities = videoTrack.getCapabilities();
if (capabilities.torch) {
$("#flash-btn").removeClass("hidden");
}
} catch (err) {
console.error("Camera Error:", err);
alert("Không thể truy cập camera hoặc đèn flash.");
}
}
// 2. Logic Bật/Tắt Đèn Flash
let isFlashOn = false;
$("#flash-btn").click(async () => {
if (!videoTrack) return;
isFlashOn = !isFlashOn;
try {
await videoTrack.applyConstraints({
advanced: [{ torch: isFlashOn }],
});
// Toggle UI
if (isFlashOn) {
$("#flash-btn").addClass("active");
$("#flash-btn i").removeClass("fa-bolt").addClass("fa-lightbulb"); // Đổi icon
} else {
$("#flash-btn").removeClass("active");
$("#flash-btn i").removeClass("fa-lightbulb").addClass("fa-bolt");
}
} catch (e) {
console.error("Flash Error:", e);
alert("Không thể bật đèn flash trên thiết bị này.");
}
});
// 3. Logic Chụp Ảnh & Scan (Giữ nguyên logic cũ)
$("#capture-btn").click(async () => {
const video = document.getElementById("video");
const canvas = document.getElementById("canvas");
const context = canvas.getContext("2d");
canvas.width = video.videoWidth;
canvas.height = video.videoHeight;
context.drawImage(video, 0, 0);
$("#loading").removeClass("hidden");
canvas.toBlob(
async (blob) => {
const formData = new FormData();
formData.append("image", blob, "capture.jpg");
formData.append("device_id", DEVICE_ID);
try {
const res = await fetch(`${BACKEND_URL}/api/scan-now`, {
method: "POST",
body: formData,
});
const data = await res.json();
if (data.analysis) {
showResults(data);
}
} catch (error) {
alert("Lỗi kết nối server!");
} finally {
$("#loading").addClass("hidden");
}
},
"image/jpeg",
0.8,
);
});
// 4. Logic UI Kết quả
function showResults(data) {
// Ẩn nút chụp, hiện popup
$("#capture-btn").addClass("hidden");
openSheet();
$("#plant-status").text(data.analysis.status);
$("#ai-diagnosis").text(data.analysis.title);
$("#action-badge").text(data.analysis.advice);
$("#soil-val").text(`${data.sensor_data?.soil_moisture || "--"}%`);
$("#bat-val").text(`${data.sensor_data?.battery_level || "--"}V`);
currentSessionId = data.session_id;
$("#chat-history").empty();
if (data.analysis.chat_opening) {
appendMessage("ai", data.analysis.chat_opening);
}
}
// 5. Logic Chat
$("#send-btn").click(sendMessage);
$("#user-input").keypress((e) => {
if (e.which == 13) sendMessage();
});
async function sendMessage() {
const text = $("#user-input").val().trim();
if (!text || !currentSessionId) return;
appendMessage("user", text);
$("#user-input").val("");
try {
const res = await fetch(`${BACKEND_URL}/api/chat`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
session_id: currentSessionId,
device_id: DEVICE_ID,
user_message: text,
}),
});
const data = await res.json();
if (data.reply) appendMessage("ai", data.reply);
} catch (error) {
appendMessage("ai", "Mất kết nối...");
}
}
function appendMessage(role, text) {
const cssClass = role === "user" ? "user-msg" : "ai-msg";
const html = `<div class="msg ${cssClass}">${text}</div>`;
$("#chat-history").append(html);
const chatHistory = document.getElementById("chat-history");
chatHistory.scrollTop = chatHistory.scrollHeight;
}
// --- 6. LOGIC KÉO THẢ & ĐÓNG/MỞ POPUP (CẬP NHẬT) ---
const sheet = document.getElementById("bottom-sheet");
const dragArea = document.querySelector(".drag-handle-area");
const reopenBtn = document.getElementById("reopen-chat-btn");
const closeSheetBtn = document.getElementById("close-sheet-btn"); // Nút X
let startY = 0;
let isDragging = false;
let sheetState = "closed"; // 'closed', 'half', 'full'
// Mở Sheet
function openSheet() {
sheet.classList.remove("hidden");
// Cần timeout nhỏ để browser render xong display:block rồi mới transform
setTimeout(() => {
sheetState = "half";
sheet.style.transform = `translateY(0)`; // Về vị trí gốc (đã set height 60vh trong css)
sheet.classList.remove("fullscreen");
reopenBtn.classList.add("hidden");
$("#capture-btn").addClass("hidden"); // Ẩn nút chụp khi đang chat
}, 10);
}
// Đóng Sheet
function closeSheet() {
sheetState = "closed";
sheet.style.transform = `translateY(100%)`; // Đẩy xuống dưới
setTimeout(() => {
sheet.classList.add("hidden");
reopenBtn.classList.remove("hidden"); // Hiện nút mở lại
$("#capture-btn").removeClass("hidden"); // Hiện nút chụp
}, 300);
}
// Sự kiện Nút X và Nút Mở lại
$("#close-sheet-btn").click(closeSheet);
$("#reopen-chat-btn").click(openSheet);
// Sự kiện Kéo thả (Real-time Dragging)
dragArea.addEventListener("touchstart", (e) => {
startY = e.touches[0].clientY;
isDragging = true;
sheet.style.transition = "none"; // Tắt animation để kéo mượt
});
dragArea.addEventListener("touchmove", (e) => {
if (!isDragging) return;
const currentY = e.touches[0].clientY;
const deltaY = currentY - startY;
// Logic kéo trực quan
if (sheetState === "half") {
const percentMoved = (deltaY / window.innerHeight) * 100;
// Chỉ cho phép kéo xuống (positive) hoặc kéo lên 1 chút (negative)
if (percentMoved > -20) {
sheet.style.transform = `translateY(${percentMoved}%)`;
}
}
});
dragArea.addEventListener("touchend", (e) => {
isDragging = false;
sheet.style.transition = "transform 0.3s cubic-bezier(0.25, 1, 0.5, 1)"; // Bật lại animation
const endY = e.changedTouches[0].clientY;
const deltaY = endY - startY;
if (sheetState === "half") {
if (deltaY < -50) {
// Kéo lên mạnh -> Fullscreen
sheetState = "full";
sheet.classList.add("fullscreen");
sheet.style.transform = `translateY(0)`;
} else if (deltaY > 50) {
// Kéo xuống mạnh -> Đóng
closeSheet();
} else {
// Kéo nhẹ -> Trả về vị trí Half
sheet.style.transform = `translateY(0)`;
}
} else if (sheetState === "full") {
if (deltaY > 50) {
// Từ full kéo xuống -> Half
sheetState = "half";
sheet.classList.remove("fullscreen");
sheet.style.transform = `translateY(0)`;
}
}
});
// Khởi chạy
initCamera();