Initial commit
This commit is contained in:
179
web_UI/README.md
Normal file
179
web_UI/README.md
Normal file
@@ -0,0 +1,179 @@
|
||||
# LoadCell 실시간 무게 측정 웹 GUI
|
||||
|
||||
Arduino HX711 로드셀 데이터를 실시간으로 웹 브라우저에 그래프로 표시하는 애플리케이션입니다.
|
||||
|
||||
## 시스템 구조
|
||||
|
||||
```
|
||||
[Arduino + HX711] --시리얼--> [Python 서버] --WebSocket--> [웹 브라우저]
|
||||
(Flask + pyserial) (Chart.js)
|
||||
```
|
||||
|
||||
## 기능
|
||||
|
||||
- 실시간 무게 데이터 그래프 표시
|
||||
- 현재 무게, 최대값, 평균값 통계
|
||||
- 영점 조절, 일시정지, 재시작 원격 제어
|
||||
- 시스템 로그 표시
|
||||
- 반응형 웹 디자인
|
||||
|
||||
## 설치 방법
|
||||
|
||||
### 1. Python 환경 설정
|
||||
|
||||
Python 3.7 이상이 필요합니다.
|
||||
|
||||
```bash
|
||||
# 가상환경 생성 (선택사항, 권장)
|
||||
python -m venv venv
|
||||
|
||||
# 가상환경 활성화
|
||||
# Windows:
|
||||
venv\Scripts\activate
|
||||
# macOS/Linux:
|
||||
source venv/bin/activate
|
||||
|
||||
# 필요한 패키지 설치
|
||||
pip install -r requirements.txt
|
||||
```
|
||||
|
||||
### 2. Arduino 준비
|
||||
|
||||
1. Arduino IDE에서 `LoadCellMeasure.ino` 파일을 Arduino에 업로드
|
||||
2. Arduino와 PC가 USB로 연결되어 있는지 확인
|
||||
3. Arduino IDE의 시리얼 모니터는 **닫아야 합니다** (포트 충돌 방지)
|
||||
|
||||
## 실행 방법
|
||||
|
||||
### 1. Python 서버 실행
|
||||
|
||||
```bash
|
||||
cd web_gui
|
||||
python app.py
|
||||
```
|
||||
|
||||
서버가 시작되면 다음과 같은 메시지가 표시됩니다:
|
||||
|
||||
```
|
||||
Arduino 포트 발견: COM3
|
||||
시리얼 포트 연결 성공!
|
||||
|
||||
=================================
|
||||
웹 서버 시작: http://localhost:5000
|
||||
=================================
|
||||
```
|
||||
|
||||
### 2. 웹 브라우저로 접속
|
||||
|
||||
브라우저에서 다음 주소로 접속:
|
||||
|
||||
```
|
||||
http://localhost:5000
|
||||
```
|
||||
|
||||
또는 같은 네트워크의 다른 기기에서:
|
||||
|
||||
```
|
||||
http://[서버PC의IP주소]:5000
|
||||
```
|
||||
|
||||
## 사용 방법
|
||||
|
||||
### 웹 인터페이스 기능
|
||||
|
||||
1. **실시간 그래프**: 최근 50개의 무게 데이터를 실시간으로 표시
|
||||
2. **현재 무게**: 현재 측정 중인 무게 값
|
||||
3. **통계**: 최대값과 평균값 자동 계산
|
||||
4. **제어 버튼**:
|
||||
- **영점 조절**: 로드셀 위의 물건을 치우고 영점 재설정
|
||||
- **일시정지**: 측정 일시 중지
|
||||
- **재시작**: 측정 재개
|
||||
- **그래프 초기화**: 그래프와 통계 데이터 초기화
|
||||
5. **시스템 로그**: Arduino와 서버의 메시지 표시
|
||||
|
||||
### Arduino 시리얼 명령어
|
||||
|
||||
웹 인터페이스 대신 Arduino IDE 시리얼 모니터에서도 제어 가능:
|
||||
|
||||
- `c`: 영점 조절
|
||||
- `p`: 일시정지
|
||||
- `r`: 재시작
|
||||
- `+`: 측정 속도 빠르게
|
||||
- `-`: 측정 속도 느리게
|
||||
- `h`: 도움말
|
||||
|
||||
## 프로젝트 구조
|
||||
|
||||
```
|
||||
web_gui/
|
||||
├── app.py # Flask 백엔드 서버
|
||||
├── requirements.txt # Python 패키지 목록
|
||||
├── templates/
|
||||
│ └── index.html # 웹 프론트엔드
|
||||
└── README.md # 이 파일
|
||||
```
|
||||
|
||||
## 문제 해결
|
||||
|
||||
### Arduino 포트를 찾을 수 없습니다
|
||||
|
||||
1. Arduino가 USB로 연결되어 있는지 확인
|
||||
2. Arduino IDE에서 올바른 포트가 선택되어 있는지 확인
|
||||
3. 다른 프로그램(Arduino IDE 시리얼 모니터 등)이 포트를 사용 중인지 확인
|
||||
4. `app.py` 를 수정하여 포트를 수동으로 지정:
|
||||
|
||||
```python
|
||||
# app.py 마지막 부분 수정
|
||||
port = "COM3" # 또는 /dev/ttyUSB0 (Linux), /dev/cu.usbserial (macOS)
|
||||
```
|
||||
|
||||
### 웹 페이지가 열리지 않습니다
|
||||
|
||||
1. Python 서버가 정상적으로 실행 중인지 확인
|
||||
2. 방화벽이 5000 포트를 차단하고 있는지 확인
|
||||
3. 브라우저 캐시를 삭제하고 새로고침 (`Ctrl+F5`)
|
||||
|
||||
### 데이터가 표시되지 않습니다
|
||||
|
||||
1. Arduino 시리얼 모니터가 닫혀있는지 확인 (포트 충돌)
|
||||
2. Arduino가 제대로 작동하는지 Arduino IDE 시리얼 모니터로 먼저 확인
|
||||
3. 브라우저 개발자 도구(F12)의 Console 탭에서 에러 확인
|
||||
|
||||
## 기술 스택
|
||||
|
||||
### 백엔드
|
||||
- **Flask**: 웹 서버 프레임워크
|
||||
- **pyserial**: Arduino 시리얼 통신
|
||||
- **Flask-SocketIO**: 실시간 WebSocket 통신
|
||||
- **eventlet**: 비동기 서버 처리
|
||||
|
||||
### 프론트엔드
|
||||
- **Chart.js**: 실시간 그래프 라이브러리
|
||||
- **Socket.IO**: 실시간 양방향 통신
|
||||
- **HTML/CSS/JavaScript**: 웹 인터페이스
|
||||
|
||||
## 커스터마이징
|
||||
|
||||
### 그래프 데이터 포인트 수 변경
|
||||
|
||||
`templates/index.html` 파일에서:
|
||||
|
||||
```javascript
|
||||
const maxDataPoints = 50; // 원하는 숫자로 변경
|
||||
```
|
||||
|
||||
### 측정 간격 조절
|
||||
|
||||
Arduino 코드의 `measureDelay` 변수 조절 또는 웹에서 `+`/`-` 키로 조절
|
||||
|
||||
### 서버 포트 변경
|
||||
|
||||
`app.py` 마지막 부분:
|
||||
|
||||
```python
|
||||
socketio.run(app, host='0.0.0.0', port=5000, debug=False) # 포트 번호 변경
|
||||
```
|
||||
|
||||
## 라이선스
|
||||
|
||||
이 프로젝트는 교육 및 연구 목적으로 자유롭게 사용할 수 있습니다.
|
||||
180
web_UI/app.py
Normal file
180
web_UI/app.py
Normal file
@@ -0,0 +1,180 @@
|
||||
"""
|
||||
LoadCell Weight Monitor - 실시간 무게 측정 웹 GUI
|
||||
Arduino에서 시리얼로 JSON 데이터를 받아 웹 브라우저에 실시간 그래프로 표시
|
||||
"""
|
||||
|
||||
from flask import Flask, render_template
|
||||
from flask_socketio import SocketIO
|
||||
import serial
|
||||
import serial.tools.list_ports
|
||||
import json
|
||||
import threading
|
||||
import time
|
||||
import logging
|
||||
|
||||
# Werkzeug HTTP 요청 로그 비활성화 (Socket.IO polling 로그 숨김)
|
||||
logging.getLogger('werkzeug').setLevel(logging.ERROR)
|
||||
|
||||
app = Flask(__name__)
|
||||
app.config['SECRET_KEY'] = 'loadcell_secret_2025'
|
||||
socketio = SocketIO(app, cors_allowed_origins="*")
|
||||
|
||||
# 전역 변수
|
||||
serial_port = None
|
||||
serial_thread = None
|
||||
is_running = False
|
||||
|
||||
# ===== Arduino 포트 자동 검색 =====
|
||||
def find_arduino_port():
|
||||
"""사용 가능한 Arduino 포트를 자동으로 찾습니다"""
|
||||
ports = serial.tools.list_ports.comports()
|
||||
for port in ports:
|
||||
# Arduino가 연결된 포트 찾기 (USB Serial, CH340, Arduino 등)
|
||||
if 'USB' in port.description or 'Arduino' in port.description or 'CH340' in port.description:
|
||||
return port.device
|
||||
|
||||
# 못 찾으면 사용 가능한 포트 목록 출력
|
||||
if ports:
|
||||
print("\n사용 가능한 포트:")
|
||||
for port in ports:
|
||||
print(f" - {port.device}: {port.description}")
|
||||
return ports[0].device # 첫 번째 포트 반환
|
||||
return None
|
||||
|
||||
# ===== 시리얼 데이터 읽기 스레드 =====
|
||||
def read_serial_data():
|
||||
"""Arduino로부터 시리얼 데이터를 읽어 WebSocket으로 전송"""
|
||||
global is_running, serial_port
|
||||
|
||||
error_count = 0
|
||||
max_errors = 5 # 연속 에러 허용 횟수
|
||||
|
||||
while is_running:
|
||||
try:
|
||||
if serial_port and serial_port.is_open:
|
||||
# in_waiting 호출을 안전하게 처리
|
||||
try:
|
||||
waiting = serial_port.in_waiting
|
||||
except Exception:
|
||||
waiting = 0
|
||||
|
||||
if waiting > 0:
|
||||
line = serial_port.readline().decode('utf-8', errors='ignore').strip()
|
||||
|
||||
# JSON 데이터 파싱
|
||||
if line.startswith('{') and line.endswith('}'):
|
||||
try:
|
||||
data = json.loads(line)
|
||||
socketio.emit('weight_data', data)
|
||||
print(f"Data: {data}")
|
||||
error_count = 0 # 성공 시 에러 카운트 리셋
|
||||
except json.JSONDecodeError:
|
||||
print(f"Invalid JSON: {line}")
|
||||
elif line: # 빈 줄이 아니면
|
||||
socketio.emit('log_message', {'message': line})
|
||||
print(f"Log: {line}")
|
||||
|
||||
time.sleep(0.02) # CPU 사용률 낮추기
|
||||
|
||||
except Exception as e:
|
||||
error_count += 1
|
||||
print(f"Serial error ({error_count}/{max_errors}): {e}")
|
||||
|
||||
if error_count >= max_errors:
|
||||
print("연속 에러 발생. 포트 재연결 시도...")
|
||||
socketio.emit('log_message', {'message': '시리얼 재연결 시도 중...'})
|
||||
|
||||
# 포트 재연결 시도
|
||||
try:
|
||||
if serial_port:
|
||||
serial_port.close()
|
||||
time.sleep(2)
|
||||
|
||||
port = find_arduino_port()
|
||||
if port:
|
||||
serial_port = serial.Serial(port, 9600, timeout=1)
|
||||
time.sleep(10)
|
||||
print(f"포트 재연결 성공: {port}")
|
||||
socketio.emit('log_message', {'message': f'재연결 성공: {port}'})
|
||||
else:
|
||||
print("Arduino 포트를 찾을 수 없습니다.")
|
||||
socketio.emit('log_message', {'message': 'Arduino 연결 실패'})
|
||||
except Exception as reconnect_error:
|
||||
print(f"재연결 실패: {reconnect_error}")
|
||||
|
||||
error_count = 0 # 재연결 시도 후 카운트 리셋
|
||||
|
||||
time.sleep(1)
|
||||
|
||||
# ===== Flask 라우트 =====
|
||||
@app.route('/')
|
||||
def loadcell_measure():
|
||||
"""메인 페이지"""
|
||||
return render_template('loadcell_measure.html')
|
||||
|
||||
# ===== SocketIO 이벤트 =====
|
||||
@socketio.on('connect')
|
||||
def handle_connect():
|
||||
"""클라이언트 연결"""
|
||||
print('Client connected')
|
||||
socketio.emit('log_message', {'message': 'Connected to server'})
|
||||
|
||||
@socketio.on('disconnect')
|
||||
def handle_disconnect():
|
||||
"""클라이언트 연결 해제"""
|
||||
print('Client disconnected')
|
||||
|
||||
@socketio.on('send_command')
|
||||
def handle_command(data):
|
||||
"""클라이언트에서 Arduino로 명령 전송"""
|
||||
global serial_port
|
||||
command = data.get('command', '')
|
||||
|
||||
if serial_port and serial_port.is_open:
|
||||
try:
|
||||
serial_port.write(command.encode('utf-8'))
|
||||
print(f"Sent command: {command}")
|
||||
socketio.emit('log_message', {'message': f'Command sent: {command}'})
|
||||
except Exception as e:
|
||||
print(f"Error sending command: {e}")
|
||||
socketio.emit('log_message', {'message': f'Error: {e}'})
|
||||
else:
|
||||
socketio.emit('log_message', {'message': 'Serial port not connected'})
|
||||
|
||||
# ===== 메인 실행 =====
|
||||
if __name__ == '__main__':
|
||||
# Arduino 포트 찾기
|
||||
port = find_arduino_port()
|
||||
|
||||
if port:
|
||||
print(f"\nArduino 포트 발견: {port}")
|
||||
try:
|
||||
# 시리얼 포트 열기
|
||||
serial_port = serial.Serial(port, 9600, timeout=1)
|
||||
time.sleep(5) # Arduino 리셋 대기
|
||||
print("시리얼 포트 연결 성공!")
|
||||
|
||||
# 시리얼 읽기 스레드 시작
|
||||
is_running = True
|
||||
serial_thread = threading.Thread(target=read_serial_data, daemon=True)
|
||||
serial_thread.start()
|
||||
|
||||
# Flask 서버 시작
|
||||
print("\n=================================")
|
||||
print("웹 서버 시작: http://localhost:5000")
|
||||
print("=================================\n")
|
||||
socketio.run(app, host='0.0.0.0', port=5000, debug=False)
|
||||
|
||||
except serial.SerialException as e:
|
||||
print(f"시리얼 포트 오류: {e}")
|
||||
print("Arduino가 제대로 연결되어 있는지 확인하세요.")
|
||||
except KeyboardInterrupt:
|
||||
print("\n서버 종료 중...")
|
||||
finally:
|
||||
is_running = False
|
||||
if serial_port and serial_port.is_open:
|
||||
serial_port.close()
|
||||
print("서버 종료 완료")
|
||||
else:
|
||||
print("Arduino 포트를 찾을 수 없습니다!")
|
||||
print("Arduino가 연결되어 있는지 확인하세요.")
|
||||
5
web_UI/requirements.txt
Normal file
5
web_UI/requirements.txt
Normal file
@@ -0,0 +1,5 @@
|
||||
Flask==3.0.0
|
||||
pyserial==3.5
|
||||
flask-socketio==5.3.5
|
||||
python-socketio==5.10.0
|
||||
eventlet==0.33.3
|
||||
459
web_UI/templates/loadcell_measure.html
Normal file
459
web_UI/templates/loadcell_measure.html
Normal file
@@ -0,0 +1,459 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="ko">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>LoadCell 실시간 무게 측정</title>
|
||||
|
||||
<!-- Chart.js CDN -->
|
||||
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.min.js"></script>
|
||||
|
||||
<!-- Socket.IO CDN -->
|
||||
<script src="https://cdn.socket.io/4.5.4/socket.io.min.js"></script>
|
||||
|
||||
<style>
|
||||
* {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
body {
|
||||
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
|
||||
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
||||
min-height: 100vh;
|
||||
padding: 20px;
|
||||
}
|
||||
|
||||
.container {
|
||||
max-width: 1400px;
|
||||
margin: 0 auto;
|
||||
}
|
||||
|
||||
.header {
|
||||
text-align: center;
|
||||
color: white;
|
||||
margin-bottom: 30px;
|
||||
}
|
||||
|
||||
.header h1 {
|
||||
font-size: 2.5em;
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
|
||||
.status {
|
||||
display: inline-block;
|
||||
padding: 8px 16px;
|
||||
background: rgba(255, 255, 255, 0.2);
|
||||
border-radius: 20px;
|
||||
font-size: 0.9em;
|
||||
}
|
||||
|
||||
.status.connected {
|
||||
background: rgba(76, 175, 80, 0.8);
|
||||
}
|
||||
|
||||
.main-grid {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 350px;
|
||||
gap: 20px;
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
|
||||
.card {
|
||||
background: white;
|
||||
border-radius: 15px;
|
||||
padding: 25px;
|
||||
box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
|
||||
}
|
||||
|
||||
.chart-container {
|
||||
position: relative;
|
||||
height: 400px;
|
||||
}
|
||||
|
||||
.current-weight {
|
||||
text-align: center;
|
||||
padding: 20px;
|
||||
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
||||
color: white;
|
||||
border-radius: 10px;
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
|
||||
.current-weight .value {
|
||||
font-size: 3.5em;
|
||||
font-weight: bold;
|
||||
margin: 10px 0;
|
||||
}
|
||||
|
||||
.current-weight .unit {
|
||||
font-size: 1.2em;
|
||||
opacity: 0.9;
|
||||
}
|
||||
|
||||
.controls {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
gap: 10px;
|
||||
margin-top: 20px;
|
||||
}
|
||||
|
||||
.btn {
|
||||
padding: 12px 20px;
|
||||
border: none;
|
||||
border-radius: 8px;
|
||||
font-size: 1em;
|
||||
cursor: pointer;
|
||||
transition: all 0.3s;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.btn:hover {
|
||||
transform: translateY(-2px);
|
||||
box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
|
||||
}
|
||||
|
||||
.btn-primary {
|
||||
background: #667eea;
|
||||
color: white;
|
||||
}
|
||||
|
||||
.btn-secondary {
|
||||
background: #f0f0f0;
|
||||
color: #333;
|
||||
}
|
||||
|
||||
.btn-danger {
|
||||
background: #e74c3c;
|
||||
color: white;
|
||||
}
|
||||
|
||||
.btn-success {
|
||||
background: #4CAF50;
|
||||
color: white;
|
||||
}
|
||||
|
||||
.log-container {
|
||||
background: #f8f9fa;
|
||||
border-radius: 8px;
|
||||
padding: 15px;
|
||||
height: 200px;
|
||||
overflow-y: auto;
|
||||
font-family: 'Courier New', monospace;
|
||||
font-size: 0.85em;
|
||||
}
|
||||
|
||||
.log-item {
|
||||
padding: 5px 0;
|
||||
border-bottom: 1px solid #e0e0e0;
|
||||
}
|
||||
|
||||
.stats-grid {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
gap: 15px;
|
||||
margin-top: 20px;
|
||||
}
|
||||
|
||||
.stat-item {
|
||||
text-align: center;
|
||||
padding: 15px;
|
||||
background: #f8f9fa;
|
||||
border-radius: 8px;
|
||||
}
|
||||
|
||||
.stat-label {
|
||||
font-size: 0.9em;
|
||||
color: #666;
|
||||
margin-bottom: 5px;
|
||||
}
|
||||
|
||||
.stat-value {
|
||||
font-size: 1.8em;
|
||||
font-weight: bold;
|
||||
color: #333;
|
||||
}
|
||||
|
||||
@media (max-width: 1024px) {
|
||||
.main-grid {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
<!-- Header -->
|
||||
<div class="header">
|
||||
<h1>LoadCell 실시간 무게 측정</h1>
|
||||
<div class="status" id="connectionStatus">연결 대기 중...</div>
|
||||
</div>
|
||||
|
||||
<!-- Main Grid -->
|
||||
<div class="main-grid">
|
||||
<!-- Chart Card -->
|
||||
<div class="card">
|
||||
<h2 style="margin-bottom: 20px;">실시간 무게 그래프</h2>
|
||||
<div class="chart-container">
|
||||
<canvas id="weightChart"></canvas>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Control Panel -->
|
||||
<div class="card">
|
||||
<h2 style="margin-bottom: 20px;">측정 정보</h2>
|
||||
|
||||
<!-- Current Weight Display -->
|
||||
<div class="current-weight">
|
||||
<div class="label">현재 무게</div>
|
||||
<div class="value" id="currentWeight">0.0</div>
|
||||
<div class="unit">g</div>
|
||||
</div>
|
||||
|
||||
<!-- Statistics -->
|
||||
<div class="stats-grid">
|
||||
<div class="stat-item">
|
||||
<div class="stat-label">최대값</div>
|
||||
<div class="stat-value" id="maxWeight">0.0</div>
|
||||
</div>
|
||||
<div class="stat-item">
|
||||
<div class="stat-label">평균값</div>
|
||||
<div class="stat-value" id="avgWeight">0.0</div>
|
||||
</div>
|
||||
<div class="stat-item">
|
||||
<div class="stat-label">측정 시간</div>
|
||||
<div class="stat-value" id="measureTime">0.00<span style="font-size:0.5em">초</span></div>
|
||||
</div>
|
||||
<div class="stat-item">
|
||||
<div class="stat-label">측정 간격</div>
|
||||
<div class="stat-value" id="measureDelay">10<span style="font-size:0.5em">ms</span></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 측정 속도 조절 -->
|
||||
<div style="margin-top: 20px;">
|
||||
<h3 style="margin-bottom: 10px; color: #666;">측정 속도 조절</h3>
|
||||
<div style="display: flex; align-items: center; gap: 10px;">
|
||||
<button class="btn btn-primary" onclick="sendCommand('-')" style="flex: 1; font-size: 1.5em;">-</button>
|
||||
<div style="flex: 2; text-align: center; font-size: 0.9em; color: #666;">
|
||||
느리게 / 빠르게
|
||||
</div>
|
||||
<button class="btn btn-primary" onclick="sendCommand('+')" style="flex: 1; font-size: 1.5em;">+</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Controls -->
|
||||
<div class="controls">
|
||||
<button class="btn btn-primary" onclick="sendCommand('c')">영점 조절</button>
|
||||
<button class="btn btn-secondary" onclick="sendCommand('p')">일시정지</button>
|
||||
<button class="btn btn-success" onclick="sendCommand('r')">재시작</button>
|
||||
<button class="btn btn-danger" onclick="clearChart()">그래프 초기화</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Log Card -->
|
||||
<div class="card">
|
||||
<h2 style="margin-bottom: 15px;">시스템 로그</h2>
|
||||
<div class="log-container" id="logContainer"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
// ===== Socket.IO 연결 =====
|
||||
const socket = io();
|
||||
|
||||
// ===== Chart.js 설정 =====
|
||||
const ctx = document.getElementById('weightChart').getContext('2d');
|
||||
const maxDataPoints = 50; // 최대 데이터 포인트 수
|
||||
|
||||
const weightChart = new Chart(ctx, {
|
||||
type: 'line',
|
||||
data: {
|
||||
labels: [],
|
||||
datasets: [{
|
||||
label: '무게 (g)',
|
||||
data: [],
|
||||
borderColor: '#667eea',
|
||||
backgroundColor: 'rgba(102, 126, 234, 0.1)',
|
||||
borderWidth: 2,
|
||||
tension: 0.4,
|
||||
fill: true,
|
||||
pointRadius: 3,
|
||||
pointHoverRadius: 5
|
||||
}]
|
||||
},
|
||||
options: {
|
||||
responsive: true,
|
||||
maintainAspectRatio: false,
|
||||
animation: {
|
||||
duration: 200
|
||||
},
|
||||
scales: {
|
||||
x: {
|
||||
display: true,
|
||||
title: {
|
||||
display: true,
|
||||
text: '시간'
|
||||
}
|
||||
},
|
||||
y: {
|
||||
beginAtZero: true,
|
||||
min: 0,
|
||||
max: 5000, // 최대값 5kg(5000g)로 고정
|
||||
title: {
|
||||
display: true,
|
||||
text: '무게 (g)'
|
||||
}
|
||||
}
|
||||
},
|
||||
plugins: {
|
||||
legend: {
|
||||
display: true,
|
||||
position: 'top'
|
||||
},
|
||||
tooltip: {
|
||||
enabled: true,
|
||||
backgroundColor: 'rgba(0, 0, 0, 0.8)',
|
||||
titleFont: {
|
||||
size: 14,
|
||||
weight: 'bold'
|
||||
},
|
||||
bodyFont: {
|
||||
size: 13
|
||||
},
|
||||
padding: 12,
|
||||
cornerRadius: 8,
|
||||
displayColors: true,
|
||||
callbacks: {
|
||||
title: function(context) {
|
||||
return '측정 시간: ' + context[0].label;
|
||||
},
|
||||
label: function(context) {
|
||||
const value = context.parsed.y;
|
||||
return '무게: ' + value.toFixed(2) + ' g';
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// ===== 통계 변수 =====
|
||||
let maxWeight = 0;
|
||||
let totalWeight = 0;
|
||||
let dataCount = 0;
|
||||
|
||||
// ===== Socket.IO 이벤트 핸들러 =====
|
||||
socket.on('connect', function() {
|
||||
updateConnectionStatus(true);
|
||||
addLog('서버에 연결되었습니다.');
|
||||
});
|
||||
|
||||
socket.on('disconnect', function() {
|
||||
updateConnectionStatus(false);
|
||||
addLog('서버 연결이 끊어졌습니다.');
|
||||
});
|
||||
|
||||
socket.on('weight_data', function(data) {
|
||||
const weight = data.weight;
|
||||
const time = data.time || 0;
|
||||
const delay = data.delay || 10;
|
||||
const timestamp = new Date().toLocaleTimeString();
|
||||
|
||||
// 차트 업데이트
|
||||
weightChart.data.labels.push(timestamp);
|
||||
weightChart.data.datasets[0].data.push(weight);
|
||||
|
||||
// 최대 데이터 포인트 제한
|
||||
if (weightChart.data.labels.length > maxDataPoints) {
|
||||
weightChart.data.labels.shift();
|
||||
weightChart.data.datasets[0].data.shift();
|
||||
}
|
||||
|
||||
weightChart.update('none'); // 애니메이션 없이 업데이트
|
||||
|
||||
// 현재 무게 표시
|
||||
document.getElementById('currentWeight').textContent = weight.toFixed(1);
|
||||
|
||||
// 측정 시간 표시
|
||||
document.getElementById('measureTime').innerHTML = time.toFixed(2) + '<span style="font-size:0.5em">초</span>';
|
||||
|
||||
// 측정 간격 표시
|
||||
document.getElementById('measureDelay').innerHTML = delay + '<span style="font-size:0.5em">ms</span>';
|
||||
|
||||
// 통계 업데이트
|
||||
updateStats(weight);
|
||||
});
|
||||
|
||||
socket.on('log_message', function(data) {
|
||||
addLog(data.message);
|
||||
});
|
||||
|
||||
// ===== 함수들 =====
|
||||
function updateConnectionStatus(connected) {
|
||||
const statusEl = document.getElementById('connectionStatus');
|
||||
if (connected) {
|
||||
statusEl.textContent = '연결됨';
|
||||
statusEl.classList.add('connected');
|
||||
} else {
|
||||
statusEl.textContent = '연결 끊김';
|
||||
statusEl.classList.remove('connected');
|
||||
}
|
||||
}
|
||||
|
||||
function updateStats(weight) {
|
||||
// 최대값
|
||||
if (weight > maxWeight) {
|
||||
maxWeight = weight;
|
||||
document.getElementById('maxWeight').textContent = maxWeight.toFixed(1);
|
||||
}
|
||||
|
||||
// 평균값
|
||||
totalWeight += weight;
|
||||
dataCount++;
|
||||
const avgWeight = totalWeight / dataCount;
|
||||
document.getElementById('avgWeight').textContent = avgWeight.toFixed(1);
|
||||
}
|
||||
|
||||
function sendCommand(cmd) {
|
||||
socket.emit('send_command', { command: cmd });
|
||||
}
|
||||
|
||||
function clearChart() {
|
||||
weightChart.data.labels = [];
|
||||
weightChart.data.datasets[0].data = [];
|
||||
weightChart.update();
|
||||
|
||||
// 통계 초기화
|
||||
maxWeight = 0;
|
||||
totalWeight = 0;
|
||||
dataCount = 0;
|
||||
document.getElementById('maxWeight').textContent = '0.0';
|
||||
document.getElementById('avgWeight').textContent = '0.0';
|
||||
|
||||
addLog('그래프 및 통계가 초기화되었습니다.');
|
||||
}
|
||||
|
||||
function addLog(message) {
|
||||
const logContainer = document.getElementById('logContainer');
|
||||
const logItem = document.createElement('div');
|
||||
logItem.className = 'log-item';
|
||||
|
||||
const timestamp = new Date().toLocaleTimeString();
|
||||
logItem.textContent = `[${timestamp}] ${message}`;
|
||||
|
||||
logContainer.appendChild(logItem);
|
||||
|
||||
// 자동 스크롤
|
||||
logContainer.scrollTop = logContainer.scrollHeight;
|
||||
|
||||
// 최대 100개 로그 유지
|
||||
if (logContainer.children.length > 100) {
|
||||
logContainer.removeChild(logContainer.firstChild);
|
||||
}
|
||||
}
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
Reference in New Issue
Block a user