-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstate.py
242 lines (200 loc) · 7.42 KB
/
state.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
import logging
import csv
import copy
import threading
import datetime
import subprocess
import os
import re
class Revision:
def __init__(self):
self.revision = Revision.timestamp()
@staticmethod
def timestamp():
return int((datetime.datetime.utcnow() - datetime.datetime(2013,1,1)).total_seconds()*1000)
def as_model(self):
return dict(revision = self.revision)
class RevisionLock(Revision):
def __init__(self):
Revision.__init__(self)
self.lock = threading.RLock()
self.waiters = set()
def wait_for_update(self, revision, callback):
self.lock.acquire()
try:
if long(revision) < self.revision:
callback(self.as_model())
return True
else:
self.waiters.add(callback)
return False
finally:
self.lock.release()
def cancel_wait(self, callback):
self.lock.acquire()
try:
if callback in self.waiters:
self.waiters.remove(callback)
return True
else:
return False
finally:
self.lock.release()
def update_revision(self, revision = None):
self.lock.acquire()
try:
if revision == None or revision <= self.revision:
self.revision = self.revision + 1
else:
self.revision = revision
#super(Revision, self).update_revision()
model = self.as_model()
waiters = self.waiters
self.waiters = set()
except:
print "Unexpected error:", sys.exc_info()[0]
raise
finally:
self.lock.release()
for callback in waiters:
try:
callback(model)
except:
logging.error("Error in waiter callback", exc_info=True)
class Radio:
def __init__(self, id, display_name, stream_url):
self.id = id
self.display_name = display_name
self.stream_url = stream_url
def as_model(self):
return self.__dict__
class Favorites(RevisionLock):
def __init__(self):
RevisionLock.__init__(self)
self.radios = []
self.load_radios()
def load_radios(self):
path = os.path.dirname(os.path.realpath(__file__))
with open(path + '/favorites.csv', 'rb') as csvfile:
radioreader = csv.reader(csvfile, delimiter=';', quotechar='\"')
for row in radioreader:
self.radios.append(Radio(row[0], row[1], row[2]))
def save_radios(self):
path = os.path.dirname(os.path.realpath(__file__))
with open(path + '/favorites.csv', 'wb') as csvfile:
radiowriter = csv.writer(csvfile, delimiter=';', quotechar='\"')
for radio in self.radios:
radiowriter.writerow([radio.id, radio.display_name, radio.stream_url])
def get_favorite(self, id):
self.lock.acquire()
try:
for radio in self.radios:
if(str(radio.id) == str(id)):
return copy.deepcopy(radio)
return None
finally:
self.lock.release()
def add_favorite(self, radio):
self.lock.acquire()
try:
self.radios.append(radio)
self.save_radios()
self.update_revision()
finally:
self.lock.release()
def as_model(self):
self.lock.acquire()
try:
result = Revision.as_model(self)
result['radios'] = copy.deepcopy(self.radios)
return result
finally:
self.lock.release()
class Title:
def __init__(self, title):
self.timestamp = datetime.datetime.now().strftime("%H:%M:%S")
self.title = title
class PlayerState(RevisionLock) :
def __init__(self):
RevisionLock.__init__(self)
self.radio = None
self.playlist = []
def set_radio(self, radio):
self.lock.acquire()
try:
self.radio = radio # set radio
del self.playlist[:] # delete playlist
self.update_revision()
except:
print "Unexpected error:", sys.exc_info()[0]
raise
finally:
self.lock.release()
def add_title(self, title):
self.lock.acquire()
try:
if len(self.playlist) == 0 or self.playlist[0].title != title:
self.playlist.insert(0, Title(title))
while len(self.playlist) > 5:
del self.playlist[len(self.playlist) - 1]
self.update_revision()
finally:
self.lock.release()
def as_model(self):
self.lock.acquire()
try:
result = Revision.as_model(self)
result['radio'] = copy.deepcopy(self.radio)
result['playlist'] = copy.deepcopy(self.playlist)
return result;
finally:
self.lock.release()
class MixerState(RevisionLock):
def __init__(self):
RevisionLock.__init__(self)
self.name, self.volume = self.get_volume()
def get_volume(self):
p = subprocess.Popen(['amixer'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
name = ""
volume = ""
while(True):
#retcode = p.poll() #returns None while subprocess is running
line = p.stdout.readline()
if line == None or line == "":
break
if name == "" and line.find("Simple mixer control") != -1:
name = re.search("('[^']+')",line).group(1)
elif volume == "" and line.find("Front Left:") != -1:
volume = re.search('\[([0-9]+)%\]',line).group(1)
if name == "":
name = "Headphone"
print 'Name: ' + name + ', Volume: ' + volume
return name, int(volume)
def set_volume(self, revision, volume):
self.lock.acquire()
try:
if revision <= self.revision:
return;
if self.volume != volume:
subprocess.call(['amixer', 'set', self.name, '--', str(volume) + '%']) #USER CALL
subprocess.call(['sudo', 'alsactl', 'store']) #ROOT CALL
#subprocess.call(['amixer', 'cset', 'numid=3', '--', volume])
self.volume = self.get_volume();
self.update_revision(long(revision))
finally:
self.lock.release()
def as_model(self):
self.lock.acquire()
try:
result = Revision.as_model(self)
result['volume'] = copy.deepcopy(self.volume)
return result;
finally:
self.lock.release()
class StateContainer:
def __init__(self):
self.currentPlayer = None
self.player_state = PlayerState()
self.favorites = Favorites()
self.mixer_state = MixerState();
state = StateContainer()