-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpc_data_recorder_with_trigger.py
More file actions
178 lines (140 loc) · 5.98 KB
/
Copy pathpc_data_recorder_with_trigger.py
File metadata and controls
178 lines (140 loc) · 5.98 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
"""
IMS-SD PCデータ記録モジュール
外部トリガありでPCにデータを保存するサンプルコード
"""
import datetime
import sys
import io
import os
import time
from typing import Optional, List
from ims_device import ImsDevice # type: ignore
from packet_parser import PacketParser, EngineeringData # type: ignore
from data_collector import collect_data, save_to_csv, setup_measurement_conditions # type: ignore
class PcDataRecorderWithTrigger:
"""PCデータ記録クラス(外部トリガ対応)"""
def __init__(self, device: ImsDevice):
self.device = device
self.data_buffer: List[EngineeringData] = []
self.packet_parser = PacketParser(device, ch_count=9, matome_pc=10)
def record_data(self, duration: float = 10.0, filename: Optional[str] = None, trigger_timeout: float = 10.0) -> bool:
"""
データ記録実行(外部トリガ待機→測定→CSV保存)
Args:
duration: 記録時間(秒)
filename: 出力ファイル名
trigger_timeout: 外部トリガ待機時間(秒)
Returns:
bool: 記録成功時True
"""
# ファイル名生成
if filename is None:
timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
filename = f"ims_sd_data_trig_{timestamp}.csv"
# Pythonファイルと同じフォルダに保存
script_dir = os.path.dirname(os.path.abspath(__file__))
full_path = os.path.join(script_dir, filename)
print(f"出力ファイル: {full_path}")
# 測定実行
if not self.device.is_connected:
print("デバイスが接続されていません")
return False
# データバッファクリア
self.data_buffer.clear()
# EXTコマンドで外部トリガ待ち受けモードに移行
if not self.device.set_ext_mode():
print("外部トリガモード移行失敗")
return False
print(f"外部トリガ待機中... (最大{trigger_timeout}秒)")
# 外部トリガ待機
start_time = time.time()
triggered = False
while time.time() - start_time < trigger_timeout:
# バッファにデータが来たかチェック(トリガが入ると測定開始してデータが来る)
bytes_in_buffer = self.device.serial.get_bytes_in_buffer()
if bytes_in_buffer > 0:
print("外部トリガ検出!測定開始")
triggered = True
break
time.sleep(0.1) # 100ms間隔でチェック
if not triggered:
print("外部トリガタイムアウト - 測定をキャンセルします")
# STOPコマンドでIDLEモードに戻す
if self.device.stop_measurement():
print("IDLEモードに戻りました")
return False
# データ収集
collected_data = collect_data(self.device, self.packet_parser, frequency=100, matome_pc=10, duration=duration)
if not collected_data:
return False
# データバッファに追加
self.data_buffer.extend(collected_data)
# STOPコマンド送信
if self.device.stop_measurement():
print("測定停止")
else:
print("測定停止失敗")
return False
# データをCSVファイルに保存
if self.data_buffer:
success = save_to_csv(self.data_buffer, full_path)
return success
else:
print("データが記録されませんでした")
return False
def main():
"""メイン処理"""
# Windows環境でのエンコーディング設定とバッファリング無効化
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8', line_buffering=True)
print("=" * 50)
print("IMS-SD PCデータ記録プログラム(外部トリガ対応)")
print("=" * 50)
# IMS-SDデバイス初期化
device = ImsDevice()
try:
# 1. ポート一覧表示
print("\n1. 利用可能なCOMポート:")
ports = device.serial.list_available_ports()
for i, port in enumerate(ports, 1):
print(f" {i}. {port['device']}: {port['description']}")
if not ports:
print("利用可能なポートがありません")
return
# 2. COM3に接続
print("\n2. デバイス接続中...")
if not device.connect("COM3"):
print("デバイス接続失敗")
return
print("✓ デバイス接続成功")
print(f" シリアル番号: {device.serial_number}")
print(f" モデル: {device.model}")
print(f" バージョン: {device.version}")
# 3. 測定条件設定(100Hz, まとめ数10, PC保存, 30G)
if not setup_measurement_conditions(device, frequency=100, matome_pc=10, save_to_flash=False, acc_range=30):
print("測定条件設定失敗")
return
# 4. PCデータ記録実行(外部トリガ待機)
print("\n=== データ記録実行(外部トリガ待機) ===")
recorder = PcDataRecorderWithTrigger(device)
duration = 10.0
trigger_timeout = 10.0
# データ記録実行
if recorder.record_data(duration=duration, trigger_timeout=trigger_timeout):
print("✓ データ記録完了")
else:
print("✗ データ記録失敗またはタイムアウト")
except KeyboardInterrupt:
print("\n中断されました")
except Exception as e:
print(f"\nエラー: {e}")
finally:
# 5. デバイス切断
print("\n5. デバイス切断中...")
if device.disconnect():
print("✓ デバイス切断完了")
else:
print("✗ デバイス切断失敗")
print("\nプログラム終了")
# テスト用コード
if __name__ == "__main__":
main()