251117 [ Day 89 ] - Project (9)

TaeHyun·2025년 11월 17일

TIL

목록 보기
105/184

시작하며

오늘도 모델 파인튜닝을 진행하면서 전에 만들어둔 채널 확인 로직을 백엔드에 연동하는 코드를 작성하였다.

channels_routes.py

# 최적조합 추천 및 선택가능 채널 확인 로직
from backend.logic.control_logic import get_available_channels, get_optimal_combination
from app.db import get_connection, close_connection
from flask import Blueprint, jsonify
import traceback

# Blueprint 생성
channels_bp = Blueprint("channels", __name__)

# 실시간 선택 가능 채널 확인
@channels_bp.route("/api/channels/available", method=["post"])
def available_channels():
    """
    실시간 선택 가능 채널 확인 및 배터리 보호
    """
    # DB에서 데이터 조회
    conn, cursor = None, None
    try:
        # DB 연결
        conn, cursor = get_connection()
        if conn is None:
            return jsonify({"message": "DB 연결 실패"}), 500
        
        # 최신 데이터 조회
        sql = "SELECT soc, solar_w FROM sun_data ORDER BY timestamp DESC LIMIT 1"
        cursor.execute(sql)
        sensor_data = cursor.fetchone()

        # 현재 사용중인 채널 확인
        #TODO 사용중인 릴레이 채널 저장 테이블 생성

        result = get_available_channels(battery=sensor_data["soc"], power=sensor_data["solaw_w"])

        return jsonify(result), 200

    except Exception as e:
        print(f"Error in check_available_channels: {e}")
        traceback.print_exc()
        return jsonify({"message": "Internal Server Error"}), 500
    
    finally:
        close_connection(conn, cursor)

# 최적 판매 조합 추천
@channels_bp.route("/api/channels/optimal", methods=["POST"])
def optimal_combination():
    """
    최적 판매 조합 추천
    """
    # DB에서 데이터 조회
    conn, cursor = None, None
    try:
        # DB 연결
        conn, cursor = get_connection()
        if conn is None:
            return jsonify({"message": "DB 연결 실패"}), 500
        
        # 최신 데이터 조회
        sql = "SELECT soc, solar_w FROM sun_data ORDER BY timestamp DESC LIMIT 1"
        cursor.execute(sql)
        sensor_data = cursor.fetchone()

        result = get_optimal_combination(battery=sensor_data["soc"], power=sensor_data["solaw_w"])

        return jsonify({'channels': result}), 200

    except Exception as e:
        print(f"Error in check_available_channels: {e}")
        traceback.print_exc()
        return jsonify({"message": "Internal Server Error"}), 500
    
    finally:
        close_connection(conn, cursor)

마치며

API 연동 자체는 미리 작성된 다른 API router 코드를 사용해서 쉽게 작성하였다. 작성을 하면서 새롭게 팀원들과 맞춰봐야 될 부분들이 있어서 정리해두었고, 내일 의논을 해봐야 될 것 같다.

profile
Hello I'm TaeHyunAn, Currently Studying Data Analysis

0개의 댓글