-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_api.py
More file actions
198 lines (159 loc) · 5.38 KB
/
test_api.py
File metadata and controls
198 lines (159 loc) · 5.38 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
from fastapi import FastAPI, Request
from fastapi.responses import FileResponse
import rclpy
from rclpy.node import Node
from std_msgs.msg import String
import os
import threading
import subprocess
from pathlib import Path
from pydantic import BaseModel
import json
import signal
import time
import httpx
import firebase_admin
from firebase_admin import messaging, credentials
app = FastAPI()
# ROS 노드 정의
class RosPublisherNode(Node):
def __init__(self):
super().__init__('fastapi_ros_node')
self.command_publisher = self.create_publisher(String, 'command', 10)
self.pixel_goal_publisher = self.create_publisher(String, 'pixel_goal', 10)
self.reexplore_publisher = self.create_publisher(String, 'reexplore', 10)
def publish_command(self, text):
msg = String()
msg.data = text
self.command_publisher.publish(msg)
self.get_logger().info(f"Published command: {text}")
def publish_pixel_goal(self, px, py):
msg = String()
msg.data = f"{px},{py}"
self.pixel_goal_publisher.publish(msg)
self.get_logger().info(f"Published pixel goal: {px},{py}")
def publish_reexplore(self):
msg = String()
self.reexplore_publisher.publish(msg)
self.get_logger().info(f"Published reexplore")
class NoiseCoordinate(BaseModel):
name: str
x: float
y: float
# ROS 노드 전역 인스턴스 생성
ros_node = None
def ros_spin_thread(node):
rclpy.spin(node)
@app.on_event("startup")
def startup_event():
global ros_node
rclpy.init()
ros_node = RosPublisherNode()
threading.Thread(target=ros_spin_thread, args=(ros_node,), daemon=True).start()
@app.on_event("shutdown")
def shutdown_event():
global ros_node
ros_node.destroy_node()
rclpy.shutdown()
@app.get("/")
def hello():
return {"message": "Hello world"}
listener_proc = None # 전역 listener 프로세스 참조
@app.post("/get-command")
async def receive_test(request: Request):
global listener_proc
# 1) JSON 파싱
try:
data = await request.json()
command = data.get("command")
if not command:
raise ValueError("`command` 필드가 없습니다.")
except Exception as e:
raise HTTPException(status_code=400, detail=str(e))
print(f"[FastAPI] 받은 명령어: {command}")
# subprocess.Popen(["ros2", "run", "hearbear", "command_listener.py"])
# 4) Listener가 spin 시작할 시간을 잠깐 줌
time.sleep(0.5)
# 5) 퍼블리시
ros_node.publish_command(command)
return {"status": "ok", "command": command}
def launch_ros2_mapping():
subprocess.Popen(["ros2", "launch", "hearbear", "cartographer_mapping.launch.py"])
@app.get("/get-map")
def get_map():
image_path = "/home/nvidia/turtlebot3_ws/map/map.png"
if os.path.exists(image_path):
return FileResponse(image_path, media_type="image/png")
else:
return {"error": "Image not found"}
@app.post('/pixel-to-navi')
async def navigate(payload: dict):
try:
px = int(payload.get('px'))
py = int(payload.get('py'))
except (ValueError, TypeError):
return {"error": "Invalid 'px' or 'py' in payload. Must be integers."}
ros_node.publish_pixel_goal(px, py)
return {'status': 'pixel goal sent', 'px': px, 'py': py}
@app.post("/request_reexplore")
async def request_reexplore():
ros_node.publish_reexplore()
return {"status": "재탐색 요청이 전달되었습니다."}
class DestinationItem(BaseModel):
category: str
px: float
py: float
DEST_PATH = Path("/home/nvidia/turtlebot3_ws/dest_list/destination.json")
@app.post("/save-destination")
async def save_destination(destinations: list[DestinationItem]):
try:
# 상위 디렉토리 생성
DEST_PATH.parent.mkdir(parents=True, exist_ok=True)
# 리스트를 dict로 변환 후 저장
data_to_save = [dest.dict() for dest in destinations]
with open(DEST_PATH, "w", encoding="utf-8") as f:
json.dump(data_to_save, f, ensure_ascii=False, indent=2)
except Exception as e:
return {"error": f"File write failed: {str(e)}"}
return {
"message": "Destination saved successfully",
"path": str(DEST_PATH),
"count": len(destinations)
}
tokens = []
cred = credentials.Certificate("serviceAccountKey.json")
firebase_admin.initialize_app(cred)
class TokenModel(BaseModel):
token: str
@app.post("/register_token")
def register_token(data: TokenModel):
tokens.append(data.token)
print("등록된 토큰: ", data.token)
return {"status":"received"}
def send_notification():
message = messaging.Message(
notification=messaging.Notification(
title="알림 제목",
body="알림 내용"
),
token="사용자_FCM_토큰"
)
response = messaging.send(message)
print("푸시 전송 성공:", response)
class PushRequest(BaseModel):
title: str
body: str
@app.post("/send_push")
def send_push(data: PushRequest):
if not tokens:
return {"error": "No token registered yet"}
message = messaging.Message(
notification=messaging.Notification(
title=data.title,
body=data.body
),
token=tokens[-1]
)
response = messaging.send(message)
print("푸시 전송 성공:", response)
return {"status": "success", "response": response}