-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
360 lines (296 loc) · 11.1 KB
/
main.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
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
import platform
import getpass
import os
import json
import subprocess
from OSC import OSCClient, OSCMessage, OSCServer
import time
import threading
import socket
from pathlib import Path
import sys
MAIN_PATH = "/home/pi/Documents/museum_video_player"
VIDEOFILE_PATH = "/home/pi/Videos" # Long term in fat32 partition
USER_SETTINGS_PATH = VIDEOFILE_PATH+"/settings/userSettings.json" # better close to the video file : fat32 editing
DEFAULT_SETTINGS_PATH = MAIN_PATH+"/settings/defaultSettings.json"
isPi = True
if (platform.machine().startswith("x86")):
isPi = False
if(platform.system() == "Darwin" and getpass.getuser()=='adminmac'):
#mac os et Aurelien Conil
MAIN_PATH = "/Users/adminmac/Boulot/JeanGiraudoux/GIT/museum_video_player"
VIDEOFILE_PATH = "/Users/adminmac/Movies/JeanGiraudoux"
USER_SETTINGS_PATH = VIDEOFILE_PATH+"/settings/UserSettings.json" # better close to the video file : fat32 editing
DEFAULT_SETTINGS_PATH = MAIN_PATH+"/settings/defaultSettings.json"
elif(platform.system() == "Darwin" and getpass.getuser()!='collor_nor'):
#print("Martin Rossi, tu dois mettre les chemin a l'interrieur du programme python")
#mac os et Martin Rossi (COLL OR_NOR)
VIDEOFILE_PATH = ""
if(isPi):
from omxplayer.player import OMXPlayer
GLOBAL_SETTINGS_PATH = MAIN_PATH+"/data/datajson.json" #NOT USED : TODO DELETE
class SimpleServer(OSCServer):
def __init__(self, t):
OSCServer.__init__(self, t)
self.selfInfos = t
self.addMsgHandler('default', self.handleMsg)
def handleMsg(self, oscAddress, tags, data, client_address):
global machine
global client
global isPlayingMovie
global runningApp
global omx_player1
global omx_player2
print("OSC message received on : "+oscAddress)
print("data: ")
print(data)
splitAddress = oscAddress.split("/")
#print(splitAddress)
############## APP itself #############
if(splitAddress[1] == "app"):
if(splitAddress[2] == "test"):
print("TEST"*10)
sendTestToMaster("TEST")
if(splitAddress[2] == "ispi"):
print("is pi ?")
print(isPi)
if(splitAddress[2]=="quit"):
print("Quitting the app : runningApp=false")
runningApp = False
if(splitAddress[2] == "update"):
print("update Radiologic2")
update()
reboot()
############## VIDEO PLAYER, OMX #############
if(splitAddress[1] == "video"):
if(splitAddress[2] == "start"):
print("Start video message")
if(isPi) and len(data)>0:
print("Play video on PI:"+data[0]+".mp4")
playVideo(data[0], False)
if(splitAddress[2] == "test"):
print("Start video TEST message")
if(isPi):
if(not(omx_player1 is None)):
omx_player1.quit()
omx_player1 = OMXPlayer(Path(VIDEOFILE_PATH+"/test.mp4"))
if(splitAddress[2] == "status"):
print("Get Status of video player1")
if(not(omx_player1 is None)):
sendToMaster("status", omx_player1.playback_status())
print("OMX player STATUS : "+omx_player1.playback_status())
else :
sendToMaster("status", "none")
print("OMX player STATUS : None")
if(splitAddress[2] == "stop"):
print("Stop video TEST message")
if(isPi):
stopAllVideo()
if(splitAddress[2] == "pause"):
print("Pause video TEST message")
############## RPI itself #############
elif(splitAddress[1] == "rpi"):
if(splitAddress[2] == "shutdown"):
print("Turning off the rpi")
#setVeille(True) # NOT IMPLETEMED YET
#powerOff() # NOT IMPLETEMED YET
if(splitAddress[2] == "reboot"):
print("Reboot the machine")
#setVeille(True) # NOT IMPLETEMED YET
#reboot() # NOT IMPLETEMED YET
# Video player works with 1 or 2 screen according to setting file
# With 1 screen data[0].mp4 is played
# With 2 screns data[0].mp4 and data[0]2.mp4 is played
# File existing test is only testing the first file : be carefull !
def playVideo(videoFileName, isLoop):
global omx_player1
global omx_player2
global userSettingsData
nbScreen = userSettingsData["video"]["screenNumber"]
path = VIDEOFILE_PATH+"/"+videoFileName
fileExist = os.path.exists(path+".mp4")
print("PLAY VIDEO FILE :"+videoFileName)
print("complete path: "+path)
if(fileExist):
print(" File exist :YES")
else:
print(" File exist :NO")
if(nbScreen == 1 and fileExist):
print("Play video : 1 screen")
if(not(omx_player1 is None)):
omx_player1.quit()
listOfArgs = ['--no-osd','--no-keys','-b','-o','local'] # local mean audio local, can be replaced with hdmi
if(isLoop):
listOfArgs.append('--loop')
omx_player1 = OMXPlayer(Path(path+".mp4"),dbus_name='org.mpris.MediaPlayer2.omxplayer1',args=listOfArgs)
omx_player1.stopEvent += player1Event
omx_player1.exitEvent += player1Event
elif(nbScreen == 2 and fileExist):
print("Play video : 2 screens")
if(not(omx_player1 is None)):
omx_player1.quit()
if(not(omx_player2 is None)):
omx_player2.quit()
listOfArgs1 = ['--no-osd','--no-keys','-b', '--display=2', '-o', 'local'] # local mean audio local, can be replaced with hdmi
listOfArgs2 = ['--no-osd','--no-keys','-b', '--display=7']
if(isLoop):
listOfArgs.append('--loop')
omx_player1 = OMXPlayer(Path(path+".mp4"), dbus_name='org.mpris.MediaPlayer2.omxplayer1', args=listOfArgs1)
omx_player2 = OMXPlayer(Path(path+"2.mp4"), dbus_name='org.mpris.MediaPlayer2.omxplayer2', args=listOfArgs2)
omx_player1.stopEvent += player1Event
omx_player1.exitEvent += player1Event
omx_player2.stopEvent += player2Event
omx_player2.exitEvent += player2Event
#TODO : add event callback here
else:
print("ERROR : NbScreen is wrong or file does not exist ! Playing aborted")
def stopAllVideo():
global omx_player1
global omx_player2
if(not(omx_player1 is None)):
try:
if(omx_player1.can_quit()):
print("omxplayer 1 can quit")
omx_player1.quit()
print("omxplayer 1 : quit")
except :
print(" ERROR : quitting omxplayer1")
print("Unexpected error:", sys.exc_info()[0])
if(not(omx_player2 is None)):
try:
if(omx_player2.can_quit()):
print("omxplayer 2 can quit")
omx_player2.quit()
print("omxplayer2 quit")
except :
print(" ERROR : quitting omxplayer2")
print("Unexpected error:", sys.exc_info()[0])
def update():
print("========= UPDATE PYTHON SCRIPT ======")
os.chdir(MAIN_PATH+"/script")
subprocess.call(["./update.sh"])
print("========= UPDATED PYTHON SCRIPT ======")
def sendTestToMaster(arg):
global client_master
oscmsg = OSCMessage()
oscmsg.setAddress("/test")
oscmsg.append(arg)
client_master.send(oscmsg)
def sendToMaster(adress, arg):
global client_master
oscmsg = OSCMessage()
oscmsg.setAddress("/"+adress)
oscmsg.append(arg)
client_master.send(oscmsg)
def player1Event(arg1, arg2):
global omx_player1
print("*** This is a player1 event ***" )
print(arg1)
print(arg2)
omx_player1 = None
print("omx_player1 = None " )
def player2Event(arg1, arg2):
global omx_player2
print("*** This is a player2 event ***" )
print(arg1)
print(arg2)
omx_player2 = None
print("omx_player2 = None " )
def initSettings():
global userSettingsData
global confSettings
# load existing user settings
settingsFilePath = DEFAULT_SETTINGS_PATH
if(os.path.exists(USER_SETTINGS_PATH)):
settingsFilePath = USER_SETTINGS_PATH
print("SETTINGS : user setting")
else:
print("SETTING : default ")
with open(settingsFilePath, 'r') as userFp:
userSettingsData = json.load(userFp)
def get_ip():
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
# doesn't even have to be reachable
s.connect(('10.255.255.255', 1))
IP = s.getsockname()[0]
except:
IP = '127.0.0.1'
finally:
s.close()
return IP
def main():
print(" ===== init settings ====")
# will ensure any default settings are present in datajson/metadata
# TODO test minimum configuration is available, otherwise, kill with error message
initSettings()
# TODO : add a try on every call on omxplayer, and avoid any risk of crash
# Function to add set_volume(volume)
#
# OSC SERVER
# myip = get_ip()
print(" ===== OSC SERVER ====")
myip = "0.0.0.0"
myip = get_ip()
print("IP adress is : "+myip)
try:
server = SimpleServer((myip, 6666))
print("server created on port 6666")
except :
print(" ERROR : creating server")
print("Unexpected error:", sys.exc_info()[0])
#Exit or Terminate successfully
sys.exit(0)
try:
st = threading.Thread(target=server.serve_forever)
except:
print(" ERROR : creating thread")
print("Unexpected error:", sys.exc_info()[0])
#Exit or Terminate successfully
sys.exit(0)
try:
st.start()
except:
print(" ERROR : starting thread")
print("Unexpected error:", sys.exc_info()[0])
#Exit or Terminate successfully
sys.exit(0)
print(" OSC server is running")
# OSC CLIENT : send osc message
print(" ===== OSC CLIENT ====")
global client_master
client_master = OSCClient()
mip = userSettingsData["master"]["ip"]
mport = userSettingsData["master"]["port"]
print("Client OSC to master | ip: "+mip+" | port: "+str(mport))
client_master.connect((mip, mport))
# OMX PLAYER INSTANCE
global omx_player1
global omx_player2
omx_player1 = None
omx_player2 = None
# MAIN LOOP
global runningApp
runningApp = True
print(" ===== STARTING MAIN LOOP ====")
while runningApp:
# This is the main loop
# Do something here
try:
time.sleep(1)
except:
print("User attempt to close programm")
runningApp = False
print("Main loop is quit. Closing software")
# Closing omx instances
print("STOP video first")
stopAllVideo()
# CLOSING THREAD AND SERVER
print(" Ending programme")
server.running = False
print(" Join thread")
st.join()
server.close()
print(" This is probably the end")
if __name__ == "__main__":
main()