Repository navigation
Expand file tree
/
Copy pathrqx590_gpio_trigger.py
More file actions
executable file
·253 lines (205 loc) · 8.82 KB
/
Copy pathrqx590_gpio_trigger.py
File metadata and controls
executable file
·253 lines (205 loc) · 8.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
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
#!/usr/bin/env python3
import time
from threading import Timer
import signal
import sys
import argparse
import os
import subprocess
try:
import psutil # for CPU affinity
except ImportError:
print("Module 'psutil' not found! Please run 'sudo apt install python3-psutil'")
exit(1)
try:
import gpiod # for native GPIO control
except ImportError:
print("Module 'gpiod' not found! Please run 'sudo apt install python3-libgpiod'")
exit(1)
import ctypes # for real-time scheduling
import ctypes.util
# Real-time scheduling parameters
SCHED_FIFO = 1
SCHED_RR = 2
SCHED_OTHER = 0
# Memory locking flags
MCL_CURRENT = 1
MCL_FUTURE = 2
class GPIOTrigger:
def __init__(self, frequency=10, chip_name="gpiochip0", line_numbers=[92, 49, 139, 138], cpu_core=3):
self.chip_name = chip_name
self.line_numbers = line_numbers
self.running = True
self.frequency = frequency
self.period = 1.0 / frequency
self.cpu_core = cpu_core
# libgpiod objects
self.chip = None
self.lines = None
# Set up signal handlers
signal.signal(signal.SIGINT, self.signal_handler)
signal.signal(signal.SIGTERM, self.signal_handler)
def lock_memory(self):
"""Lock process memory to prevent swapping"""
try:
libc = ctypes.CDLL(ctypes.util.find_library('c'), use_errno=True)
result = libc.mlockall(MCL_CURRENT | MCL_FUTURE)
if result != 0:
error = ctypes.get_errno()
raise OSError(error, f"mlockall failed: {os.strerror(error)}")
print("Successfully locked memory")
except Exception as e:
print(f"Warning: Could not lock memory: {str(e)}")
def set_realtime_priority(self):
try:
# Load the POSIX library
libc = ctypes.CDLL('libc.so.6')
# Define structure for scheduling parameters
class sched_param(ctypes.Structure):
_fields_ = [('sched_priority', ctypes.c_int)]
# Set real-time scheduling policy (SCHED_FIFO)
param = sched_param(99) # Maximum real-time priority
result = libc.sched_setscheduler(0, SCHED_FIFO, ctypes.byref(param))
if result == 0:
print("Successfully set real-time scheduling policy")
else:
print("Failed to set real-time scheduling policy. Are you running with sudo?")
except Exception as e:
print(f"Warning: Could not set real-time scheduling: {str(e)}")
def set_cpu_affinity(self):
try:
# Get the process
process = psutil.Process()
# Set CPU affinity to specified core
process.cpu_affinity([self.cpu_core])
print(f"Successfully set CPU affinity to core {self.cpu_core}")
except Exception as e:
print(f"Warning: Could not set CPU affinity: {str(e)}")
def setup_system_config(self):
try:
# Check if running as root
if os.geteuid() != 0:
raise PermissionError("This program must be run as root (sudo)")
# Set real-time group (if not already in group)
subprocess.run(["groupadd", "-f", "realtime"], check=True)
subprocess.run(["usermod", "-a", "-G", "realtime", os.getenv("SUDO_USER", "root")], check=True)
# Set system limits for real-time
limits_file = "/etc/security/limits.d/99-realtime.conf"
limits_content = """
@realtime soft rtprio 99
@realtime hard rtprio 99
@realtime soft memlock unlimited
@realtime hard memlock unlimited
"""
try:
with open(limits_file, "w") as f:
f.write(limits_content)
print(f"Created {limits_file} with real-time limits")
except Exception as e:
print(f"Warning: Could not create limits file: {str(e)}")
print("You may need to set up limits manually")
print("Real-time system configuration set up successfully")
except Exception as e:
print(f"Warning: Could not set up real-time system configuration: {str(e)}")
def setup_gpio(self):
try:
# Configure system for real-time operation
self.setup_system_config()
# Set CPU affinity
self.set_cpu_affinity()
# Set real-time priority
self.set_realtime_priority()
# Lock memory
self.lock_memory()
# Initialize gpiod objects
self.chip = gpiod.Chip(self.chip_name)
self.lines = self.chip.get_lines(self.line_numbers)
# Request lines as output and set initial value to LOW (0)
# This locks the GPIO file descriptors and prevents state drops
self.lines.request(consumer="fsync_trigger",
type=gpiod.LINE_REQ_DIR_OUT,
default_vals=[0] * len(self.line_numbers))
print("GPIO setup successful using native gpiod API")
except AttributeError:
print("Error: libgpiod API version mismatch. Make sure you are using libgpiod v1 bindings.")
sys.exit(1)
except Exception as e:
print(f"GPIO setup error: {str(e)}")
sys.exit(1)
def trigger_pulse(self):
if not self.running:
return
try:
start_time = time.perf_counter()
# Set all requested pins to HIGH
self.lines.set_values([1] * len(self.line_numbers))
# Precise sleep for 5 milliseconds
target_time = start_time + 0.005
while time.perf_counter() < target_time:
pass
# Set all requested pins to LOW
self.lines.set_values([0] * len(self.line_numbers))
# Calculate next trigger time and remaining sleep
end_time = time.perf_counter()
elapsed = end_time - start_time
sleep_time = max(0, self.period - elapsed)
# Schedule next trigger
if self.running:
Timer(sleep_time, self.trigger_pulse).start()
except Exception as e:
print(f"Error during trigger: {str(e)}")
self.cleanup()
def signal_handler(self, signum, frame):
print("\nReceived termination signal, cleaning up...")
self.cleanup()
def cleanup(self):
self.running = False
try:
if self.lines:
# Ensure all pins are set to LOW before releasing
self.lines.set_values([0] * len(self.line_numbers))
# Release the GPIO lines
self.lines.release()
if self.chip:
# Close the GPIO chip
self.chip.close()
print("GPIO resources cleanly released.")
except Exception as e:
print(f"Error during cleanup: {str(e)}")
sys.exit(0)
def run(self):
print(f"Starting GPIO trigger... (Frequency: {self.frequency} Hz)")
print(f"Using GPIO lines: {self.line_numbers}")
self.setup_gpio()
self.trigger_pulse()
def parse_arguments():
parser = argparse.ArgumentParser(description='Real-time GPIO Trigger Program')
parser.add_argument('-f', '--frequency',
type=float,
default=10.0,
help='Trigger frequency in Hz (default: 10 Hz)')
parser.add_argument('--chip',
type=str,
default="gpiochip0",
help='GPIO chip name (default: gpiochip0)')
parser.add_argument('--cpu-core',
type=int,
default=3,
help='CPU core to run on (default: 3)')
parser.add_argument('--min-freq',
type=float,
default=1,
help='Minimum allowed frequency in Hz (default: 1 Hz)')
parser.add_argument('--max-freq',
type=float,
default=30,
help='Maximum allowed frequency in Hz (default: 30 Hz)')
return parser.parse_args()
if __name__ == "__main__":
args = parse_arguments()
# Check if frequency is within valid range
if args.frequency < args.min_freq or args.frequency > args.max_freq:
print(f"Error: Frequency must be between {args.min_freq} Hz and {args.max_freq} Hz")
sys.exit(1)
trigger = GPIOTrigger(frequency=args.frequency, chip_name=args.chip, cpu_core=args.cpu_core)
trigger.run()