forked from shane-mason/FieldStation42
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfield_player.py
More file actions
261 lines (211 loc) · 8.37 KB
/
Copy pathfield_player.py
File metadata and controls
261 lines (211 loc) · 8.37 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
import argparse
import time
import datetime
import json
import signal
import logging
from fs42.station_manager import StationManager
from fs42.timings import MIN_1, DAYS
from fs42.station_player import (
StationPlayer,
PlayStatus,
check_channel_socket,
update_status_socket,
)
from fs42.reception import ReceptionStatus
logging.basicConfig(
format="%(asctime)s %(levelname)s:%(name)s:%(message)s", level=logging.INFO
)
debounce_fragment = 0.1
def main_loop(transition_fn):
manager = StationManager()
reception = ReceptionStatus()
logger = logging.getLogger("MainLoop")
logger.info("Starting main loop")
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
channel_index = 0
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
player = StationPlayer(manager.stations[channel_index])
reception.degrade()
player.update_filters()
def sigint_handler(sig, frame):
logger.critical("Received sig-int signal, attempting to exit gracefully...")
player.shutdown()
update_status_socket("stopped", "", -1)
logger.info("Shutdown completed as expected - exiting application")
exit(0)
signal.signal(signal.SIGINT, sigint_handler)
channel_conf = manager.stations[channel_index]
# this is actually the main loop
outcome = None
skip_play = False
stuck_timer = 0
while True:
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")
outcome = player.show_guide(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} "
)
outcome = player.play_slot(
channel_conf["network_name"], datetime.datetime.now()
)
logger.debug(f"Got player outcome:{outcome.status}")
# reset skip
skip_play = False
if outcome.status == PlayStatus.CHANNEL_CHANGE:
stuck_timer = 0
tune_up = True
# get the json payload
if outcome.payload:
try:
as_obj = json.loads(outcome.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")
channel_index -= 1
if channel_index < 0:
channel_index = len(manager.stations) - 1
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")
channel_index += 1
if channel_index >= len(manager.stations):
channel_index = 0
channel_conf = manager.stations[channel_index]
player.station_config = channel_conf
# long_change_effect(player, reception)
transition_fn(player, reception)
elif outcome.status == PlayStatus.FAILED:
stuck_timer += 1
# only put it up once after 2 seconds of being stuck
if stuck_timer == 2 and "standby_image" in channel_conf:
player.play_file(channel_conf["standby_image"])
current_title_on_stuck = player.get_current_title()
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_outcome = check_channel_socket()
if new_outcome is not None:
outcome = new_outcome
# set skip play so outcome isn't overwritten
# and the channel change can be processed next loop
skip_play = True
elif outcome.status == PlayStatus.SUCCESS:
stuck_timer = 0
else:
stuck_timer = 0
def none_change_effect(player, reception):
pass
def short_change_effect(player, reception):
prev = reception.improve_amount
reception.improve_amount = 0
while not reception.is_degraded():
reception.degrade(0.2)
player.update_filters()
time.sleep(debounce_fragment)
reception.improve_amount = prev
def long_change_effect(player, reception):
# add noise to current channel
while not reception.is_degraded():
reception.degrade()
player.update_filters()
time.sleep(debounce_fragment)
# reception.improve(1)
player.play_file("runtime/static.mp4")
while not reception.is_perfect():
reception.improve()
player.update_filters()
time.sleep(debounce_fragment)
# time.sleep(1)
while not reception.is_degraded():
reception.degrade()
player.update_filters()
time.sleep(debounce_fragment)
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",
)
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
main_loop(trans_fn)