-
Notifications
You must be signed in to change notification settings - Fork 0
/
main2.py
382 lines (316 loc) · 11.2 KB
/
main2.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
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
import platform
import getpass
import os
import json
import subprocess
from OSC import OSCClient, OSCMessage, OSCServer
import time
import threading
import socket
import sys
from VidPlayerClass import VidPlayer
MAIN_PATH = "/home/pi/Documents/museum_video_player"
VIDEOFILE_PATH = "/media/fat32"
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 runningApp
global vid
global flagToStop
global flagToPlayMain
global flagToPlayWait
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
############## VIDEO PLAYER, OMX #############
if(splitAddress[1] == "video"):
if(splitAddress[2] == "playmain"):
if(not(flagToPlayMain)):
print("Play main file")
flagToPlayMain = True
while(vid.state != vid.PLAYINGMAIN):
time.sleep(0.2)
flagToPlayMain = False
print("Flag to false")
else :
print("ERROR Main file already opening")
if(splitAddress[2] == "playwait"):
if(not(flagToPlayWait )):
print("Play wait file")
flagToPlayWait = True
while(vid.state != vid.PLAYINGSECOND):
time.sleep(0.2)
flagToPlayWait = False
print("Flag to false")
else :
print("ERROR Main file already opening")
if(splitAddress[2] == "status"):
vid.printState()
sendToMaster("status", vid.state)
if(splitAddress[2] == "pause"):
vid.pause_play()
if(splitAddress[2] == "stop"):
if(not(flagToStop)):
print("Stop all action, go to waiting mode")
flagToStop = True
while(vid.state != vid.WAITING):
time.sleep(0.2)
flagToStop = False
print("Flag to false")
else :
print("ERROR Stop flag already operating")
############## RPI itself #############
elif(splitAddress[1] == "rpi"):
if(splitAddress[2] == "startx"):
print("Starting desktop")
startx()
if(splitAddress[2] == "shutdown"):
print("Turning off the rpi")
powerOff()
if(splitAddress[2] == "reboot"):
print("Reboot the machine")
#setVeille(True) # NOT IMPLETEMED YET
reboot() #
def powerOff():
time.sleep(5)
print("========= POWER OFF ======")
os.chdir(MAIN_PATH+"/script")
subprocess.call(['./shutdown.sh'])
def reboot():
time.sleep(5)
print("========= POWER OFF ======")
os.chdir(MAIN_PATH+"/script")
subprocess.call(['./reboot.sh'])
def startx():
time.sleep(5)
print("========= STARTX ======")
launchCmd(MAIN_PATH+"/script" , ["./startx.sh"])
def launchCmd(dir, cmd):
try:
os.chdir(dir)
subprocess.Popen(cmd)
except Exception as e:
print(" error on running cmd " + str(cmd))
print(e)
def sendTestToMaster(arg):
sendToMaster("test", arg)
def sendToMaster(adress, arg):
#global client_master
client_master = OSCClient()
global mip
global mport
oscmsg = OSCMessage()
print(" ===== SEND TO MASTER ====")
print(get_ip())
finalAddress = "/"+userSettingsData["identity"]["name"]+"/"+adress
oscmsg.setAddress(finalAddress)
print("msg adress : "+finalAddress)
print("ip msg adress : "+mip)
print("port msg adress : "+str(mport))
oscmsg.append(arg)
try :
client_master.sendto(oscmsg, (mip, mport))
except :
print("Impossible d'envoyer un message au master")
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, encoding='utf-8')
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("============= ")
print(" MUSEUM : WELCOME : starting in 10 sec")
if(isPi):
time.sleep(10)
print(" started")
print("============= ")
global userSettingsData
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()
#PLAYLIST
playlist = []
try:
media = userSettingsData["playlist"]["mainMediaPath"]
playlist.append(media)
media = userSettingsData["playlist"]["waitingMediaPath"]
playlist.append(media)
except :
print(" ERROR : creating playlist. Error in json file. Try json_tester.py")
print("Unexpected error:", sys.exc_info()[0])
#Exit or Terminate successfully
sys.exit(0)
print("==== playlist ===== ")
print(VIDEOFILE_PATH+"/"+playlist[0]+".mp4")
print(VIDEOFILE_PATH+"/"+playlist[1]+".mp4")
global vid
global flagToPlayMain
global flagToPlayWait
global flagToStop
isVideoRandom = ("random" in userSettingsData)
vid = VidPlayer(userSettingsData["video"]["screenNumber"], playlist, VIDEOFILE_PATH, isVideoRandom)
if(isVideoRandom):
print("VideoPlayer RANDOM Mode activated")
vid.randomNbFolder = userSettingsData["random"]["nbFolder"]
vid.setRandom()
flagToPlayMain = False
flagToPlayWait = False
flagToStop = False
# OSC SERVER
# myip = get_ip()
print(" ===== MY IP IS ====")
print(get_ip())
print(" ===== OSC SERVER ====")
myip = "0.0.0.0"
myport = userSettingsData["in"]["port"]
print("IP adress is : "+myip+" port="+str(myport))
server = None
while server == None :
try:
server = SimpleServer((myip, myport))
print("Server created on port :"+str(myport))
except Exception as inst:
print(" ERROR : creating server")
print("Unexpected error:", sys.exc_info()[0])
print(inst)
print("retry now")
time.sleep(1)
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")
print(" ===== MY IP IS ====")
print(get_ip())
# OSC CLIENT : send osc message
print(" ===== OSC CLIENT ====")
#global client_master
#client_master = OSCClient()
global mip
global mport
mip = userSettingsData["master"]["ip"]
mport = userSettingsData["master"]["port"]
# print("Client OSC to master | ip: "+mip+" | port: "+str(mport))
# while client_master.address() == None :
# print(" (re)try to connect OSC client ...")
# try:
# client_master.connect((mip, mport))
# print("SUCCESS ")
# except Exception as inst:
# print("FAILURE : ")
# print(inst)
# time.sleep(1)
# client_master.close()
print(" ===== MY IP IS ====")
print(get_ip())
# MAIN LOOP
global runningApp
runningApp = True
print(" ===== STARTING MAIN LOOP ====")
while runningApp:
# This is the main loop
# Do something here
if(flagToPlayMain):
print("Flag to play main open")
vid.playMain()
sendToMaster("status", vid.state)
if(flagToPlayWait):
print("Flag to play wait open")
if(vid.state == vid.PLAYINGMAIN):
vid.stop()
if(vid.state == vid.PLAYINGMAIN or vid.state == vid.WAITING ):
vid.playSec()
sendToMaster("status", vid.state)
if(flagToStop):
print("Flag to play stop open")
vid.stopAll()
if(vid.state == vid.ASKPLAYINGMAIN):
vid.playMain()
sendToMaster("status", vid.state)
if(vid.state == vid.ASKPLAYINGSECOND):
vid.playSec()
sendToMaster("status", vid.state)
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")
vid.stopAll()
# CLOSING THREAD AND SERVER
print(" Ending programme")
server.running = False
print(" Join thread")
st.join()
print(" Close Server")
server.close()
print(" End of sript . Bye Bye")
if __name__ == "__main__":
main()