-
-
Notifications
You must be signed in to change notification settings - Fork 131
Expand file tree
/
Copy pathfield_player.py
More file actions
400 lines (339 loc) · 14.5 KB
/
Copy pathfield_player.py
File metadata and controls
400 lines (339 loc) · 14.5 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
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
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
import multiprocessing
from queue import Empty
import argparse
import time
import datetime
import json
import shelve
import signal
import logging
from fs42.liquid_manager import LiquidManager
from fs42.station_manager import StationManager
from fs42.timings import MIN_1, DAYS
from fs42.station_player import (
StationPlayer,
PlayerState,
PlayerOutcome,
update_status_socket,
)
from fs42.reception import (
ReceptionStatus,
long_change_effect,
short_change_effect,
none_change_effect,
)
from fs42.live_schedule_agent import LiveScheduleAgent
logging.basicConfig(
format="%(asctime)s %(levelname)s:%(name)s:%(message)s", level=logging.INFO
)
try:
from fs42.overlay.ticker import run_ticker
except ModuleNotFoundError:
logging.getLogger("FieldPlayer").warning("Error importing ticker - using the ticker will cause an error.")
STATE_SHELVE = "runtime/player_state.bin"
api_commands_queue: multiprocessing.Queue = None
def input_check():
if api_commands_queue:
q_message = None
try:
q_message = api_commands_queue.get(block=False)
except Empty:
pass
if q_message:
command = q_message.get("command", None)
if not command:
return
match command:
case "exit":
return PlayerOutcome(PlayerState.EXIT_COMMAND)
case "reload_data":
LiquidManager().reload_schedules()
case "guide":
try:
c_number = StationManager().guide_config["channel_number"]
change_request = {"command": "direct", "channel": c_number}
return PlayerOutcome(PlayerState.CHANNEL_CHANGE, json.dumps(change_request))
except TypeError:
logging.getLogger("InputCheck").warning("Guide channel not configured")
case "ticker":
message = q_message.get("message", None)
header = q_message.get("header", None)
style = q_message.get("style", None)
iterations = q_message.get("iterations", None)
run_ticker(message, header, style, iterations)
case "play_file":
file_path = q_message.get("file_path", None)
return PlayerOutcome(PlayerState.PLAY_FILE, file_path)
case "web_key":
key = q_message.get("key", "")
return PlayerOutcome(PlayerState.SUCCESS, f"web_key:{key}")
case "parental_digit":
digit = str(q_message.get("digit", ""))
return PlayerOutcome(PlayerState.SUCCESS, f"parental_digit:{digit}")
case "parental_clear":
return PlayerOutcome(PlayerState.SUCCESS, "parental_clear")
channel_socket = StationManager().server_conf["channel_socket"]
with open(channel_socket, "r") as r_sock:
contents = r_sock.read()
if len(contents):
with open(channel_socket, "w"):
pass
return PlayerOutcome(PlayerState.CHANNEL_CHANGE, contents)
return None
def main_loop(transition_fn, shutdown_queue=None, api_proc=None, schedule_lock=None):
manager = StationManager()
reception = ReceptionStatus()
logger = logging.getLogger("MainLoop")
logger.info("Starting main loop")
# set up the live schedule agent if configured
schedule_agent = None
agent_conf = manager.server_conf.get("schedule_agent")
if agent_conf and schedule_lock:
schedule_agent = LiveScheduleAgent(agent_conf, schedule_lock)
logger.info("Live schedule agent is active")
else:
logger.info("Live schedule agent is not configured")
channel_socket = StationManager().server_conf["channel_socket"]
# go ahead and clear the channel socket (or create if it doesn't exist)
with open(channel_socket, "w"):
pass
if not len(manager.stations):
logger.error(
"Could not find any station runtimes - do you have your channels configured?"
)
logger.error(
"Check to make sure you have valid json configurations in the confs dir"
)
logger.error(
"The confs/examples folder contains working examples that you can build off of - just move one into confs/"
)
return
channel_index = 0
# if they specified a start channel, just use that
start_channel_config = StationManager().server_conf.get("start_channel", None)
if not start_channel_config:
use_saved = StationManager().server_conf.get("recall_last_channel", True)
if use_saved:
with shelve.open(STATE_SHELVE) as s:
channel_index = s.get("channel_index", 0)
else:
channel_index = manager.index_from_channel(start_channel_config)
if not channel_index:
logger.error(f"Start channel specified as {start_channel_config} in main_config.json, but station doesn't exist.")
logger.warning(f"Attempting fallback to the first channel")
channel_index = 0
if channel_index >= len(manager.stations):
logger.warning("Saved channel index %d is out of range, resetting to 0", channel_index)
channel_index = 0
player = StationPlayer(manager.stations[channel_index], input_check)
if schedule_lock:
player.schedule_lock = schedule_lock
stand_by = StationManager().server_conf.get("standby_image", "runtime/standby.png")
reception.degrade()
player.update_filters()
player.play_file(stand_by)
player.load_up()
def signal_handler(sig, frame):
logger.critical("Received sig-int signal, attempting to exit gracefully...")
player.shutdown()
update_status_socket("stopped", "", -1)
# Signal API server to shutdown if running
if shutdown_queue is not None:
shutdown_queue.put("shutdown")
if api_proc is not None:
api_proc.join(timeout=5)
logger.info("Shutdown completed as expected - exiting application")
exit(0)
signal.signal(signal.SIGINT, signal_handler)
signal.signal(signal.SIGTERM, signal_handler)
channel_conf = manager.stations[channel_index]
# this is actually the main loop
player_state = None
skip_play = False
stuck_timer = 0
while True:
if schedule_agent:
schedule_agent.tick()
logger.info(f"Playing station: {channel_conf['network_name']}")
if channel_conf["network_type"] == "guide" and not skip_play:
logger.info("Starting the guide channel")
player_state = player.show_guide(channel_conf)
elif channel_conf["network_type"] == "web" and not skip_play:
logger.info("Starting the web channel")
player_state = player.show_web(channel_conf)
elif not skip_play:
now = datetime.datetime.now()
week_day = DAYS[now.weekday()]
hour = now.hour
skip = now.minute * MIN_1 + now.second
logger.info(
f"Starting station {channel_conf['network_name']} at: {week_day} {hour} skipping={skip} "
)
player_state = player.play_slot(
channel_conf["network_name"], datetime.datetime.now()
)
logger.debug(f"Got player outcome:{player_state.status}")
# reset skip
skip_play = False
if player_state.status == PlayerState.CHANNEL_CHANGE:
stuck_timer = 0
# Cache stations to prevent race conditions during reload
station_cache = manager.stations
stations_len = len(station_cache)
#if we got anything, we'll tune up one channel
tune_up = True
# get the json payload
if player_state.payload:
try:
as_obj = json.loads(player_state.payload)
if "command" in as_obj:
if as_obj["command"] == "direct":
tune_up = False
if "channel" in as_obj:
logger.debug(
f"Got direct tune command for channel {as_obj['channel']}"
)
new_index = manager.index_from_channel(
as_obj["channel"]
)
if new_index is None:
logger.warning(
f"Got direct tune command but could not find station with channel {as_obj['channel']}"
)
else:
channel_index = new_index
else:
logger.critical(
"Got direct tune command, but no channel specified"
)
elif as_obj["command"] == "up":
tune_up = True
logger.debug("Got channel up command")
elif as_obj["command"] == "down":
tune_up = False
logger.debug("Got channel down command")
found = False
while not found:
channel_index -= 1
if channel_index < 0:
channel_index = stations_len-1
if not station_cache[channel_index]["hidden"]:
found = True
except Exception as e:
logger.exception(e)
logger.warning(
"Got payload on channel change, but JSON convert failed"
)
if tune_up:
logger.info("Starting channel change")
found = False
while not found:
channel_index += 1
channel_index = channel_index if channel_index < stations_len else 0
found = not station_cache[channel_index]["hidden"]
# save the player state
with shelve.open(STATE_SHELVE) as s:
s["channel_index"] = channel_index
channel_conf = station_cache[channel_index]
player.station_config = channel_conf
# long_change_effect(player, reception)
transition_fn(player, reception)
elif player_state.status == PlayerState.PLAY_FILE:
print("Got playfile!", player_state.payload )
skip_play = True
player_state = player.play_and_wait(player_state.payload)
elif player_state.status == PlayerState.FAILED:
stuck_timer += 1
# only put it up once after 2 seconds of being stuck
if stuck_timer == 2:
stand_by = channel_conf.get("standby_image", StationManager().server_conf.get("standby_image", "runtime/standby.png"))
player.play_file(stand_by)
current_title_on_stuck = player.get_current_path()
update_status_socket(
"stuck",
channel_conf["network_name"],
channel_conf["channel_number"],
current_title_on_stuck,
)
time.sleep(1)
logger.critical(
"Player failed to start - resting for 1 second and trying again"
)
# check for channel change so it doesn't stay stuck on a broken channel
new_state = input_check()
if new_state is not None:
player_state = new_state
# set skip play so outcome isn't overwritten
# and the channel change can be processed next loop
skip_play = True
elif player_state.status == PlayerState.SUCCESS:
stuck_timer = 0
elif player_state.status == PlayerState.EXIT_COMMAND:
signal_handler(None, None)
else:
stuck_timer = 0
def start_api_server_with_shutdown_queue(shutdown_queue, command_q):
from fs42.fs42_server import fs42_server
fs42_server.run_with_shutdown_queue(shutdown_queue, command_q)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="FieldStation42 Player")
parser.add_argument(
"-t",
"--transition",
choices=["long", "short", "none"],
help="Transition effect to use on channel change",
)
parser.add_argument(
"-l", "--logfile", help="Set logging to use output file - will append each run"
)
parser.add_argument(
"-v",
"--verbose",
action="store_true",
help="Set logging verbosity level to very chatty",
)
parser.add_argument(
"--no_server",
action="store_true",
help="Do not start the web API server process.",
)
args = parser.parse_args()
if args.verbose:
logging.getLogger().setLevel(logging.DEBUG)
if args.logfile:
formatter = logging.Formatter("%(asctime)s:%(levelname)s:%(name)s:%(message)s")
fh = logging.FileHandler(args.logfile)
fh.setFormatter(formatter)
logging.getLogger().addHandler(fh)
trans_fn = short_change_effect
if args.transition:
if args.transition == "long":
trans_fn = long_change_effect
elif args.transition == "none":
trans_fn = none_change_effect
# else keep short change as default
if not args.no_server:
# Set up shutdown queue and start API server as a background process
shutdown_queue = multiprocessing.Queue()
api_commands_queue = multiprocessing.Queue()
api_proc = multiprocessing.Process(
target=start_api_server_with_shutdown_queue,
args=(
shutdown_queue,
api_commands_queue,
),
daemon=True,
)
api_proc.start()
else:
shutdown_queue = None
api_commands_queue = None
api_proc = None
schedule_lock = multiprocessing.Lock()
try:
main_loop(trans_fn, shutdown_queue=shutdown_queue, api_proc=api_proc, schedule_lock=schedule_lock)
finally:
if shutdown_queue is not None:
shutdown_queue.put("shutdown")
if api_proc is not None:
api_proc.join(timeout=5)