-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAATC_GPIO.py
292 lines (208 loc) · 10.1 KB
/
AATC_GPIO.py
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
import threading,multiprocessing,queue,time,random, sys
try:
import RPi.GPIO as GPIO
ENABLE_GPIO = True
except:
print("No RPi.GPIO module available. Features depending on this will not work/crash")
ENABLE_GPIO = False
#GPIO.setmode(GPIO.BOARD)
##GPIO.setup(11, GPIO.OUT) #red
##GPIO.setup(13, GPIO.OUT) #amber
##GPIO.setup(21, GPIO.OUT) #green
##GPIO.setup(26, GPIO.IN) #button
def GPIO_Wait_Switch(pin,wait_time = 1, SWITCH_MODE= 1, Indicator_Pin = False): # Will wait for pin to switch to the SWITCH_MODE setting. If not will sleep for wait_time seconds.
#if "GPIO" in sys.modules: # If does not have GPIO will automatically pass through.
if ENABLE_GPIO:
GPIO.setmode(GPIO.BOARD)
GPIO.setup(pin,GPIO.IN)
if Indicator_Pin:
GPIO_Queue = Create_Controller(Name = "AMBER_LED")
GPIO_Queue.put(("Controller","Create_Thread",("INDICATOR",)))
while GPIO.input(pin) != SWITCH_MODE:
if Indicator_Pin:
GPIO_Queue.put(("INDICATOR","Function",(Blink,(Indicator_Pin,1/wait_time,1,False)))) # will automatically blink at a rate of 1 blink per wait_time
time.sleep(wait_time)
else:
pass
def GPIO_Thread(Thread_Name,GPIO_Queue): #Generic thread for executing functions
Exit = False
Function = BlankFunction
FuncArgs = ()
while not Exit:
try:
Repeat = Function(Thread_Name,*FuncArgs) #calls the function passed to the thread
if not Repeat:
Function,FuncArgs = BlankFunction,() #Resets commands. Allows function to exit itself.
while not GPIO_Queue.empty(): #While loop implemented so that if many commands are send per loop they will all be processed.
Data = GPIO_Queue.get()
#GPIO_Queue.task_done()
Command,Arguments = Data[0],Data[1]
if Command == "Function":
Function, FuncArgs = Arguments[0],Arguments[1]
elif Command == "Exit":
Exit = True
except Exception as e:
print("Error occured in GPIO_Thread",Thread_Name,".",str(e))
Function,FuncArgs = BlankFunction,() #Resets commands to prevent large prints
class Thread_Handle: #Acts as storage for thread name, pointer and communications queue
def __init__(self,Thread_Name,ThreadPointer,Queue):
self._Thread_Name = Thread_Name
self._ThreadPointer = ThreadPointer
self._Queue = Queue
def Get_Thread_Name(self):
return self._Thread_Name
def Get_ThreadPointer(self):
return self._ThreadPointer
def Get_Queue(self):
return self._Queue
class Thread_Controller: #Handle usage of sub processes automatically using this object
def __init__(self,Command_Queue,Name = ""):
print("Creating Thread Controller",Name)
self._Name ="TC"+ Name + " >"
self._Command_Queue = Command_Queue
self._Threads = {}
def Create_Thread(self,Thread_Name,TargetCommand = GPIO_Thread,TargetArgs = (),Process = False): #If Process is True, will use a Process rather than a thread.
if Thread_Name in self._Threads: #Close thread if already exists
self.Close_Thread(Thread_Name)
if Process:
Thread_Queue = multiprocessing.Queue()
threadPointer = multiprocessing.Process(target = TargetCommand,args = (Thread_Name,Thread_Queue)+TargetArgs)
else: #Create the secondary thread/process depending on selected type
Thread_Queue = queue.Queue()
threadPointer = threading.Thread(target = TargetCommand,args = (Thread_Name,Thread_Queue)+TargetArgs)
self._Threads[Thread_Name] = Thread_Handle(Thread_Name,threadPointer,Thread_Queue)
threadPointer.start()
def Close_Thread(self,Thread_Name): #Close a thread of this name
ClosingThreadHandle = self._Threads.pop(Thread_Name)
Queue = ClosingThreadHandle.Get_Queue()
Queue.put(("Exit",()))
print(self._Name,"GPIO Controller closed Thread",Thread_Name)
return ClosingThreadHandle #Returns Thread_Handle of thread
def PassData(self,Thread_Name,Data): #Pass data to the subprocess via the queue
Queue = self._Threads[Thread_Name].Get_Queue()
Queue.put(Data)
def Main(self):
Exit = False
while not Exit:
try:
Request = self._Command_Queue.get() #(Thread_Name/Controller,"Command",Args)
self._Command_Queue.task_done()
if Request[0] == "Controller": #If this is a command to be processed by the controller
Command,Args = Request[1],Request[2]
if Command == "Create_Thread": #In total form ("Controller","Create_Thread",(ThreadName,[TargetFunction,TargetArguments]))
self.Create_Thread(*Args)
elif Command == "Create_Process":
self.Create_Thread(*Args, Process = True)
elif Command == "Close_Thread":
self.Close_Thread(*Args)
elif Command == "Exit": #Shutdown everything
self.Reset(*Args)
Exit = True
elif Command == "Reset": #Shutdown all threads, not controller
self.Reset(*Args)
else:
self.PassData(Request[0],Request[1:]) #Pass the data to the subprocess excluding the Target process name.
except Exception as e:
print(self._Name,"Error in GPIO_Thread_Controller",e)
print(self._Name,"Shutting down")
def Reset(self,Wait_Join = False): #Close all processes , optionally waiting for them to join.
print(self._Name,"Reseting GPIO Threading Controller...")
Thread_Names = list(self._Threads.keys())
ThreadHandles = []
for Thread_Name in Thread_Names:
ClosingThreadHandle = self.Close_Thread(Thread_Name)
ThreadHandles.append(ClosingThreadHandle)
if Wait_Join: #In seperate loop to asyncrously call 'Exit'
for ThreadHandle in ThreadHandles:
ThreadPointer = ThreadHandle.Get_ThreadPointer()
ThreadPointer.join()
print(self._Name,"Reset GPIO Threading Controller")
def Create_Controller(process = False, Name = ""): #Create a thread controller and return the command queue
if process:
q = multiprocessing.Queue()
else:
q = queue.Queue()
TC = Thread_Controller(q,Name)
if process:
t = multiprocessing.Process(target = TC.Main)
else:
t = threading.Thread(target = TC.Main)
t.start()
return q
"""
Thread_Name is common to all processes accessing the Thread_Controller.
EG 'RED' will always reference the thread 'RED'.
Pin Number is not fixed per thread. Threads can control multiple pins or none at all. A new function can change the pins a Thread is controlling.
def Command(Thread_Name,arg1,arg2...):
run function code
...
...
...
end of function code
return True/False # return Repeat value. If True, function will be repeated. If False will exit.
"""
# Example functions
def BlankFunction(Thread_Name): #Just sleep repeatedly
time.sleep(0.2)
return True
def DisplayName(Thread_Name,Sleep_Time): #Repeatedly display the threads name
print("Message from Thread",Thread_Name,". Sleeping for time",Sleep_Time)
time.sleep(Sleep_Time)
return True
def BlinkTest(Thread_Name,pin,frequency,cycles=1,repeat = False): #prints demonstration of blinking pin in text, Frequency in Hz, cycles = repeats till check for new instruction
pauseTime = 1/(frequency*2)
for x in range(cycles):
print("Activating blink pin",pin, "Cycle:",x)
time.sleep(pauseTime)
print("Deactivating blink pin",pin, "Cycle:",x)
time.sleep(pauseTime)
return repeat
##################General GPIO functions
def Blink(Thread_Name,pin,frequency,cycles = 1,repeat= False): #Blinks an LED
pauseTime = 1/(frequency*2)
GPIO.setmode(GPIO.BOARD)
GPIO.setup(pin,GPIO.OUT)
try:
for x in range(cycles):
#On
GPIO.output(pin,1)
time.sleep(pauseTime)
#Off
GPIO.output(pin,0)
time.sleep(pauseTime)
finally:
GPIO.cleanup(pin)
return repeat
def Pattern(Thread_Name, Pattern ,ReferenceTime=1,repeat = True): #Executes a pattern of LED events
pins = set()
for item in Pattern:
pins.add(item[0])
try:
GPIO.setmode(GPIO.BOARD)
## GPIO.setup(11, GPIO.OUT) #red
## GPIO.setup(13, GPIO.OUT) #amber
## GPIO.setup(21, GPIO.OUT) #green
for pin in pins:
GPIO.setup(pin,GPIO.OUT)
#Pattern consists of a list with tuples of (Pin,State,WaitTime)
for Step in Pattern:
Pin = Step[0]
State = Step[1]
WaitTime = Step[2]
GPIO.output(Pin,State)
print("Thread {} | Pin {:>3} | State {:>2} | WaitTime {:>4}".format(Thread_Name,str(Pin),str(State),str(WaitTime)))
time.sleep(WaitTime*ReferenceTime)
except Exception as e:
print("Exception in PatternTest",e)
finally:
GPIO.cleanup(*pins)
return repeat
def PatternGenerator(PinSet=[11,13,21],StateSet = [0,1] ,Length = 50 ,MinTime = 0.1 ,MaxTime = 1 , RoundingTime = 2): #Generate a random pattern
Pattern = []
for x in range(Length):
Pattern.append((
random.choice(PinSet),
random.choice(StateSet),
round(random.random()*(MaxTime-MinTime)+MinTime,RoundingTime)
))
return Pattern