-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathorac_hardware.py
More file actions
151 lines (124 loc) · 4.96 KB
/
Copy pathorac_hardware.py
File metadata and controls
151 lines (124 loc) · 4.96 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
"""
ORAC-NT + MPU-6050 – ХАРДУЕРНА ВЕРСИЯ v2
Фикс: baseline се изчислява ПООТДЕЛНО за всяка ос
"""
import serial
import time
import numpy as np
from collections import deque
class Watchdog_v5:
def __init__(self, h_limit=0.012, persistence_req=1, warmup_steps=100):
self.h_limit = h_limit
self.persistence_req = persistence_req
self.warmup = 0
self.warmup_steps = warmup_steps
self.consecutive = 0
self.cus_pos = [0., 0., 0.]
# Per-axis baseline
self.baseline = [deque(maxlen=warmup_steps) for _ in range(3)]
self.avg = [None, None, None]
self.k_drift = [None, None, None]
def compute(self, sensors):
self.warmup += 1
# Фаза 1: калибриране per-axis
if self.warmup <= self.warmup_steps:
for i, s in enumerate(sensors):
self.baseline[i].append(abs(s))
if self.warmup > 10:
for i in range(3):
self.avg[i] = np.mean(self.baseline[i])
self.k_drift[i] = max(0.005, np.std(self.baseline[i]) * 0.5)
return 0.0, 'CALIBRATING'
# Фаза 2: magnitude deviation detector
magnitude = np.sqrt(sum(s**2 for s in sensors))
baseline_mag = np.sqrt(sum(self.avg[i]**2 for i in range(3)))
deviation = abs(magnitude - baseline_mag)
if deviation > self.h_limit:
self.consecutive += 1
if self.consecutive >= self.persistence_req:
self.consecutive = 0
return 0.9, 'ANOMALY'
else:
self.consecutive = max(0, self.consecutive - 1)
return 0.0, 'NONE'
class OracController:
MODES = {'NORMAL': 0.0, 'SURVIVAL': 70.0}
def __init__(self):
self.current_mode = 'NORMAL'
self.temp = 25.0
def decide(self, score, fault, G):
if self.current_mode == 'SURVIVAL':
self.temp += 0.02 * (25 - self.temp)
else:
self.temp += 0.01 * (30 - self.temp)
Q = 1.0 - score
D = 1.0 - (self.MODES[self.current_mode] / 100.0)
T = np.clip((self.temp - 25) / 30, 0, 1)
W = Q * D - T
if fault == 'ANOMALY':
self.current_mode = 'SURVIVAL'
status = "⚠️ АНОМАЛИЯ"
elif G > 1.5 or G < 0.5:
self.current_mode = 'SURVIVAL'
status = "💥 УДАР"
elif W < 0.08:
self.current_mode = 'SURVIVAL'
status = "🔥 КРИТИЧНО"
else:
self.current_mode = 'NORMAL'
status = "✅ НОРМАЛНО"
return self.current_mode, W, status
def main():
print("=" * 70)
print("🚀 ORAC-NT v5.4 + MPU-6050 — ХАРДУЕРЕН ТЕСТ v2")
print("=" * 70)
try:
ser = serial.Serial('COM4', 115200, timeout=1)
time.sleep(2)
print("✅ Свързан с Arduino на COM4\n")
except Exception as e:
print(f"❌ Грешка: {e}")
return
watchdog = Watchdog_v5(warmup_steps=100)
orac = OracController()
print("⏳ Калибриране (100 стъпки)...\n")
print(f"{'Стъпка':>6} | {'G(X)':>7} | {'G(Y)':>7} | {'G(Z)':>7} | "
f"{'W':>7} | {'Режим':<10} | Статус")
print("-" * 78)
step = 0
try:
while True:
line = ser.readline().decode(errors='ignore').strip()
if line:
parts = line.split(',')
if len(parts) == 3:
try:
ax, ay, az = map(int, parts)
gx, gy, gz = ax/16384., ay/16384., az/16384.
score, fault = watchdog.compute([gx, gy, gz])
mode, W, status = orac.decide(score, fault, gz)
if fault == 'CALIBRATING':
if step % 10 == 0 and watchdog.avg[2]:
print(f"{step:6d} | {gx:7.3f} | {gy:7.3f} | {gz:7.3f} | "
f"{'---':>7} | {'CALIBR.':<10} | "
f"Z_avg={watchdog.avg[2]:.4f} "
f"k={watchdog.k_drift[2]:.4f}")
else:
print(f"{step:6d} | {gx:7.3f} | {gy:7.3f} | {gz:7.3f} | "
f"{W:7.3f} | {mode:<10} | {status}")
step += 1
except Exception:
pass
time.sleep(0.01)
except KeyboardInterrupt:
print("\n\n👋 Спиране.")
if watchdog.avg[2]:
print(f"\n📊 Per-axis baseline:")
axes = ['X', 'Y', 'Z']
for i in range(3):
print(f" G({axes[i]}): avg={watchdog.avg[i]:.4f} "
f"k_drift={watchdog.k_drift[i]:.4f}")
ser.close()
print("✅ Затворено.")
if __name__ == "__main__":
main()