-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathspksel.py
executable file
·199 lines (153 loc) · 5.35 KB
/
spksel.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
#!/usr/bin/env python
# Webapp server for speaker selector/audio control
#
# Copyright (C) 2013-2014 David Liu (http://iceboundflame.com)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from __future__ import print_function
import flask
import json
import subprocess
import os
import re
import sys
import time
from pianobar_control import PianoBar
SOURCES = {'Cd': 'PhilipsHiFi Cd',
'Tuner': 'PhilipsHiFi Tuner',
'Usb': 'PhilipsHiFiUsb Usb',
'AirPlay': 'PhilipsHiFi Aux',
'Pandora': 'PhilipsHiFi Aux',
'Ipod': 'PhilipsHiFi Ipod'}
NUM_ROOMS = 5
STATE_FILE = './state.dat'
DEFAULT_STATE = dict(switches=[False]*NUM_ROOMS, source='Cd')
ENABLE_EXEC = True
SWITCH_EXEC = ['sudo', './control.py']
IR_EXEC = ['irsend', 'SEND_ONCE']
app = flask.Flask(__name__)
app.jinja_env.add_extension('pyjade.ext.jinja.PyJadeExtension')
app.config['PROPAGATE_EXCEPTIONS'] = True
pianobar = None
def do_exec(command):
print("Exec:", command)
if ENABLE_EXEC:
try:
subprocess.check_output(command, stderr=subprocess.STDOUT)
except Exception as e:
print("Error calling", command, ":\n", e, file=sys.stderr)
@app.route('/')
def index():
state = load_state()
add_pandora_status(state)
return flask.render_template('index.jade', state=json.dumps(state))
@app.route('/state')
def state():
state = load_state()
add_pandora_status(state)
return flask.jsonify(state)
@app.route('/switches', methods=['GET','POST'])
def switches():
room = int(flask.request.values.get('room'))
val = flask.request.values.get('val') == '1'
assert 0 <= room < NUM_ROOMS
print("Setting switch", room, val)
state = load_state()
state['switches'][room] = val
save_state(state)
set_switches(state['switches'])
add_pandora_status(state)
return flask.jsonify(state)
@app.route('/ir', methods=['GET','POST'])
def ir():
ir = flask.request.values.get('ir')
assert re.match(r'^[A-Za-z0-9 ]+$', ir)
do_exec(IR_EXEC + ir.split())
state = load_state()
add_pandora_status(state)
return flask.jsonify(state)
@app.route('/source', methods=['GET','POST'])
def source():
source = flask.request.values.get('source')
assert source in SOURCES
do_exec(IR_EXEC + SOURCES[source].split())
global pianobar
if source == 'Pandora':
if pianobar and pianobar.is_running():
pianobar.play()
else:
restart_pianobar()
else:
if pianobar and pianobar.is_running():
pianobar.pause()
state = load_state()
state['source'] = source
save_state(state)
add_pandora_status(state)
return flask.jsonify(state)
@app.route('/pandora', methods=['GET','POST'])
def pandora():
cmd = flask.request.values.get('cmd')
if cmd:
if cmd in {'play', 'pause', 'skip', 'love', 'ban', 'tired'}:
getattr(pianobar, cmd)()
elif cmd in {'select_station'}:
getattr(pianobar, cmd)(flask.request.values.get('arg'))
time.sleep(1) # allow status file to be updated.
elif cmd == 'restart':
restart_pianobar()
else:
raise ValueError("Unknown command")
state = load_state()
add_pandora_status(state)
return flask.jsonify(state)
# Not really concurrency safe, but only one or two users will ever really use
# this at a time.
def load_state():
state = DEFAULT_STATE
try:
with open(STATE_FILE, 'r') as f:
state = json.load(f)
assert len(state['switches']) == NUM_ROOMS
assert state['source'] in SOURCES
except Exception as e:
print("Error loading persisted state", file=sys.stderr)
state = DEFAULT_STATE
return state
def save_state(state):
with open(STATE_FILE, 'w') as f:
json.dump(state, f)
def set_switches(switches):
on_rooms = filter(lambda x: switches[x], range(len(switches)))
do_exec(SWITCH_EXEC + map(str, on_rooms))
def add_pandora_status(state):
global pianobar
if pianobar and pianobar.is_running():
state['pandora'] = pianobar.status()
def restart_pianobar():
global pianobar
if pianobar and pianobar.is_running():
pianobar.quit()
pianobar = PianoBar()
pianobar.run()
if __name__ == '__main__':
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--no_exec', help='disable execution of control commands (for testing)', action='store_true')
parser.add_argument('--bind', help='IP to listen on', default='127.0.0.1')
parser.add_argument('--port', help='port to listen on', default=5000)
parser.add_argument('--debug', help='debug mode', default=True)
args = parser.parse_args()
ENABLE_EXEC = not args.no_exec
app.run(debug=args.debug, host=args.bind, port=args.port)