어제 수업이 끝나기 전에 아두이노와 와이파이 통신을 하여 서버에서 데이터를 전달하는 테스트를 해보았는데 실패를 해서 해당 부분을 조사해보니, 이번에 사용하는 와이파이 모듈은 따로 IP를 가지고 있지 않아 서버에서 POST는 불가능하고 아두이노가 주기적으로 서버에 요청을 하여 반환하는 구조를 사용해야 되는 것을 알게 되었다. 따라서 기존 릴레이 채널 제어를 2가지로 변경하는 작업을 진행하였다.
@relay_bp.route("/api/relay/update", methods=["POST"])
def update_relay():
data = request.get_json() # 웹에서 보낸 JSON 수신 (예: {"A": true, "B": false, ...})
# 데이터 유효성 검사
if not data or "A" not in data or "B" not in data or "C" not in data or "D" not in data:
print("\n릴레이 유효성 검사 : 필수 데이터 누락")
return jsonify({"message": "Relay : Missing required fields"}), 400
# 현재 릴레이 상태 조회
current_status, message, status_code = get_current_relay_status()
if current_status is None:
return jsonify({"message": message}), status_code
# DB 저장 함수 호출
success, message, status_code = update_relay_status_in_db(data)
if not success:
return jsonify({"message": message}), status_code
# 거래 내역 DB에 저장
success, message, status_code = save_relay_state_changes(data, current_status)
return jsonify({"message": message}), status_code
@relay_bp.route("/api/relay/control", methods=["POST"])
def control_relay():
# DB 최신 상태 조회
current_status, message, status_code = get_current_relay_status()
if current_status is None:
return jsonify({"message": message}), status_code
# 결과 가공 (JSON 형식 변경)
status_map = {key: (value == "on") for key, value in current_status.items()}
print("\n릴레이 제어 : DB 상태 응답 전송")
return jsonify(status_map), status_code
# 거래 내역 DB에 저장
def save_relay_state_changes(data, current_status):
"""
릴레이 변경 사항(OFF -> ON)을 DB에 저장
"""
for channel, new_state in data.items():
old_state = current_status.get(channel, "off")
if old_state == "off" and new_state == True:
# 채널명을 buyer_id로 변환
buyer_id = get_buyer_id_from_channel(channel)
# 채널별 소비전력 조회
amount = CHANNEL_CONFIG.get(channel)
if buyer_id in [1,2,3,4] and amount >= 0:
# DB에 거래 내역 저장
success, message, status_code = insert_trade_history(buyer_id, amount)
if not success:
print(f"저장 실패 : ({channel}) / {message}")
return success, message, status_code
else:
print(f"성공 내역 : ({channel}) / {amount}W")
else:
print("\n릴레이 제어 : 필수 데이터 입력값 오류")
return False, "Invalid input values", 400
print("\n릴레이 제어 : 저장 완료")
return True, "Relay state updated successfully", 201
/api/relay/update에서는 웹 요청값과 거래 내역을 DB에 업데이트하는 엔드포인트이고, /api/relay/control은 아두이노에서 해당 엔드포인트를 요청하면 DB에 저장되어 있는 릴레이 채널 상태를 JSON 형식으로 반환하는 엔드포인트이다.
이번에 수정한 엔드포인트만 잘 동작이 되면 아두이노 회로를 꾸미고 발표 준비를 할 단계이다.