File size: 18,378 Bytes
460bd69
17f5a8a
460bd69
 
 
 
 
 
 
 
 
 
 
7cef4b0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17f5a8a
460bd69
 
 
17f5a8a
460bd69
17f5a8a
 
 
d3f3344
 
17f5a8a
d3f3344
7cef4b0
 
17f5a8a
7cef4b0
 
17f5a8a
 
 
 
 
 
 
 
 
d3f3344
17f5a8a
 
 
 
 
 
 
 
 
 
 
d3f3344
17f5a8a
 
 
 
 
 
 
 
 
 
d3f3344
17f5a8a
 
d3f3344
17f5a8a
d3f3344
17f5a8a
460bd69
d3f3344
 
 
17f5a8a
d3f3344
7cef4b0
 
460bd69
 
17f5a8a
 
 
d3f3344
17f5a8a
d3f3344
 
 
17f5a8a
 
460bd69
17f5a8a
 
460bd69
 
17f5a8a
d3f3344
17f5a8a
460bd69
 
 
 
 
17f5a8a
460bd69
7cef4b0
 
 
 
17f5a8a
 
460bd69
17f5a8a
 
 
 
 
 
 
 
 
 
 
460bd69
17f5a8a
 
 
 
460bd69
 
17f5a8a
460bd69
17f5a8a
460bd69
 
 
 
 
 
17f5a8a
460bd69
 
 
 
 
17f5a8a
 
460bd69
17f5a8a
460bd69
 
 
 
17f5a8a
 
460bd69
 
 
 
 
17f5a8a
460bd69
7cef4b0
 
 
 
17f5a8a
 
 
460bd69
17f5a8a
 
 
 
 
 
 
 
 
 
 
460bd69
17f5a8a
 
 
 
460bd69
 
17f5a8a
460bd69
17f5a8a
460bd69
 
 
 
 
 
17f5a8a
460bd69
 
 
 
 
 
17f5a8a
460bd69
17f5a8a
460bd69
 
 
 
17f5a8a
 
460bd69
 
 
 
 
17f5a8a
460bd69
7cef4b0
 
 
460bd69
7cef4b0
17f5a8a
460bd69
 
17f5a8a
 
 
460bd69
17f5a8a
 
 
 
 
 
 
 
 
 
 
 
 
460bd69
17f5a8a
 
 
 
460bd69
 
17f5a8a
 
 
460bd69
 
 
 
 
 
17f5a8a
460bd69
 
 
 
 
 
17f5a8a
460bd69
17f5a8a
460bd69
 
 
63f77d7
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
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
"""
RAG ๊ฒ€์ƒ‰ ์ฑ—๋ด‡ ์›น ์• ํ”Œ๋ฆฌ์ผ€์ด์…˜ - ์žฅ์น˜ ๊ด€๋ฆฌ API ๋ผ์šฐํŠธ ์ •์˜ (API ๊ฒฝ๋กœ ์ˆ˜์ •๋จ)
"""

import logging
import requests
from flask import request, jsonify

# ๋กœ๊ฑฐ ๊ฐ€์ ธ์˜ค๊ธฐ
logger = logging.getLogger(__name__)

def register_device_routes(app, login_required, DEVICE_SERVER_URL):
    """Flask ์• ํ”Œ๋ฆฌ์ผ€์ด์…˜์— ์žฅ์น˜ ๊ด€๋ฆฌ ๊ด€๋ จ ๋ผ์šฐํŠธ ๋“ฑ๋ก"""
    
    # ์‚ฌ์šฉ์ž ์ง€์ • ์žฅ์น˜ ์„œ๋ฒ„ URL ๋ณ€์ˆ˜
    custom_device_url = None
    
    # URL ์„ค์ • ํ•จ์ˆ˜
    def get_device_url():
        # ์‚ฌ์šฉ์ž ์ง€์ • URL์ด ์žˆ์œผ๋ฉด ์‚ฌ์šฉ, ์—†์œผ๋ฉด ํ™˜๊ฒฝ๋ณ€์ˆ˜ ๊ฐ’ ์‚ฌ์šฉ
        return custom_device_url or DEVICE_SERVER_URL
    
    @app.route('/api/device/connect', methods=['POST'])
    @login_required
    def connect_device_server():
        """์‚ฌ์šฉ์ž ์ง€์ • ์žฅ์น˜ ์„œ๋ฒ„ URL ์—ฐ๊ฒฐ API"""
        nonlocal custom_device_url  # ์ƒ์œ„ ์Šค์ฝ”ํ”„์˜ ๋ณ€์ˆ˜ ์ฐธ์กฐ
        
        try:
            # ์š”์ฒญ์—์„œ URL ๊ฐ€์ ธ์˜ค๊ธฐ
            request_data = request.get_json()
            if not request_data or 'url' not in request_data:
                logger.error("URL์ด ์ œ๊ณต๋˜์ง€ ์•Š์•˜์Šต๋‹ˆ๋‹ค.")
                return jsonify({
                    "success": False,
                    "error": "URL์ด ์ œ๊ณต๋˜์ง€ ์•Š์•˜์Šต๋‹ˆ๋‹ค."
                }), 400  # Bad Request
            
            new_url = request_data['url'].strip()
            if not new_url:
                logger.error("URL์ด ๋น„์–ด ์žˆ์Šต๋‹ˆ๋‹ค.")
                return jsonify({
                    "success": False, 
                    "error": "URL์ด ๋น„์–ด ์žˆ์Šต๋‹ˆ๋‹ค."
                }), 400  # Bad Request
            
            # URL ์„ค์ •
            logger.info(f"์‚ฌ์šฉ์ž ์ง€์ • ์žฅ์น˜ ์„œ๋ฒ„ URL ์„ค์ •: {new_url}")
            custom_device_url = new_url
            
            # ์„ค์ •๋œ URL๋กœ ์ƒํƒœ ํ™•์ธ ์‹œ๋„
            try:
                api_path = "/api/status"
                logger.info(f"์žฅ์น˜ ์„œ๋ฒ„ ์ƒํƒœ ํ™•์ธ ์š”์ฒญ: {custom_device_url}{api_path}")
                response = requests.get(f"{custom_device_url}{api_path}", timeout=5)
                
                if response.status_code == 200:
                    try:
                        data = response.json()
                        logger.info(f"์‚ฌ์šฉ์ž ์ง€์ • ์žฅ์น˜ ์„œ๋ฒ„ ์—ฐ๊ฒฐ ์„ฑ๊ณต. ์‘๋‹ต ๋ฐ์ดํ„ฐ: {data}")
                        return jsonify({
                            "success": True,
                            "message": "์žฅ์น˜ ์„œ๋ฒ„ ์—ฐ๊ฒฐ์— ์„ฑ๊ณตํ–ˆ์Šต๋‹ˆ๋‹ค.",
                            "server_status": data.get("status", "์ •์ƒ")
                        })
                    except requests.exceptions.JSONDecodeError:
                        logger.error("์žฅ์น˜ ์„œ๋ฒ„ ์‘๋‹ต JSON ํŒŒ์‹ฑ ์‹คํŒจ")
                        return jsonify({
                            "success": False,
                            "error": "์žฅ์น˜ ์„œ๋ฒ„๋กœ๋ถ€ํ„ฐ ์œ ํšจํ•˜์ง€ ์•Š์€ JSON ์‘๋‹ต์„ ๋ฐ›์•˜์Šต๋‹ˆ๋‹ค."
                        }), 502  # Bad Gateway
                else:
                    error_message = f"์žฅ์น˜ ์„œ๋ฒ„ ์‘๋‹ต ์˜ค๋ฅ˜: {response.status_code}"
                    try:
                        error_detail = response.json().get("error", response.text)
                        error_message += f" - {error_detail}"
                    except Exception:
                        error_message += f" - {response.text}"
                    
                    logger.warning(error_message)
                    custom_device_url = None  # ์—ฐ๊ฒฐ ์‹คํŒจ ์‹œ URL ์ดˆ๊ธฐํ™”
                    return jsonify({
                        "success": False,
                        "error": error_message
                    }), 502  # Bad Gateway
            
            except requests.exceptions.Timeout:
                logger.error(f"์žฅ์น˜ ์„œ๋ฒ„ ์—ฐ๊ฒฐ ํƒ€์ž„์•„์›ƒ ({custom_device_url})")
                custom_device_url = None  # ์—ฐ๊ฒฐ ์‹คํŒจ ์‹œ URL ์ดˆ๊ธฐํ™”
                return jsonify({
                    "success": False,
                    "error": "์žฅ์น˜ ์„œ๋ฒ„ ์—ฐ๊ฒฐ ํƒ€์ž„์•„์›ƒ. ์„œ๋ฒ„ ์‘๋‹ต์ด ๋„ˆ๋ฌด ๋А๋ฆฝ๋‹ˆ๋‹ค."
                }), 504  # Gateway Timeout
            
            except requests.exceptions.ConnectionError:
                logger.error(f"์žฅ์น˜ ๊ด€๋ฆฌ ์„œ๋ฒ„ ์—ฐ๊ฒฐ ์‹คํŒจ ({custom_device_url})")
                custom_device_url = None  # ์—ฐ๊ฒฐ ์‹คํŒจ ์‹œ URL ์ดˆ๊ธฐํ™”
                return jsonify({
                    "success": False,
                    "error": "์žฅ์น˜ ๊ด€๋ฆฌ ์„œ๋ฒ„์— ์—ฐ๊ฒฐํ•  ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค. ์„œ๋ฒ„๊ฐ€ ์‹คํ–‰ ์ค‘์ธ์ง€, URL์ด ์ •ํ™•ํ•œ์ง€ ํ™•์ธํ•ด์ฃผ์„ธ์š”."
                }), 502  # Bad Gateway
            
            except Exception as e:
                logger.error(f"์žฅ์น˜ ์„œ๋ฒ„ ์—ฐ๊ฒฐ ์ค‘ ์˜ˆ์ƒ์น˜ ๋ชปํ•œ ์˜ค๋ฅ˜ ๋ฐœ์ƒ: {e}", exc_info=True)
                custom_device_url = None  # ์—ฐ๊ฒฐ ์‹คํŒจ ์‹œ URL ์ดˆ๊ธฐํ™”
                return jsonify({
                    "success": False,
                    "error": f"์žฅ์น˜ ์„œ๋ฒ„ ์—ฐ๊ฒฐ ์ค‘ ์˜ค๋ฅ˜ ๋ฐœ์ƒ: {str(e)}"
                }), 500  # Internal Server Error
        
        except Exception as e:
            logger.error(f"/api/device/connect ์ฒ˜๋ฆฌ ์ค‘ ๋‚ด๋ถ€ ์„œ๋ฒ„ ์˜ค๋ฅ˜: {e}", exc_info=True)
            return jsonify({
                "success": False,
                "error": f"๋‚ด๋ถ€ ์„œ๋ฒ„ ์˜ค๋ฅ˜ ๋ฐœ์ƒ: {str(e)}"
            }), 500  # Internal Server Error

    @app.route('/api/device/status', methods=['GET'])
    @login_required
    def device_status():
        """์žฅ์น˜ ๊ด€๋ฆฌ ์„œ๋ฒ„์˜ ์ƒํƒœ๋ฅผ ํ™•์ธํ•˜๋Š” API ์—”๋“œํฌ์ธํŠธ"""
        try:
            # requests ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ๋Š” ํ•จ์ˆ˜ ๋‚ด์—์„œ ์ž„ํฌํŠธํ•  ํ•„์š” ์—†์Œ (์ƒ๋‹จ ์ž„ํฌํŠธ ์‚ฌ์šฉ)
            # json, jsonify๋„ Flask์—์„œ ์ด๋ฏธ ์ž„ํฌํŠธ๋จ (์ƒ๋‹จ ์ž„ํฌํŠธ ์‚ฌ์šฉ)

            # ์—ฐ๊ฒฐ ํƒ€์ž„์•„์›ƒ ์„ค์ •
            timeout = 5  # 5์ดˆ๋กœ ํƒ€์ž„์•„์›ƒ ์„ค์ •

            try:
                # ์žฅ์น˜ ์„œ๋ฒ„ ์ƒํƒœ ํ™•์ธ - ๊ฒฝ๋กœ: /api/status
                current_device_url = get_device_url()
                api_path = "/api/status"
                logger.info(f"์žฅ์น˜ ์„œ๋ฒ„ ์ƒํƒœ ํ™•์ธ ์š”์ฒญ: {current_device_url}{api_path}")
                response = requests.get(f"{current_device_url}{api_path}", timeout=timeout)

                # ์‘๋‹ต ์ƒํƒœ ์ฝ”๋“œ ๋ฐ ๋‚ด์šฉ ๋กœ๊น… (๋””๋ฒ„๊น… ๊ฐ•ํ™”)
                logger.debug(f"์žฅ์น˜ ์„œ๋ฒ„ ์‘๋‹ต ์ƒํƒœ ์ฝ”๋“œ: {response.status_code}")
                try:
                    logger.debug(f"์žฅ์น˜ ์„œ๋ฒ„ ์‘๋‹ต ๋‚ด์šฉ: {response.text[:200]}...") # ๋„ˆ๋ฌด ๊ธธ๋ฉด ์ž˜๋ผ์„œ ๋กœ๊น…
                except Exception:
                     logger.debug("์žฅ์น˜ ์„œ๋ฒ„ ์‘๋‹ต ๋‚ด์šฉ ๋กœ๊น… ์‹คํŒจ (ํ…์ŠคํŠธ ํ˜•์‹ ์•„๋‹˜?)")


                if response.status_code == 200:
                    # ์„ฑ๊ณต ์‹œ ์‘๋‹ต ๋ฐ์ดํ„ฐ ๊ตฌ์กฐ ํ™•์ธ ๋ฐ ๋กœ๊น…
                    try:
                        data = response.json()
                        logger.info(f"์žฅ์น˜ ์„œ๋ฒ„ ์ƒํƒœ ํ™•์ธ ์„ฑ๊ณต. ์‘๋‹ต ๋ฐ์ดํ„ฐ: {data}")
                        return jsonify({"success": True, "status": "connected", "data": data})
                    except requests.exceptions.JSONDecodeError:
                        logger.error("์žฅ์น˜ ์„œ๋ฒ„ ์‘๋‹ต JSON ํŒŒ์‹ฑ ์‹คํŒจ")
                        return jsonify({
                            "success": False,
                            "error": "์žฅ์น˜ ์„œ๋ฒ„๋กœ๋ถ€ํ„ฐ ์œ ํšจํ•˜์ง€ ์•Š์€ JSON ์‘๋‹ต์„ ๋ฐ›์•˜์Šต๋‹ˆ๋‹ค."
                        }), 502 # Bad Gateway (์—…์ŠคํŠธ๋ฆผ ์„œ๋ฒ„ ์˜ค๋ฅ˜)
                else:
                    # ์‹คํŒจ ์‹œ ์˜ค๋ฅ˜ ๋ฉ”์‹œ์ง€ ํฌํ•จ ๋กœ๊น…
                    error_message = f"์žฅ์น˜ ์„œ๋ฒ„ ์‘๋‹ต ์˜ค๋ฅ˜: {response.status_code}"
                    try:
                         # ์„œ๋ฒ„์—์„œ ์˜ค๋ฅ˜ ๋ฉ”์‹œ์ง€๋ฅผ json์œผ๋กœ ๋ณด๋‚ด๋Š” ๊ฒฝ์šฐ ํฌํ•จ
                         error_detail = response.json().get("error", response.text)
                         error_message += f" - {error_detail}"
                    except Exception:
                         error_message += f" - {response.text}" # JSON ํŒŒ์‹ฑ ์‹คํŒจ ์‹œ ์›๋ณธ ํ…์ŠคํŠธ

                    logger.warning(error_message) # ๊ฒฝ๊ณ  ๋ ˆ๋ฒจ๋กœ ๋กœ๊น…
                    return jsonify({
                        "success": False,
                        "error": error_message
                    }), 502  # Bad Gateway

            except requests.exceptions.Timeout:
                logger.error(f"์žฅ์น˜ ์„œ๋ฒ„ ์—ฐ๊ฒฐ ํƒ€์ž„์•„์›ƒ ({DEVICE_SERVER_URL})")
                return jsonify({
                    "success": False,
                    "error": "์žฅ์น˜ ์„œ๋ฒ„ ์—ฐ๊ฒฐ ํƒ€์ž„์•„์›ƒ. ์„œ๋ฒ„ ์‘๋‹ต์ด ๋„ˆ๋ฌด ๋А๋ฆฝ๋‹ˆ๋‹ค."
                }), 504  # Gateway Timeout

            except requests.exceptions.ConnectionError:
                current_device_url = get_device_url()
                logger.error(f"์žฅ์น˜ ๊ด€๋ฆฌ ์„œ๋ฒ„ ์—ฐ๊ฒฐ ์‹คํŒจ ({current_device_url})")
                return jsonify({
                    "success": False,
                    "error": "์žฅ์น˜ ๊ด€๋ฆฌ ์„œ๋ฒ„์— ์—ฐ๊ฒฐํ•  ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค. ์„œ๋ฒ„๊ฐ€ ์‹คํ–‰ ์ค‘์ธ์ง€, URL์ด ์ •ํ™•ํ•œ์ง€ ํ™•์ธํ•ด์ฃผ์„ธ์š”."
                }), 502  # Bad Gateway (์—ฐ๊ฒฐ ์‹คํŒจ๋„ ์—…์ŠคํŠธ๋ฆผ ๋ฌธ์ œ๋กœ ๊ฐ„์ฃผ)

            except Exception as e:
                logger.error(f"์žฅ์น˜ ์„œ๋ฒ„ ์—ฐ๊ฒฐ ์ค‘ ์˜ˆ์ƒ์น˜ ๋ชปํ•œ ์˜ค๋ฅ˜ ๋ฐœ์ƒ: {e}", exc_info=True) # ์ƒ์„ธ ์Šคํƒ ํŠธ๋ ˆ์ด์Šค ๋กœ๊น…
                return jsonify({
                    "success": False,
                    "error": f"์žฅ์น˜ ์„œ๋ฒ„ ์—ฐ๊ฒฐ ์ค‘ ์˜ค๋ฅ˜ ๋ฐœ์ƒ: {str(e)}"
                }), 500  # Internal Server Error (Flask ์•ฑ ๋‚ด๋ถ€ ๋˜๋Š” requests ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ ๋ฌธ์ œ ๊ฐ€๋Šฅ์„ฑ)

        except Exception as e:
            # ์ด try-except ๋ธ”๋ก์€ /api/device/status ๋ผ์šฐํŠธ ์ž์ฒด์˜ ๋‚ด๋ถ€ ์˜ค๋ฅ˜ ์ฒ˜๋ฆฌ
            logger.error(f"/api/device/status ์ฒ˜๋ฆฌ ์ค‘ ๋‚ด๋ถ€ ์„œ๋ฒ„ ์˜ค๋ฅ˜: {e}", exc_info=True)
            return jsonify({
                "success": False,
                "error": f"๋‚ด๋ถ€ ์„œ๋ฒ„ ์˜ค๋ฅ˜ ๋ฐœ์ƒ: {str(e)}"
            }), 500  # Internal Server Error

    @app.route('/api/device/list', methods=['GET'])
    @login_required
    def device_list():
        """์žฅ์น˜ ๋ชฉ๋ก ์กฐํšŒ API"""
        logger.info("์žฅ์น˜ ๋ชฉ๋ก ์กฐํšŒ ์š”์ฒญ")

        try:
            current_device_url = get_device_url()
            api_path = "/api/devices"
            logger.info(f"์žฅ์น˜ ๋ชฉ๋ก ์กฐํšŒ ์š”์ฒญ: {current_device_url}{api_path}")
            response = requests.get(f"{current_device_url}{api_path}", timeout=5)
            logger.debug(f"์žฅ์น˜ ๋ชฉ๋ก ์‘๋‹ต ์ƒํƒœ ์ฝ”๋“œ: {response.status_code}")

            if response.status_code == 200:
                try:
                    data = response.json()
                    devices = data.get("devices", [])
                    logger.info(f"์žฅ์น˜ ๋ชฉ๋ก ์กฐํšŒ ์„ฑ๊ณต: {len(devices)}๊ฐœ ์žฅ์น˜")
                    return jsonify({
                        "success": True,
                        "devices": devices
                    })
                except requests.exceptions.JSONDecodeError:
                     logger.error("์žฅ์น˜ ๋ชฉ๋ก ์‘๋‹ต JSON ํŒŒ์‹ฑ ์‹คํŒจ")
                     return jsonify({"success": False, "error": "์žฅ์น˜ ์„œ๋ฒ„๋กœ๋ถ€ํ„ฐ ์œ ํšจํ•˜์ง€ ์•Š์€ JSON ์‘๋‹ต"}), 502
            else:
                error_message = f"์žฅ์น˜ ๋ชฉ๋ก ์กฐํšŒ ์‹คํŒจ: {response.status_code}"
                try: error_message += f" - {response.json().get('error', response.text)}"
                except Exception: error_message += f" - {response.text}"
                logger.warning(error_message)
                return jsonify({
                    "success": False,
                    "error": error_message
                }), 502

        except requests.exceptions.Timeout:
            logger.error("์žฅ์น˜ ๋ชฉ๋ก ์กฐํšŒ ์‹œ๊ฐ„ ์ดˆ๊ณผ")
            return jsonify({
                "success": False,
                "error": "์žฅ์น˜ ๋ชฉ๋ก ์กฐํšŒ ์‹œ๊ฐ„์ด ์ดˆ๊ณผ๋˜์—ˆ์Šต๋‹ˆ๋‹ค."
            }), 504

        except requests.exceptions.ConnectionError:
            logger.error("์žฅ์น˜ ๊ด€๋ฆฌ ์„œ๋ฒ„ ์—ฐ๊ฒฐ ์‹คํŒจ")
            return jsonify({
                "success": False,
                "error": "์žฅ์น˜ ๊ด€๋ฆฌ ์„œ๋ฒ„์— ์—ฐ๊ฒฐํ•  ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค. ์„œ๋ฒ„๊ฐ€ ์‹คํ–‰ ์ค‘์ธ์ง€ ํ™•์ธํ•ด์ฃผ์„ธ์š”."
            }), 503 # Service Unavailable

        except Exception as e:
            logger.error(f"์žฅ์น˜ ๋ชฉ๋ก ์กฐํšŒ ์ค‘ ์˜ค๋ฅ˜ ๋ฐœ์ƒ: {e}", exc_info=True)
            return jsonify({
                "success": False,
                "error": f"์žฅ์น˜ ๋ชฉ๋ก ์กฐํšŒ ์ค‘ ์˜ค๋ฅ˜ ๋ฐœ์ƒ: {str(e)}"
            }), 500


    @app.route('/api/device/programs', methods=['GET'])
    @login_required
    def device_programs():
        """์‹คํ–‰ ๊ฐ€๋Šฅํ•œ ํ”„๋กœ๊ทธ๋žจ ๋ชฉ๋ก ์กฐํšŒ API"""
        logger.info("ํ”„๋กœ๊ทธ๋žจ ๋ชฉ๋ก ์กฐํšŒ ์š”์ฒญ")

        try:
            current_device_url = get_device_url()
            api_path = "/api/programs"
            logger.info(f"ํ”„๋กœ๊ทธ๋žจ ๋ชฉ๋ก ์กฐํšŒ ์š”์ฒญ: {current_device_url}{api_path}")
            response = requests.get(f"{current_device_url}{api_path}", timeout=5)
            logger.debug(f"ํ”„๋กœ๊ทธ๋žจ ๋ชฉ๋ก ์‘๋‹ต ์ƒํƒœ ์ฝ”๋“œ: {response.status_code}")


            if response.status_code == 200:
                try:
                    data = response.json()
                    programs = data.get("programs", [])
                    logger.info(f"ํ”„๋กœ๊ทธ๋žจ ๋ชฉ๋ก ์กฐํšŒ ์„ฑ๊ณต: {len(programs)}๊ฐœ ํ”„๋กœ๊ทธ๋žจ")
                    return jsonify({
                        "success": True,
                        "programs": programs
                    })
                except requests.exceptions.JSONDecodeError:
                     logger.error("ํ”„๋กœ๊ทธ๋žจ ๋ชฉ๋ก ์‘๋‹ต JSON ํŒŒ์‹ฑ ์‹คํŒจ")
                     return jsonify({"success": False, "error": "์žฅ์น˜ ์„œ๋ฒ„๋กœ๋ถ€ํ„ฐ ์œ ํšจํ•˜์ง€ ์•Š์€ JSON ์‘๋‹ต"}), 502
            else:
                error_message = f"ํ”„๋กœ๊ทธ๋žจ ๋ชฉ๋ก ์กฐํšŒ ์‹คํŒจ: {response.status_code}"
                try: error_message += f" - {response.json().get('error', response.text)}"
                except Exception: error_message += f" - {response.text}"
                logger.warning(error_message)
                return jsonify({
                    "success": False,
                    "error": error_message
                }), 502

        except requests.exceptions.Timeout:
            logger.error("ํ”„๋กœ๊ทธ๋žจ ๋ชฉ๋ก ์กฐํšŒ ์‹œ๊ฐ„ ์ดˆ๊ณผ")
            return jsonify({
                "success": False,
                "error": "ํ”„๋กœ๊ทธ๋žจ ๋ชฉ๋ก ์กฐํšŒ ์‹œ๊ฐ„์ด ์ดˆ๊ณผ๋˜์—ˆ์Šต๋‹ˆ๋‹ค."
            }), 504

        except requests.exceptions.ConnectionError:
            logger.error("์žฅ์น˜ ๊ด€๋ฆฌ ์„œ๋ฒ„ ์—ฐ๊ฒฐ ์‹คํŒจ")
            return jsonify({
                "success": False,
                "error": "์žฅ์น˜ ๊ด€๋ฆฌ ์„œ๋ฒ„์— ์—ฐ๊ฒฐํ•  ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค. ์„œ๋ฒ„๊ฐ€ ์‹คํ–‰ ์ค‘์ธ์ง€ ํ™•์ธํ•ด์ฃผ์„ธ์š”."
            }), 503

        except Exception as e:
            logger.error(f"ํ”„๋กœ๊ทธ๋žจ ๋ชฉ๋ก ์กฐํšŒ ์ค‘ ์˜ค๋ฅ˜ ๋ฐœ์ƒ: {e}", exc_info=True)
            return jsonify({
                "success": False,
                "error": f"ํ”„๋กœ๊ทธ๋žจ ๋ชฉ๋ก ์กฐํšŒ ์ค‘ ์˜ค๋ฅ˜ ๋ฐœ์ƒ: {str(e)}"
            }), 500


    @app.route('/api/device/programs/<program_id>/execute', methods=['POST'])
    @login_required
    def execute_program(program_id):
        """ํ”„๋กœ๊ทธ๋žจ ์‹คํ–‰ API"""
        logger.info(f"ํ”„๋กœ๊ทธ๋žจ ์‹คํ–‰ ์š”์ฒญ: {program_id}")

        try:
            current_device_url = get_device_url()
            api_path = f"/api/programs/{program_id}/execute"
            logger.info(f"ํ”„๋กœ๊ทธ๋žจ ์‹คํ–‰ ์š”์ฒญ: {current_device_url}{api_path}")
            response = requests.post(
                f"{current_device_url}{api_path}",
                json={}, # ํ•„์š”์‹œ ์—ฌ๊ธฐ์— ํŒŒ๋ผ๋ฏธํ„ฐ ์ถ”๊ฐ€ ๊ฐ€๋Šฅ
                timeout=10  # ํ”„๋กœ๊ทธ๋žจ ์‹คํ–‰์—๋Š” ๋” ๊ธด ์‹œ๊ฐ„ ๋ถ€์—ฌ
            )
            logger.debug(f"ํ”„๋กœ๊ทธ๋žจ ์‹คํ–‰ ์‘๋‹ต ์ƒํƒœ ์ฝ”๋“œ: {response.status_code}")


            if response.status_code == 200:
                try:
                    data = response.json()
                    success = data.get("success", False)
                    message = data.get("message", "")
                    logger.info(f"ํ”„๋กœ๊ทธ๋žจ ์‹คํ–‰ ์‘๋‹ต: {success}, {message}")
                    return jsonify(data) # ์„œ๋ฒ„ ์‘๋‹ต ๊ทธ๋Œ€๋กœ ๋ฐ˜ํ™˜
                except requests.exceptions.JSONDecodeError:
                    logger.error("ํ”„๋กœ๊ทธ๋žจ ์‹คํ–‰ ์‘๋‹ต JSON ํŒŒ์‹ฑ ์‹คํŒจ")
                    # ์„ฑ๊ณต(200)ํ–ˆ์ง€๋งŒ ์‘๋‹ต์ด ๋น„์ •์ƒ์ ์ธ ๊ฒฝ์šฐ
                    return jsonify({
                        "success": False, # ํŒŒ์‹ฑ ์‹คํŒจํ–ˆ์œผ๋ฏ€๋กœ False๋กœ ๊ฐ„์ฃผ
                        "error": "ํ”„๋กœ๊ทธ๋žจ ์‹คํ–‰ ์„œ๋ฒ„๋กœ๋ถ€ํ„ฐ ์œ ํšจํ•˜์ง€ ์•Š์€ JSON ์‘๋‹ต"
                        }), 502
            else:
                error_message = f"ํ”„๋กœ๊ทธ๋žจ ์‹คํ–‰ ์š”์ฒญ ์‹คํŒจ: {response.status_code}"
                try: error_message += f" - {response.json().get('error', response.text)}"
                except Exception: error_message += f" - {response.text}"
                logger.warning(error_message)
                return jsonify({
                    "success": False,
                    "error": error_message
                }), 502 # ๋˜๋Š” response.status_code ๋ฅผ ๊ทธ๋Œ€๋กœ ๋ฐ˜ํ™˜ํ•˜๋Š” ๊ฒƒ๋„ ๊ณ ๋ ค

        except requests.exceptions.Timeout:
            logger.error("ํ”„๋กœ๊ทธ๋žจ ์‹คํ–‰ ์š”์ฒญ ์‹œ๊ฐ„ ์ดˆ๊ณผ")
            return jsonify({
                "success": False,
                "error": "ํ”„๋กœ๊ทธ๋žจ ์‹คํ–‰ ์š”์ฒญ ์‹œ๊ฐ„์ด ์ดˆ๊ณผ๋˜์—ˆ์Šต๋‹ˆ๋‹ค."
            }), 504

        except requests.exceptions.ConnectionError:
            logger.error("์žฅ์น˜ ๊ด€๋ฆฌ ์„œ๋ฒ„ ์—ฐ๊ฒฐ ์‹คํŒจ")
            return jsonify({
                "success": False,
                "error": "์žฅ์น˜ ๊ด€๋ฆฌ ์„œ๋ฒ„์— ์—ฐ๊ฒฐํ•  ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค. ์„œ๋ฒ„๊ฐ€ ์‹คํ–‰ ์ค‘์ธ์ง€ ํ™•์ธํ•ด์ฃผ์„ธ์š”."
            }), 503

        except Exception as e:
            logger.error(f"ํ”„๋กœ๊ทธ๋žจ ์‹คํ–‰ ์ค‘ ์˜ค๋ฅ˜ ๋ฐœ์ƒ: {e}", exc_info=True)
            return jsonify({
                "success": False,
                "error": f"ํ”„๋กœ๊ทธ๋žจ ์‹คํ–‰ ์ค‘ ์˜ค๋ฅ˜ ๋ฐœ์ƒ: {str(e)}"
            }), 500