-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsoundlight.py
282 lines (209 loc) · 7.65 KB
/
soundlight.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
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
# Python 2.7 code to analyze sound and interface with Arduino
'''
Sources
http://www.swharden.com/blog/2010-03-05-realtime-fft-graph-of-audio-wav-file-or-microphone-input-with-python-scipy-and-wckgraph/
http://macdevcenter.com/pub/a/python/2001/01/31/numerically.html?page=2
'''
import audioop
from flask import Flask, jsonify
from flask import request
import math
from multiprocessing import process
import serial # from http://pyserial.sourceforge.net/
import sys
from thread import start_new_thread
import time
import analyzer
from generator import *
from graph import Graph
from lmgraphics.pointgenerator import PointGenerator
from magiclamp import *
import multiprocessing as mp
try:
from ledrenderer import LEDRenderer
except:
pass
app = Flask(__name__)
graph = None
@app.route('/config')
def getConfig():
return jsonify({'generatorIndex' : config['generatorIndex'],
'brightness' : config['brightness'],
'active' : config['active']})
@app.route('/config', methods=['PUT'])
def setConfig():
if not request.json:
return "no request", 400
config['brightness'] = request.json['brightness']
config['active'] = request.json['active']
updateConfig();
return jsonify(request.json)
@app.route('/generatorConfig/')
@app.route('/generatorConfig/<int:generatorIndex>')
def getGeneratorConfig(generatorIndex=None):
if (generatorIndex == None):
result = {}
for generatorIndex in range(len(config['generators'])):
generator = config['generators'][generatorIndex]
generatorName = generator.config['name']
result[generatorName] = getGeneratorConfig(generatorIndex)
return jsonify(result)
else:
return jsonify(getGeneratorConfig(generatorIndex))
def getGeneratorConfig(generatorIndex):
generator = config['generators'][generatorIndex]
result = generator.config
result['hash'] = generator.getHash()
result['generatorIndex'] = generatorIndex
return result
@app.route('/generatorConfig/<int:generatorId>', methods=['PUT'])
def setGeneratorConfig(generatorId=None):
if not request.json:
return "no request", 400
config['generators'][generatorId].config = request.json
return jsonify(config['generators'][generatorId].config)
@app.route('/next')
def nextGenerator():
generators = config.get('generators')
generatorIndex = config.get('generatorIndex')
if (generatorIndex == len(generators) - 1):
generatorIndex = 0
else:
generatorIndex = generatorIndex + 1
print "setting generatorIndex to %s" % (generatorIndex)
config['generatorIndex'] = generatorIndex
return "true"
def updateConfig():
brightness = config['brightness']
print "setting brightness to %s" % (brightness)
for renderer in config['renderers']:
renderer.setBrightness(brightness)
if (config['active'] == False):
for pixel in config['canvas'].pixels:
pixel.color.r = 0
pixel.color.g = 0
pixel.color.b = 0
for renderer in config['renderers']:
renderer.update()
def initMLCanvas():
numLeds = 240
pixelPerRow = 14
incY = 1
incX = 15
pixels = []
x = 0
y = 0
maxX = 0
currentRowPixelCount = 0
for i in range(numLeds):
# todo: modulo
if currentRowPixelCount > pixelPerRow:
currentRowPixelCount = 0
x = 0
pix = MLPixel(x + incX / 2, y + incX / 2, MLColor(0, 0, 0))
y = y + incY
x = x + incX
if maxX < x:
maxX = x
currentRowPixelCount = currentRowPixelCount + 1
pixels.append(pix)
canvas = MLCanvas(maxX, y)
canvas.pixels = pixels
return canvas
def startAnalyzer():
global analyzerStat
analyzerStat = mp.Array('i', [0] * analyzer.LEVELS)
p = mp.Process(target=analyzer.start, args=([analyzerStat]))
p.start()
def start():
canvas = initMLCanvas()
config['canvas'] = canvas
# init Graph
renderers = config['renderers']
try:
renderers.append(LEDRenderer(canvas))
except:
pass
generators = []
# set up imageBasedGenerator
# generators.append(ImageBasedGenerator(canvas, [PointGenerator()], False))
generators.append(FloatingPointGenerator(canvas,
{
'name' : 'FloatingPointGenerator1',
'maxPoints' : 6,
'pixelPerRow' : 15,
'tailElementSpeedFactor' : 8,
'minSpeed' : 1,
'maxSpeed' : 10}))
generators.append(ImageBasedGenerator("bar.png", canvas, [RotatingGenerator(20), ZoomingGenerator(0.2, 1, 1.5)],
{
'name' : 'ImageBasedGenerator1',
'showPreview' : False}))
generators.append(LavaGenerator(canvas,
{
'name' : 'LavaGenerator1',
'color' : {'r' : 0, 'g' : 0, 'b' : 255}}))
generators.append(AnalyzerGenerator(canvas,
{
'name' : 'AnalyzerGenerator1',
'color' : {'r' : 0, 'g' : 0, 'b' : 255}}))
generators.append(RainbowGenerator(canvas,
{
'name' : 'RainbowGenerator1'
}))
config['generators'] = generators
graph = Graph(renderers, [generators[2], generators[0]])
updateConfig()
startAnalyzer()
print "Starting, use Ctrl+C to stop"
try:
while False:
line = []
graph.update(line)
# time.sleep(1)
lastTime = time.time()
iterations = 0
lastIndex = -1
while True:
try:
if (config['active'] == False):
time.sleep(1)
continue
# clear canvas if generator changes
if (lastIndex != config['generatorIndex']):
for pixel in config['canvas'].pixels:
color = pixel.color
color.r = 0
color.g = 0
color.b = 0
lastIndex = config['generatorIndex']
graph.generators = [generators[config['generatorIndex']]]
graph.update(analyzerStat)
now = time.time()
iterations += 1
# TODO: different process
time.sleep(0.003)
if (now - lastTime > 1):
print "%s fps" % (iterations)
# print ' '.join(map(str, analyzerStat))
iterations = 0
lastTime = now
except IOError:
print ":("
pass
except KeyboardInterrupt:
print "interrupt"
pass
finally:
print "\nStopping"
print sys.exc_info()
stream.close()
p.terminate()
if __name__ == '__main__':
config = {'generatorIndex' : 0, 'generators' : [],
'renderers' : [],
'brightness' : 50,
'active' : True}
# list_devices()
start_new_thread(start, ())
app.run(host='0.0.0.0', debug=False)