Files
smartgarden_chat/lib/services/chat_service.dart
2026-06-25 17:51:36 +09:00

167 lines
4.8 KiB
Dart

import 'dart:convert';
import 'package:http/http.dart' as http;
import '../models/chat_message.dart';
class ChatService {
// 서버 URL
static const String serverUrl = 'http://49.238.167.122:8000/chat/';
// 타임아웃 설정 (초)
static const int timeoutSeconds = 30;
/// 사용자 메시지를 서버로 전송하고 응답을 받는 메서드
/// 반환값: (메시지, emotion_category) 튜플
static Future<(String, int)> sendMessage(String userMessage) async {
try {
// 요청 생성
final requestBody = {
'device_id': 1,
'locale': 'ko-KR',
'message': userMessage,
'session_id': 'session-001',
'user_id': 'user-123',
};
print('서버로 요청 전송: $requestBody');
// POST 요청 전송
final response = await http.post(
Uri.parse(serverUrl),
headers: {
'Content-Type': 'application/json',
'accept': 'application/json',
},
body: jsonEncode(requestBody),
).timeout(
const Duration(seconds: timeoutSeconds),
onTimeout: () => throw TimeoutException('서버 응답 시간 초과'),
);
print('서버 응답 상태코드: ${response.statusCode}');
print('서버 응답 본문: ${response.body}');
// 상태 코드 확인
if (response.statusCode == 200) {
// 성공
final jsonResponse = jsonDecode(response.body);
// 응답에서 'message' 필드 추출
final responseMessage = jsonResponse['message'] as String?;
// 응답에서 'emotion_category' 필드 추출 (기본값: 1)
final emotionCategory = jsonResponse['emotion_category'] as int? ?? 1;
if (responseMessage != null && responseMessage.isNotEmpty) {
print('응답 메시지: $responseMessage');
print('감정 카테고리: $emotionCategory');
return (responseMessage, emotionCategory);
} else {
print('응답이 비어있습니다');
return ('응답을 받지 못했습니다', 1);
}
} else {
// 실패
print('서버 오류: ${response.statusCode}');
return ('서버 오류 (${response.statusCode})', 1);
}
} on TimeoutException catch (e) {
print('타임아웃: $e');
return ('서버 응답이 없습니다. 시간 초과', 1);
} on FormatException catch (e) {
print('JSON 파싱 오류: $e');
return ('JSON 형식 오류', 1);
} catch (e) {
print('오류 발생: $e');
return ('오류가 발생했습니다: $e', 1);
}
}
/// 서버 연결 테스트
static Future<bool> testConnection() async {
try {
print('서버 연결 테스트 중...');
final response = await http.get(
Uri.parse(serverUrl),
).timeout(
const Duration(seconds: timeoutSeconds),
);
if (response.statusCode == 200 || response.statusCode == 405) {
print('서버 연결 성공');
return true;
} else {
print('서버 연결 실패: ${response.statusCode}');
return false;
}
} catch (e) {
print('서버 연결 오류: $e');
return false;
}
}
/// 서버 상태 상세 테스트
static Future<void> testServerDetailed() async {
print('\n=== 서버 상세 테스트 시작 ===\n');
try {
print('서버 주소: $serverUrl');
print('연결 시도 중...\n');
// 1. 연결 테스트 (GET)
print('⃣ GET 요청 테스트...');
try {
final getResponse = await http.get(
Uri.parse(serverUrl),
).timeout(const Duration(seconds: 5));
print('GET 상태코드: ${getResponse.statusCode}');
print('GET 응답: ${getResponse.body}\n');
} catch (e) {
print('GET 오류: $e\n');
}
// 2. POST 테스트 (실제 요청)
print('POST 요청 테스트...');
final testBody = {
'device_id': 1,
'locale': 'ko-KR',
'message': '테스트',
'session_id': 'session-001',
'user_id': 'user-123',
};
print('전송할 데이터: $testBody\n');
try {
final postResponse = await http.post(
Uri.parse(serverUrl),
headers: {
'Content-Type': 'application/json',
'accept': 'application/json',
},
body: jsonEncode(testBody),
).timeout(const Duration(seconds: 5));
print('POST 상태코드: ${postResponse.statusCode}');
print('POST 응답: ${postResponse.body}\n');
} catch (e) {
print('POST 오류: $e\n');
}
} catch (e) {
print('테스트 오류: $e\n');
}
print('=== 테스트 완료 ===\n');
}
}
/// 타임아웃 예외
class TimeoutException implements Exception {
final String message;
TimeoutException(this.message);
@override
String toString() => message;
}