forked from JW-Albert/ProWaveDAQ-Python-Visualization-Unit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsql_uploader.py
More file actions
executable file
·434 lines (367 loc) · 16.9 KB
/
sql_uploader.py
File metadata and controls
executable file
·434 lines (367 loc) · 16.9 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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
SQL 上傳器模組
負責將振動數據上傳至 SQL 伺服器(MySQL/MariaDB),支援動態建立資料表和批次插入。
"""
import time
import os
import csv
from datetime import datetime
from typing import List, Optional, Dict
import threading
try:
import pymysql
PYMySQL_AVAILABLE = True
except ImportError:
try:
import mysql.connector
PYMySQL_AVAILABLE = False
MYSQL_CONNECTOR_AVAILABLE = True
except ImportError:
PYMySQL_AVAILABLE = False
MYSQL_CONNECTOR_AVAILABLE = False
# 導入統一日誌系統
try:
from logger import info, debug, error, warning
except ImportError:
# 如果無法導入,使用簡單的 fallback
def info(msg): print(f"[INFO] {msg}")
def debug(msg): print(f"[Debug] {msg}")
def error(msg): print(f"[Error] {msg}")
def warning(msg): print(f"[Warning] {msg}")
if not PYMySQL_AVAILABLE and not MYSQL_CONNECTOR_AVAILABLE:
warning("未安裝 pymysql 或 mysql-connector-python,SQL 上傳功能將無法使用")
class SQLUploader:
"""SQL 上傳器類別,支援動態建立資料表和批次插入"""
def __init__(self, channels: int, label: str, sql_config: Dict[str, str]):
"""初始化 SQL 上傳器"""
self.channels = channels
self.label = label
self.sql_config = sql_config
self.connection: Optional[object] = None
self.cursor: Optional[object] = None
self.upload_lock = threading.Lock()
self.is_connected = False
self.current_table_name = None
def _get_connection(self):
"""取得資料庫連線(使用 pymysql 或 mysql.connector)"""
if not PYMySQL_AVAILABLE and not MYSQL_CONNECTOR_AVAILABLE:
raise ImportError("未安裝 pymysql 或 mysql-connector-python")
try:
if PYMySQL_AVAILABLE:
return pymysql.connect(
host=self.sql_config.get('host', 'localhost'),
port=int(self.sql_config.get('port', 3306)),
user=self.sql_config.get('user', 'raspberrypi'),
password=self.sql_config.get('password', 'Raspberry@Pi'),
database=self.sql_config.get('database', 'daq-prowavedaq-data'),
charset='utf8mb4',
autocommit=False
)
else: # mysql.connector
return mysql.connector.connect(
host=self.sql_config.get('host', 'localhost'),
port=int(self.sql_config.get('port', 3306)),
user=self.sql_config.get('user', 'raspberrypi'),
password=self.sql_config.get('password', 'Raspberry@Pi'),
database=self.sql_config.get('database', 'daq-prowavedaq-data'),
autocommit=False
)
except Exception as e:
error(f"SQL 連線失敗: {e}")
raise
def _sanitize_table_name(self, table_name: str) -> str:
"""清理表名,確保符合 SQL 命名規範"""
import re
sanitized = re.sub(r'[^a-zA-Z0-9_]', '_', table_name)
if sanitized and sanitized[0].isdigit():
sanitized = 't_' + sanitized
if not sanitized:
sanitized = 'vibration_data'
return sanitized
def create_table(self, table_name: str) -> bool:
"""建立新的資料表(表名與 CSV 檔名對應)"""
try:
sanitized_table_name = self._sanitize_table_name(table_name)
if not self.connection:
if not self._reconnect():
error("無法建立 SQL 表:連線失敗")
return False
try:
if PYMySQL_AVAILABLE:
self.connection.ping(reconnect=True)
else:
if not self.connection.is_connected():
if not self._reconnect():
return False
except:
if not self._reconnect():
return False
if not self.cursor:
self.cursor = self.connection.cursor()
create_table_sql = f"""
CREATE TABLE IF NOT EXISTS `{sanitized_table_name}` (
id BIGINT AUTO_INCREMENT PRIMARY KEY,
timestamp DATETIME(6) NOT NULL,
label VARCHAR(255) NOT NULL,
channel_1 DOUBLE NOT NULL,
channel_2 DOUBLE NOT NULL,
channel_3 DOUBLE NOT NULL,
INDEX idx_timestamp (timestamp),
INDEX idx_label (label)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
"""
self.cursor.execute(create_table_sql)
self.connection.commit()
self.current_table_name = sanitized_table_name
self.is_connected = True
info(f"SQL 資料表已建立: {sanitized_table_name} (對應 CSV: {table_name})")
return True
except Exception as e:
error(f"建立 SQL 資料表失敗: {e}")
self.is_connected = False
return False
def _reconnect(self) -> bool:
"""重新連線到 SQL 伺服器"""
try:
if self.connection:
try:
self.connection.close()
except:
pass
self.connection = self._get_connection()
if PYMySQL_AVAILABLE:
self.cursor = self.connection.cursor()
else: # mysql.connector
self.cursor = self.connection.cursor()
self.is_connected = True
info("SQL 連線已重新建立")
return True
except Exception as e:
error(f"SQL 重新連線失敗: {e}")
self.is_connected = False
return False
def add_data_block(self, data: List[float]) -> bool:
"""
新增數據區塊到 SQL 伺服器
此方法會將資料按通道分組(每 3 個為一組:X, Y, Z),
並使用批次插入(executemany)提升效能。
錯誤處理機制:
- 最多重試 3 次
- 每次重試前會檢查連線狀態,如果斷線則嘗試重連
- 重試延遲時間遞增(0.1s, 0.2s, 0.3s)
- 如果所有重試都失敗,返回 False(資料不會遺失,會保留在緩衝區)
Args:
data: 振動數據列表,格式為 [X1, Y1, Z1, X2, Y2, Z2, ...]
Returns:
bool: 上傳成功返回 True,失敗返回 False
注意:
- 此方法使用執行緒鎖(upload_lock)確保多執行緒安全
- 如果資料長度不是 channels 的倍數,不足的部分會填充 0.0
- 所有資料使用相同的時間戳記(當前時間)
- 使用批次插入(executemany)可以大幅提升插入效能
"""
if not data or not self.is_connected:
return False
# 使用執行緒鎖確保多執行緒安全
with self.upload_lock:
max_retries = 3 # 最多重試 3 次
retry_count = 0
while retry_count < max_retries:
try:
if not self.connection:
if not self._reconnect():
retry_count += 1
time.sleep(0.1 * retry_count)
continue
try:
if PYMySQL_AVAILABLE:
self.connection.ping(reconnect=True)
else:
if not self.connection.is_connected():
if not self._reconnect():
retry_count += 1
time.sleep(0.1 * retry_count)
continue
except:
if not self._reconnect():
retry_count += 1
time.sleep(0.1 * retry_count)
continue
if not self.current_table_name:
error("SQL 表名未設定,無法插入資料。請先呼叫 create_table() 建立表")
return False
insert_sql = f"""
INSERT INTO `{self.current_table_name}` (timestamp, label, channel_1, channel_2, channel_3)
VALUES (%s, %s, %s, %s, %s)
"""
timestamp = datetime.now()
rows_to_insert = []
for i in range(0, len(data), self.channels):
row_data = [
timestamp,
self.label,
data[i] if i < len(data) else 0.0,
data[i + 1] if i + 1 < len(data) else 0.0,
data[i + 2] if i + 2 < len(data) else 0.0
]
rows_to_insert.append(tuple(row_data))
if rows_to_insert:
if not self.cursor:
self.cursor = self.connection.cursor()
self.cursor.executemany(insert_sql, rows_to_insert)
self.connection.commit()
return True
except Exception as e:
error(f"SQL 寫入資料失敗 (嘗試 {retry_count + 1}/{max_retries}): {e}")
try:
if self.connection:
self.connection.rollback()
except:
pass
self.is_connected = False
retry_count += 1
if retry_count < max_retries:
time.sleep(0.1 * retry_count)
if not self._reconnect():
continue
else:
error(f"SQL 寫入資料失敗,已重試 {max_retries} 次,放棄此次上傳")
return False
return False
def upload_from_csv_file(self, csv_file_path: str, table_name: Optional[str] = None) -> bool:
"""
從 CSV 檔案讀取資料並上傳至 SQL 伺服器
此方法會讀取 CSV 檔案中的所有資料,並批次上傳至 SQL 伺服器。
如果未指定表名,會從 CSV 檔名自動推斷(去除路徑和 .csv 後綴)。
Args:
csv_file_path: CSV 檔案路徑
table_name: 目標表名(可選,如果不提供則從檔名推斷)
Returns:
bool: 上傳成功返回 True,失敗返回 False
注意:
- CSV 檔案格式應為:Timestamp, Channel_1(X), Channel_2(Y), Channel_3(Z)
- 第一行會被視為標題行並跳過
- 使用批次插入提升效能
- 如果表不存在,會自動建立
"""
if not os.path.exists(csv_file_path):
error(f"CSV 檔案不存在: {csv_file_path}")
return False
# 如果未指定表名,從檔名推斷
if not table_name:
filename = os.path.basename(csv_file_path)
table_name = os.path.splitext(filename)[0]
# 清理表名
sanitized_table_name = self._sanitize_table_name(table_name)
# 確保表存在
if sanitized_table_name != self.current_table_name:
if not self.create_table(table_name):
error(f"無法建立 SQL 表: {sanitized_table_name}")
return False
# 讀取 CSV 檔案
try:
rows_to_insert = []
with open(csv_file_path, 'r', encoding='utf-8') as f:
reader = csv.reader(f)
next(reader) # 跳過標題行
for row in reader:
if len(row) < 4:
continue
try:
timestamp_str = row[0]
channel_1 = float(row[1])
channel_2 = float(row[2])
channel_3 = float(row[3])
# 解析時間戳記
try:
timestamp = datetime.fromisoformat(timestamp_str)
except:
timestamp = datetime.now()
rows_to_insert.append((
timestamp,
self.label,
channel_1,
channel_2,
channel_3
))
except (ValueError, IndexError) as e:
warning(f"跳過無效的 CSV 行: {row}, 錯誤: {e}")
continue
if not rows_to_insert:
warning(f"CSV 檔案中沒有有效資料: {csv_file_path}")
return True # 檔案為空,視為成功
# 批次上傳
with self.upload_lock:
max_retries = 3
retry_count = 0
while retry_count < max_retries:
try:
if not self.connection:
if not self._reconnect():
retry_count += 1
time.sleep(0.1 * retry_count)
continue
try:
if PYMySQL_AVAILABLE:
self.connection.ping(reconnect=True)
else:
if not self.connection.is_connected():
if not self._reconnect():
retry_count += 1
time.sleep(0.1 * retry_count)
continue
except:
if not self._reconnect():
retry_count += 1
time.sleep(0.1 * retry_count)
continue
if not self.cursor:
self.cursor = self.connection.cursor()
insert_sql = f"""
INSERT INTO `{sanitized_table_name}` (timestamp, label, channel_1, channel_2, channel_3)
VALUES (%s, %s, %s, %s, %s)
"""
# 批次插入
self.cursor.executemany(insert_sql, rows_to_insert)
self.connection.commit()
info(f"成功從 CSV 檔案上傳 {len(rows_to_insert)} 筆資料至 SQL 表: {sanitized_table_name}")
return True
except Exception as e:
error(f"從 CSV 檔案上傳資料失敗 (嘗試 {retry_count + 1}/{max_retries}): {e}")
try:
if self.connection:
self.connection.rollback()
except:
pass
self.is_connected = False
retry_count += 1
if retry_count < max_retries:
time.sleep(0.1 * retry_count)
if not self._reconnect():
continue
else:
error(f"從 CSV 檔案上傳資料失敗,已重試 {max_retries} 次")
return False
return False
except Exception as e:
error(f"讀取 CSV 檔案時發生錯誤: {e}")
return False
def close(self) -> None:
"""關閉 SQL 連線"""
with self.upload_lock:
try:
if self.cursor:
self.cursor.close()
self.cursor = None
if self.connection:
self.connection.close()
self.connection = None
self.is_connected = False
info("SQL 連線已關閉")
except Exception as e:
error(f"關閉 SQL 連線時發生錯誤: {e}")
def __del__(self):
"""解構函數"""
self.close()