-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.py
More file actions
613 lines (558 loc) · 25.6 KB
/
Copy pathapi.py
File metadata and controls
613 lines (558 loc) · 25.6 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
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
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
import io
import json
import os
import socket
import uvicorn
from datetime import datetime
from fastapi import FastAPI, File, Form, HTTPException, UploadFile
from fastapi.responses import FileResponse, HTMLResponse, JSONResponse
from pathlib import Path
from ..analyzer import analyze_csv
# FastAPI のアプリ本体を作る。
# ここで作った app に対して「/analyze へPOSTされたらこの関数を呼ぶ」のような設定を追加していく。
app = FastAPI(title="モーター調整補助APIサーバー")
# このファイルは src/server/api.py にあるため、parents[2] でプロジェクトの一番上のフォルダを指す。
# 例: C:\Users\...\pid_adjust
BASE_DIR = Path(__file__).resolve().parents[2]
# 解析結果と、アップロードされたCSVを保存するディレクトリ。
# exist_ok=True にしておくと、すでにフォルダがあってもエラーにならない。
RESULTS_DIR = BASE_DIR / "analysis_results"
os.makedirs(RESULTS_DIR, exist_ok=True)
def get_local_ip():
"""同じLAN内の別PCからアクセスするときに使う、このPCのIPアドレスを取得する。"""
try:
# UDPソケットで外部アドレスへ「接続したことにする」と、
# 実際にデータを送らずに、このPCが使うローカルIPを調べられる。
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
s.connect(("8.8.8.8", 80))
return s.getsockname()[0]
except OSError:
try:
# 上の方法が使えない環境向けの予備手段。
# PC名からIPアドレスを引くが、環境によっては 127.0.0.1 になることもある。
return socket.gethostbyname(socket.gethostname())
except OSError:
# どちらの方法でも取れなかった場合は None を返し、呼び出し元で案内文を出す。
return None
def print_server_urls(port):
"""サーバー起動時に、ブラウザや別PCからアクセスするURLを表示する。"""
local_ip = get_local_ip()
print("")
print("APIサーバーを起動します")
# localhost は「このPC自身」を表す特別な名前。
# サーバーを起動しているPC上のブラウザやStreamlitから使う。
print(f" このPCから: http://localhost:{port}")
print(f" ダッシュボード: http://localhost:{port}/dashboard")
if local_ip and not local_ip.startswith("127."):
# 127.x.x.x は自分自身専用のアドレスなので、別PCからは使えない。
# それ以外のIPなら、同じLAN内の端末からアクセスできる可能性が高い。
print(f" 同じLAN内から: http://{local_ip}:{port}")
print(f" LAN内ダッシュボード: http://{local_ip}:{port}/dashboard")
else:
print(" LAN内IPアドレスを自動取得できませんでした。ipconfig の IPv4 アドレスを確認してください。")
print("")
def save_result(result, timestamp_key):
"""解析結果をJSONファイルに保存"""
# timestamp_key をファイル名に含めることで、複数回解析しても上書きされにくくする。
filename = f"{RESULTS_DIR}/result_{timestamp_key}.json"
# ensure_ascii=False にすると、日本語を \uXXXX のような形にせず、そのまま保存できる。
# indent=2 は、人が読んだときに見やすいように2スペースで整形する設定。
with open(filename, "w", encoding="utf-8") as f:
json.dump(result, f, ensure_ascii=False, indent=2)
# 保存したファイル名を呼び出し元に返す。今は主に確認用。
return filename
def generate_dashboard_html(results_list=None):
"""ダッシュボードHTMLを生成"""
# 引数なしで呼ばれたときは、保存済みJSONからダッシュボードを作る。
# Pythonではデフォルト引数に [] を直接書くと意図しない共有が起きるため、None にしてから作る。
if results_list is None:
results_list = []
# 結果ファイルを読み込む。
# results_list が空のときだけ、analysis_results フォルダから読み込む。
if not results_list:
try:
# result_*.json の一覧を新しい順に並べる。
result_files = sorted(
[f for f in os.listdir(RESULTS_DIR) if f.endswith(".json")],
reverse=True,
)
for filename in result_files[-10:]: # 最新10件
try:
# JSONファイルをPythonの辞書(dict)として読み込む。
with open(
os.path.join(RESULTS_DIR, filename), "r", encoding="utf-8"
) as f:
results_list.append(json.load(f))
except:
# 壊れたJSONなどが1件あっても、ダッシュボード全体は止めない。
pass
except:
# フォルダが読めない場合なども、空のダッシュボードを表示する。
pass
# スコア推移グラフ用に、左右のスコアと時刻だけをリストに取り出す。
left_scores = [r["left_motor"]["score"] for r in results_list]
right_scores = [r["right_motor"]["score"] for r in results_list]
timestamps = [r["timestamp"][-8:-3] for r in results_list] # HH:MM形式
# ここから下は、ブラウザに返すHTML文字列を組み立てている。
# f""" ... """ の中では {変数名} と書くとPythonの値を埋め込める。
html = f"""
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>モーター調整補助ダッシュボード</title>
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
<style>
* {{
margin: 0;
padding: 0;
box-sizing: border-box;
}}
body {{
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
min-height: 100vh;
padding: 20px;
}}
.container {{
max-width: 1400px;
margin: 0 auto;
}}
.header {{
background: white;
padding: 30px;
border-radius: 10px;
margin-bottom: 20px;
box-shadow: 0 4px 6px rgba(0,0,0,0.1);
}}
.header h1 {{
color: #333;
margin-bottom: 10px;
font-size: 2em;
}}
.header p {{
color: #666;
font-size: 1em;
}}
.latest-result {{
display: grid;
grid-template-columns: 1fr 1fr;
gap: 20px;
margin-bottom: 20px;
}}
.metric-card {{
background: white;
padding: 20px;
border-radius: 10px;
box-shadow: 0 4px 6px rgba(0,0,0,0.1);
}}
.metric-card h2 {{
color: #333;
font-size: 1.3em;
margin-bottom: 15px;
border-bottom: 2px solid #667eea;
padding-bottom: 10px;
}}
.metric {{
display: flex;
justify-content: space-between;
margin: 10px 0;
padding: 8px 0;
border-bottom: 1px solid #eee;
}}
.metric-label {{
color: #666;
font-weight: 500;
}}
.metric-value {{
color: #333;
font-weight: bold;
font-size: 1.1em;
}}
.score {{
font-size: 2em;
color: #667eea;
text-align: center;
margin: 20px 0;
}}
.advice {{
background: #f0f4ff;
padding: 15px;
border-left: 4px solid #667eea;
margin-top: 15px;
border-radius: 5px;
color: #333;
line-height: 1.6;
font-size: 0.95em;
}}
.chart-container {{
background: white;
padding: 20px;
border-radius: 10px;
box-shadow: 0 4px 6px rgba(0,0,0,0.1);
margin-bottom: 20px;
}}
.chart-container h2 {{
color: #333;
margin-bottom: 20px;
font-size: 1.3em;
}}
.grid-2 {{
display: grid;
grid-template-columns: 1fr 1fr;
gap: 20px;
}}
.footer {{
text-align: center;
color: white;
padding: 20px;
font-size: 0.9em;
}}
.status-good {{
color: #10b981;
font-weight: bold;
}}
.status-warning {{
color: #f59e0b;
font-weight: bold;
}}
.status-bad {{
color: #ef4444;
font-weight: bold;
}}
@media (max-width: 768px) {{
.latest-result {{
grid-template-columns: 1fr;
}}
.grid-2 {{
grid-template-columns: 1fr;
}}
}}
</style>
</head>
<body>
<div class="container">
<div class="header">
<h1>🚀 モーター調整補助ダッシュボード</h1>
<p>FastAPI サーバーで送信されたデータをリアルタイム表示</p>
</div>
"""
if results_list:
# 最新の解析結果をカード表示するため、先頭の1件を取り出す。
latest = results_list[0]
left_motor = latest["left_motor"]
right_motor = latest["right_motor"]
balance = latest["balance"]
html += f"""
<div class="latest-result">
<div class="metric-card">
<h2>⬅️ 左モーター</h2>
<div class="score">{left_motor["score"]:.1f}</div>
<div class="metric">
<span class="metric-label">最大速度</span>
<span class="metric-value">{left_motor["max_speed"]:.2f}</span>
</div>
<div class="metric">
<span class="metric-label">オーバーシュート</span>
<span class="metric-value">{left_motor["overshoot"]:.2f}%</span>
</div>
<div class="metric">
<span class="metric-label">定常偏差</span>
<span class="metric-value">{left_motor["steady_error"]:.2f}</span>
</div>
<div class="metric">
<span class="metric-label">ハンチング周期</span>
<span class="metric-value">{left_motor["hunting_cycles"]}</span>
</div>
<div class="metric">
<span class="metric-label">推奨 Kp</span>
<span class="metric-value">{left_motor["suggested_kp"]:.5f}</span>
</div>
<div class="metric">
<span class="metric-label">推奨 Ki</span>
<span class="metric-value">{left_motor["suggested_ki"]:.5f}</span>
</div>
<div class="metric">
<span class="metric-label">推奨 Kd</span>
<span class="metric-value">{left_motor["suggested_kd"]:.5f}</span>
</div>
<div class="advice">
<strong>アドバイス:</strong><br>
{"<br>".join(left_motor["advice"])}
</div>
</div>
<div class="metric-card">
<h2>➡️ 右モーター</h2>
<div class="score">{right_motor["score"]:.1f}</div>
<div class="metric">
<span class="metric-label">最大速度</span>
<span class="metric-value">{right_motor["max_speed"]:.2f}</span>
</div>
<div class="metric">
<span class="metric-label">オーバーシュート</span>
<span class="metric-value">{right_motor["overshoot"]:.2f}%</span>
</div>
<div class="metric">
<span class="metric-label">定常偏差</span>
<span class="metric-value">{right_motor["steady_error"]:.2f}</span>
</div>
<div class="metric">
<span class="metric-label">ハンチング周期</span>
<span class="metric-value">{right_motor["hunting_cycles"]}</span>
</div>
<div class="metric">
<span class="metric-label">推奨 Kp</span>
<span class="metric-value">{right_motor["suggested_kp"]:.5f}</span>
</div>
<div class="metric">
<span class="metric-label">推奨 Ki</span>
<span class="metric-value">{right_motor["suggested_ki"]:.5f}</span>
</div>
<div class="metric">
<span class="metric-label">推奨 Kd</span>
<span class="metric-value">{right_motor["suggested_kd"]:.5f}</span>
</div>
<div class="advice">
<strong>アドバイス:</strong><br>
{"<br>".join(right_motor["advice"])}
</div>
</div>
</div>
<div class="metric-card">
<h2>⚖️ 左右バランス分析</h2>
<div class="metric">
<span class="metric-label">左平均速度</span>
<span class="metric-value">{balance["left_avg_speed"]:.2f}</span>
</div>
<div class="metric">
<span class="metric-label">右平均速度</span>
<span class="metric-value">{balance["right_avg_speed"]:.2f}</span>
</div>
<div class="metric">
<span class="metric-label">差異率</span>
<span class="metric-value {("status-good" if balance["diff_ratio"] < 5 else "status-warning" if balance["diff_ratio"] < 10 else "status-bad")}">{balance["diff_ratio"]:.2f}%</span>
</div>
<div class="metric">
<span class="metric-label">回帰係数</span>
<span class="metric-value">{balance["regression_a"]:.6f}</span>
</div>
</div>
"""
if len(left_scores) > 1:
# 2件以上の履歴があるときだけ、Plotlyでスコア推移グラフを表示する。
html += (
"""
<div class="chart-container">
<h2>📊 スコア推移</h2>
<div id="scoreChart" style="height: 400px;"></div>
<script>
var data = [
{{
x: """
+ json.dumps(timestamps)
+ """,
y: """
+ json.dumps(left_scores)
+ """,
name: '左モーター',
mode: 'lines+markers',
line: {{color: '#667eea'}}
}},
{{
x: """
+ json.dumps(timestamps)
+ """,
y: """
+ json.dumps(right_scores)
+ """,
name: '右モーター',
mode: 'lines+markers',
line: {{color: '#764ba2'}}
}}
];
var layout = {{
title: 'スコア推移(最新10件)',
xaxis: {{title: '時刻'}},
yaxis: {{title: 'スコア', range: [0, 100]}},
hovermode: 'x unified'
}};
Plotly.newPlot('scoreChart', data, layout);
</script>
</div>
"""
)
else:
html += """
<div class="metric-card">
<h2>📭 データなし</h2>
<p>まだ解析データがありません。PowerShellスクリプトまたはAPIで解析を実行してください。</p>
</div>
"""
# HTMLの最後の閉じタグを追加する。
html += """
<div class="footer">
<p>このダッシュボードは FastAPI サーバーから自動生成されています</p>
<p><code>http://localhost:8000/dashboard</code> でアクセス</p>
</div>
</div>
</body>
</html>
"""
return html
# @app.post は「このURLにPOSTリクエストが来たら、下の関数を実行する」という意味。
# POSTは、CSVファイルのようにデータをサーバーへ送るときによく使う。
@app.post("/analyze")
async def analyze_data(
# File(...) は「必須のファイル入力」を表す。
file: UploadFile = File(...),
# Form(...) は、HTMLフォームやcurlの -F で送られてくる値を受け取る。
# 値が送られてこなかった場合は、カッコ内のデフォルト値を使う。
speed_target: float = Form(500.0),
position_target: float = Form(0.0),
kp_l: float = Form(1.00),
ki_l: float = Form(0.00),
kd_l: float = Form(0.00),
kp_r: float = Form(1.00),
ki_r: float = Form(0.00),
kd_r: float = Form(0.00),
):
"""
CSVファイルをアップロードして解析します。
"""
try:
# FastAPIの UploadFile から、CSVファイルの中身を bytes として読み出す。
contents = await file.read()
# analyzer.py 側はファイルのようなオブジェクトを読むため、
# bytes を io.BytesIO で包んで「メモリ上のファイル」の形にする。
csv_data = io.BytesIO(contents)
result = analyze_csv(csv_data, speed_target, position_target, kp_l, ki_l, kd_l, kp_r, ki_r, kd_r)
# タイムスタンプキーを生成(マイクロ秒を含めて衝突防止)
timestamp_key = datetime.now().strftime("%Y%m%d_%H%M%S_%f")
# あとから同じデータを再表示できるように、アップロードされたCSVも保存しておく。
csv_filename = f"{RESULTS_DIR}/data_{timestamp_key}.csv"
with open(csv_filename, "wb") as f:
f.write(contents)
# 解析結果はJSONとして保存する。
# Streamlit側の「サーバーと同期」は、このJSON一覧を読んでいる。
save_result(result, timestamp_key)
# APIを呼んだ側に、解析結果をJSONとして返す。
return JSONResponse(content=result)
except ValueError as e:
# CSVの列不足など、入力データ側の問題は 400 Bad Request として返す。
raise HTTPException(status_code=400, detail=str(e))
except Exception as e:
# 予想外のエラーは 500 Internal Server Error として返す。
raise HTTPException(status_code=500, detail=f"解析エラー: {str(e)}")
# ブラウザで /dashboard を開いたとき、HTMLのダッシュボードを返す。
@app.get("/dashboard", response_class=HTMLResponse)
async def dashboard():
"""ダッシュボード表示"""
return generate_dashboard_html()
# サーバーが生きているか確認するための軽いAPI。
# 監視や接続確認では、まずこのURLを見ると原因を切り分けやすい。
@app.get("/health")
async def health_check():
"""ヘルスチェック"""
return {"status": "ok"}
# 保存済みの解析結果一覧を返すAPI。
# Streamlit側はこの一覧を使って、選択ボックスに過去データを表示している。
@app.get("/results")
async def get_results():
"""保存された解析結果のリストを取得"""
results_list = []
try:
# 保存フォルダがまだなければ、履歴は空として返す。
if not os.path.exists(RESULTS_DIR):
return []
# result_*.json だけを対象にする。
# data_*.csv はCSV本体なので、この一覧には入れない。
result_files = sorted(
[
f
for f in os.listdir(RESULTS_DIR)
if f.startswith("result_") and f.endswith(".json")
],
reverse=True,
)
for filename in result_files:
try:
timestamp_key = filename[7:-5] # result_ と .json を除く
# 1件ずつJSONを読み込む。
with open(
os.path.join(RESULTS_DIR, filename), "r", encoding="utf-8"
) as f:
data = json.load(f)
# Streamlit側で一覧表示やパラメータ復元に必要な項目だけ抜き出す。
# get(..., デフォルト値) にしておくと、古いJSONに項目がなくても落ちにくい。
results_list.append(
{
"timestamp_key": timestamp_key,
"timestamp": data.get("timestamp", ""),
"speed_target": data.get("speed_target", 500.0),
"position_target": data.get("position_target", 0.0),
"left_score": data.get("left_motor", {}).get("score", 0.0),
"right_score": data.get("right_motor", {}).get(
"score", 0.0
),
"kp_l": data.get("kp_l", 1.0),
"ki_l": data.get("ki_l", 0.0),
"kd_l": data.get("kd_l", 0.0),
"kp_r": data.get("kp_r", 1.0),
"ki_r": data.get("ki_r", 0.0),
"kd_r": data.get("kd_r", 0.0),
}
)
except Exception:
# 1件読み込みに失敗しても、他の履歴は返したいのでスキップする。
pass
except Exception as e:
raise HTTPException(status_code=500, detail=f"履歴読み込みエラー: {str(e)}")
return results_list
# 保存済みCSVをダウンロードするAPI。
# timestamp_key は、result_20260613_120000_123456.json の数字部分に相当する。
@app.get("/results/{timestamp_key}/csv")
async def get_result_csv(timestamp_key: str):
"""指定されたタイムスタンプのCSVファイルを取得"""
csv_path = os.path.join(RESULTS_DIR, f"data_{timestamp_key}.csv")
if not os.path.exists(csv_path):
raise HTTPException(status_code=404, detail="CSVファイルが見つかりません。")
return FileResponse(
csv_path, media_type="text/csv", filename=f"data_{timestamp_key}.csv"
)
# 保存済みJSONをそのまま取得するAPI。
# デバッグや外部ツール連携で、解析結果の詳細を見たいときに使える。
@app.get("/results/{timestamp_key}/json")
async def get_result_json(timestamp_key: str):
"""指定されたタイムスタンプの解析結果JSONを取得"""
json_path = os.path.join(RESULTS_DIR, f"result_{timestamp_key}.json")
if not os.path.exists(json_path):
raise HTTPException(status_code=404, detail="JSONファイルが見つかりません。")
try:
with open(json_path, "r", encoding="utf-8") as f:
data = json.load(f)
return data
except Exception as e:
raise HTTPException(
status_code=500, detail=f"JSONファイル読み込みエラー: {str(e)}"
)
# このファイルを直接実行したときだけ、ここから下が動く。
# 例: python -m src.server.api
# import された場合は、サーバーを勝手に起動しない。
if __name__ == "__main__":
import argparse
# コマンドライン引数を読むための準備。
# --port 8001 のように指定すると、待ち受けポートを変えられる。
parser = argparse.ArgumentParser(description="モーター調整補助APIサーバー")
parser.add_argument(
"--port",
type=int,
default=int(os.environ.get("PORT", 8000)),
help="サーバーが待機するポート番号(デフォルト: 8000)"
)
args = parser.parse_args()
# 実際に待ち受けを開始する前に、アクセス用URLをターミナルへ表示する。
print_server_urls(args.port)
# host="0.0.0.0" は、このPC以外からの接続も受け付ける設定。
# localhost だけにしたい場合は host="127.0.0.1" にする。
uvicorn.run(app, host="0.0.0.0", port=args.port)