-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathomxplayer-pir.py
executable file
·291 lines (231 loc) · 8.92 KB
/
omxplayer-pir.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
291
#!/usr/bin/env python
#
# Copyright (C) 2015-2017 Jozef Hutting <[email protected]>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
import sys
import os
import subprocess
import logging
import threading
import time
import RPi.GPIO as GPIO
__author__ = 'Jozef Hutting'
__copyright__ = 'Copyright (C) 2015 Jozef Hutting <[email protected]>'
__license__ = 'GPLv2'
__version__ = '0.14'
# USAGE
# sudo python omxplayer-pir FILE
# where
# FILE is the name of the file to play
# the REAL OMXPlayer
OMXPLAYER = 'omxplayer'
# REAL OMXPLAYER options
OMXPLAYER_ARGS = [
#'--display=4', # Raspberry Pi touchscreen
'--no-osd', # Do not display status information on screen
'--loop' # Loop file.
]
omxplayer = None
class OMXPlayer:
'''
Note: this python wrapper to control OMXPlayer is a very simple implementation.
If you want a more (on the edge) control over OMXPlayer, I suggest to use
Will Price OMXPlayer wrapper (https://github.com/willprice/python-omxplayer-wrapper).
'''
process = None
running = False
completed = False
def __init__(self):
self.logger = logging.getLogger('__OMXPlayer__')
def log(self, args):
self.logger.debug('{0}'.format(args))
def log_error(self, args):
self.logger.error('{0}'.format(args))
def play(self, filename):
def run_in_thread():
#def monitor(process):
# process.wait()
command = [OMXPLAYER]
command.extend(OMXPLAYER_ARGS) # default arguments
command.append(filename)
self.log('Full command={0}'.format(command))
with open(os.devnull, 'w') as devnull:
self.process = subprocess.Popen(command,
stdin=subprocess.PIPE,
stdout=devnull,
stderr=devnull)
# wait for REAL OMXPlayer process is running
while self.process.poll() is not None:
time.sleep(0.01) # seconds
self.log('#')
self.log('process PID={0}'.format(self.process.pid))
self.running = True
while True:
if self.process.poll() is not None:
break
self.log('REAL OMXPlayer exit status/return code : {0}'
.format(self.process.returncode))
self.completed = True
return
if not os.path.isfile(filename):
self.log_error('Error: File "{0}" not found!'.format(filename))
raise IOError(filename)
self.thread = threading.Thread(target=run_in_thread, args=())
self.thread.start()
self.log('Waiting for running REAL OMXPlayer...')
while(not self.running):
continue;
self.log('REAL OMXPlayer is up and running!')
def quit(self):
p = self.process
if (p is not None):
try:
self.log('Quitting REAL OMXPlayer...')
self.running = False
self.__key(b'q') # send quit command
# wait for process termination
self.thread.join()
except:
self.log_error('Error upon quitting REAL OMXPlayer: {0}'
.format(sys.exc_info()[0]))
def pause(self):
if self.running:
self.log('Pause REAL OMXPlayer')
self.__key(b' ') # SPACE character to pause
def resume(self):
if self.running:
self.log('Resume REAL OMXPlayer')
self.__key(b' ') # SPACE character to unpause
def __key(self, value):
if self.running:
try:
self.process.stdin.write(value)
self.log("Key b'{0}' sent successfully".format(value))
except:
self.log_error('Error on sending key to REAL OMXPlayer: {0}'
.format(sys.exc_info()[0]))
class PirControl():
'''
PIR (motion) sensor input signal :
- value 0 : no motion detected
- value 1 : motion detected
'''
def __init__(self):
self.logger = logging.getLogger('__PirControl__')
# ------ H A R D W A R E configuration ---------------------------------
#self.gpio = 22 # BCM port number!
#GPIO.setup(self.gpio, GPIO.IN, pull_up_down=GPIO.PUD_UP)
self.gpio = 7 # BCM port number!
GPIO.setup(self.gpio, GPIO.IN)
# ----------------------------------------------------------------------
self.state = self.__get_state()
self.log('initial state={0}'.format(self.state))
def __get_state(self):
return GPIO.input(self.gpio)
def start(self):
self.log('start')
GPIO.add_event_detect(self.gpio, GPIO.BOTH, callback=self.edge_callback
)#, bouncetime=1)
self.state = self.__get_state()
self.log('initial state={0}'.format(self.state))
def log(self, args):
self.logger.debug('{0}'.format(args))
def edge_callback(self, channel):
global omplayer
state = self.__get_state()
self.log('Edge detected {0}=>{1}'.format(self.state, state))
# Hmmm...sometimes I get 0=0 and 1=>1 edges!?
# I ONLY want the real edges!
if state != self.state:
if state == 1: # edge 0=>1
self.log('Motion detected!')
omxplayer.resume()
else: # edge 1=>0
self.log('NO motion detected')
omxplayer.pause();
self.state = state
def motion_detected(self):
self.state = self.__get_state()
return self.state == 1
class Main():
def __init__(self):
self.logger = logging.getLogger('__Main__')
def log(self, args):
self.logger.debug('{0}'.format(args))
def log_error(self, args):
self.logger.error('{0}'.format(args))
def run(self, filename):
global omxplayer
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
omxplayer = OMXPlayer()
pir_control = PirControl()
return_code = 0 # OK
try:
self.log('Waiting for operator clearing the scene...');
while(pir_control.motion_detected()):
continue;
self.log('Video player is armed!');
# handle the PIR sensor signal edges
pir_control.start()
# OMXPlayer doesn't have the ability to start in a PAUSED state, and
# a command to start the PLAYING.
# Therefor start with a PLAYING OMXPlayer...
self.log("Start REAL OMXPlayer");
omxplayer.play(filename)
# ...but as soon it is playing, PAUSEd it, as we want it to start
# playing on motion detection.
self.log("Pausing REAL OMXPlayer");
omxplayer.pause()
# Wait here until OMXPlayer is done playing the file
# Note: when the default arguments OMXPLAYER_ARGS contains '--loop'
# the looping is stopped (aborted) by CTRL+C (KeyboardInterrupt event).
self.log("Waiting for REAL OMXPlayer played the file...");
while(not omxplayer.completed):
continue
except IOError as e:
self.log_error('Error: File "{0}" not found!'.format(e.message))
return_code = -1
except KeyboardInterrupt:
"""http://stackoverflow.com/questions/19807134/python-sub-process-ctrlc"""
self.log('KeyboardInterrupt')
omxplayer.quit()
print('EXIT')
GPIO.cleanup()
return return_code
if __name__ == '__main__':
logging.basicConfig(level=logging.DEBUG)
# we need at least one FILE argument...
if len(sys.argv) < 2:
print('Error: missing FILE argument!')
sys.exit(-3)
# ... and at most one FILE argument
if len(sys.argv) > 2:
print('Error: too many arguments! Only one FILE argument expected.')
sys.exit(-2)
# so we only have one argument and that's the FILE argument
filename = sys.argv[1]
# check if the file exists
if not os.path.isfile(filename):
print('Error: File "{0}" not found!'.format(filename))
sys.exit(-1)
# so far so good, so let's play :-)
try:
mainloop = Main();
return_code = mainloop.run(filename);
finally:
pass
sys.exit(return_code);