-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
187 lines (139 loc) · 6.82 KB
/
main.py
File metadata and controls
187 lines (139 loc) · 6.82 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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Bug : 數據點數不準確
"""
ProWaveDAQ主程式 - 振動數據採集系統
"""
import os
import sys
import time
import configparser
from datetime import datetime
from prowavedaq import ProWaveDAQ
from csv_writer import CSVWriter
def get_current_time() -> str:
"""取得當前時間作為格式化字串 (YYYYMMDDHHMMSS)"""
return datetime.now().strftime("%Y%m%d%H%M%S")
def clear_screen():
"""清除螢幕"""
os.system('cls' if os.name == 'nt' else 'clear')
def main():
"""主函數"""
daq = ProWaveDAQ()
while True:
clear_screen()
# 載入設定檔案以設定參數
ini_file_path = "API/Master.ini"
try:
config = configparser.ConfigParser()
config.read(ini_file_path, encoding='utf-8')
if not config.has_section('SaveUnit'):
print(f"無法載入INI檔案: {ini_file_path}")
return 1
# 讀取"SaveUnit"設定(時間間隔,單位:秒)
target_section = "SaveUnit"
target_key = "second"
save_unit = config.getint(target_section, target_key, fallback=60)
print(f"[{target_section}] {target_key} = {save_unit}")
except Exception as e:
print(f"載入INI檔案時發生錯誤: {e}")
return 1
# 初始化設備
daq.init_devices("API/ProWaveDAQ.ini")
pro_wave_daq_sample_rate = daq.get_sample_rate()
print(f"ProWaveDAQ取樣率: {pro_wave_daq_sample_rate} Hz")
# * 3 通道
# 計算預期的數據點數(每筆數據約123個樣本點)
expected_samples_per_second = pro_wave_daq_sample_rate * 3 # 每秒總樣本點數
target_size = save_unit * expected_samples_per_second
print(f"[Debug] 預期每檔案數據點數: {target_size}")
# 重置DAQ計數器,確保新一輪讀取時計數器從0開始
daq.reset_counter()
clear_screen() # 清除終端螢幕以提高可讀性
print("============================== 標籤建立 ============================")
label = input("請輸入數據標籤(輸入'exit'退出): ")
if label.lower() == "exit":
daq.stop_reading()
return 1
folder = get_current_time() + "_" + label
# 建立輸出目錄
output_path = os.path.join("output", "ProWaveDAQ", folder)
os.makedirs(output_path, exist_ok=True)
# 初始化CSV寫入器
csv_writer = CSVWriter(3, output_path, label)
is_running = True
data_size = 0
prev_counter = 0 # 初始化prev_counter
print("============================== 數據採集 ============================")
print("按'Q'退出...")
daq.start_reading()
try:
while is_running:
current_counter = daq.get_counter()
# print("[Debug] current_counter: ", current_counter)
# print("[Debug] prev_counter: ", prev_counter)
# 檢查鍵盤輸入(非阻塞)
try:
import select
import tty
import termios
# 設定終端為非阻塞模式
old_settings = termios.tcgetattr(sys.stdin)
tty.setraw(sys.stdin.fileno())
if select.select([sys.stdin], [], [], 0.1)[0]:
ch = sys.stdin.read(1)
if ch.lower() == 'q':
is_running = False
print("正在儲存最終數據後退出...")
# 立即恢復終端設定
termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_settings)
break
print(f"您按了: {ch}")
# 恢復終端設定
termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_settings)
except Exception as e:
# 其他錯誤的處理
print(f"其他錯誤: {e}")
# 處理所有可用的新數據(使用佇列避免重複讀取)
data = daq.get_data()
processed_count = 0 # 記錄處理的數據筆數
while data: # 當佇列中有數據時持續處理
data_size += len(data)
processed_count += 1 # 每處理一筆數據就增加計數
if data_size < target_size:
csv_writer.add_data_block(data)
print(f"[INFO] {datetime.now().strftime('%Y-%m-%d %H:%M:%S')} 數據已儲存")
else:
data_actual_size = len(data) # 防止誤用data_size
empty_space = target_size - (data_size - data_actual_size)
# 如果data_size > target_size,將數據分批處理
while data_size >= target_size:
batch = data[:empty_space]
csv_writer.add_data_block(batch)
# 每個完整批次後更新檔案名稱
csv_writer.update_filename()
print(f"[INFO] {datetime.now().strftime('%Y-%m-%d %H:%M:%S')} CSV已儲存並更新檔案名稱")
data_size -= target_size
pending = data_actual_size - empty_space
# 處理剩餘數據(少於target_size)
if pending:
remaining_data = data[empty_space:]
csv_writer.add_data_block(remaining_data)
data_size = pending
else:
data_size = 0
# 繼續從佇列中取得下一筆數據
data = daq.get_data()
# 根據實際處理的數據筆數更新prev_counter
prev_counter += processed_count
except KeyboardInterrupt:
print("\n收到中斷信號,正在退出...")
is_running = False
finally:
# 清理資源
csv_writer.close()
daq.stop_reading()
daq.stop_reading()
return 0
if __name__ == "__main__":
sys.exit(main())