This repository has been archived by the owner on Jan 14, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathchromeline.py
96 lines (68 loc) · 2.52 KB
/
chromeline.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
"""Cast a Pi line in to a Chromecast."""
import ConfigParser
import os
import signal
import subprocess
import time
import pychromecast
def get_chromecast(uuid):
"""Return the target Chromecast, or None."""
try:
return [chromecast
for chromecast
in pychromecast.get_chromecasts()
if str(chromecast.device.uuid) == uuid][0]
except IndexError:
pass
def enable_stream(audio_device, password):
"""Start the stream, restart it on error."""
cmd = ['./push_to_icecast.sh', audio_device, password]
return subprocess.Popen(cmd, preexec_fn=os.setsid)
def cast_stream(chromecast, stream_source_ip, mount='chromeline.ogg'):
"""Tell the Chromecast about the stream."""
url = 'http://{}:8000/{}'.format(stream_source_ip, mount)
chromecast.media_controller.play_media(url, 'audio/ogg')
def load_config():
"""Load the configuration file."""
config = ConfigParser.ConfigParser()
config.read('config.ini')
return dict(config.items('chromeline'))
def enable_pulseaudio():
"""This is dumb, but needs to be done."""
subprocess.call(['pulseaudio', '-D'])
def chromecast_still_connected(chromecast):
"""Seems to be the bulletproof way to work this out."""
return not chromecast.socket_client.heartbeat_controller.is_expired()
def chromeline(chromecast_uuid, stream_source_ip, line_in_device, icecast_password):
"""Connect it all up."""
chromecast = None
while chromecast is None:
print 'Searching for Chromecast...'
time.sleep(5)
chromecast = get_chromecast(chromecast_uuid)
print 'Mounting internal stream in Icecast...'
process = enable_stream(line_in_device, icecast_password)
time.sleep(5)
print 'Casting external stream to Chromecast...'
cast_stream(chromecast, stream_source_ip)
print 'Running...'
return chromecast, process
def main():
"""Main loop."""
enable_pulseaudio()
while True:
conf = load_config()
chromecast, process = chromeline(**conf)
while True:
time.sleep(5)
if not chromecast_still_connected(chromecast):
print 'Stopping internal stream due to Chromecast disconnect!'
os.killpg(os.getpgid(process.pid), signal.SIGTERM)
process.kill()
break
if process.poll() is not None:
print 'Restarting due to internal stream failing!'
break
time.sleep(5)
if __name__ == '__main__':
main()