/
Sloshbox.py
executable file
·621 lines (505 loc) · 19.3 KB
/
Sloshbox.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
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
#!/usr/bin/env python
# USES:
# Adafruit ADXL345 Triple-Axis Accelerometer - ADXL345 : https://github.com/pimoroni/adxl345
# Fadecandy 8x8 board
# Open Pixel Control
from __future__ import division
# adxl345 library can't import smbus unless in a Linux environment
# this flag tells the code to fake accelerometer data.
# look for it and uncomment appropriate lines when deploying to RPI
RUNNINGONRPI = True
import time
import sys
import optparse
import random
import opc, color_utils
import pytweening
import switch_case
import math
if RUNNINGONRPI:
import adxl345
print
try:
import json
except ImportError:
import simplejson as json
#-------------------------------------------------------------------------------
# Visualization Tweak Values!
default_fps = 60
timeScale = 0.6
drainAmount = 0.1
# amount to drain from each array square per tick.
wave_spawn_period = 0.1
g_tolerance = 4
color_white = (255,255,255)
color_01 = (60, 43, 212) # 3C2BD4, primary wedding color
color_02 = (39,28,138)
color_03 = (25,18,90)
color_04 = (12,9,43)
color_black = (0,0,0)
waveIndex = 0
accel_wobble = True
wobble_speed = 0.1
# Maximum magnitude = min speed, and vice versa
updateSpeed_min = 0.1
updateSpeed_max = 1
# threshold from flat at which roll/pitch changes are ignored (i.e. rest state)
roll_threshold = 0.0015
pitch_threshold = 0.0015
# increment by which angle must change from previous amount to generate a new wave (in radians)
waveAngleIncrement = 0.0015
class Wave(object):
"""
Define a wave
# 8x base wave directions.
# LTR, RTL, TTB, BTT UL_DR, UR_DL, DL_UR, DR_UL
"""
def __init__(self, wave_type = "LTR", speed = 1.0):
self.name = "Wave-" + str(waveIndex)
self.wave_type = "<UNKNOWN>"
self.SetWaveType(wave_type, True)
self.speed = speed
self.update_period = self.CalcUpdatePeriod(self.speed);
self.delete_flag = False
self.createdAt = time.time()
self.last_update = self.createdAt #immediate
def update(self):
"""
:return:
"""
self.x1 += self.x_velocity
self.x2 += self.x_velocity
self.y1 += self.y_velocity
self.y2 += self.y_velocity
self.CheckWaveConstraints()
def CheckWaveConstraints(self):
if self.x1 > LED_xsize and self.x2 > LED_xsize:
self.delete_flag = True
if self.x1 < 0 and self.x2 < 0:
self.delete_flag = True
if self.y1 > LED_ysize and self.y2 > LED_ysize:
self.delete_flag = True
if self.y1 < 0 and self.y2 < 0:
self.delete_flag = True
def SetWaveType(self, toset = "LTR", resetcoords = False):
for case in switch_case.switch(toset):
if case("LTR"):
# wave traveling Left to Right
self.wave_type = toset
if resetcoords:
self.x1 = -1
self.y1 = -1
self.x2 = -1
self.y2 = LED_ysize
self.x_velocity = 1.0
self.y_velocity = 0.0
break
if case("RTL"):
# wave traveling Right to Left
self.wave_type = toset
if resetcoords:
self.x1 = LED_xsize
self.y1 = -1
self.x2 = LED_xsize
self.y2 = LED_ysize
self.x_velocity = -1.0
self.y_velocity = 0.0
break
if case("TTB"):
# wave traveling Top to Bottom
self.wave_type = toset
if resetcoords:
self.x1 = -1
self.y1 = -1
self.x2 = LED_xsize
self.y2 = -1
self.x_velocity = 0.0
self.y_velocity = 1.0
break
if case("BTT"):
# wave traveling Bottom to Top
self.wave_type = toset
if resetcoords:
self.x1 = -1
self.y1 = LED_ysize
self.x2 = LED_xsize
self.y2 = LED_ysize
self.x_velocity = 0.0
self.y_velocity = -1.0
break
if case():
self.wave_type = "<unknown>"
if resetcoords:
self.x1 = -1
self.y1 = -1
self.x2 = -1
self.y2 = LED_ysize
self.x_velocity = 1.0
self.y_velocity = 0.0
break
def TimerUpdate(self):
# if wave timer is reached, check accelerometer and spawn a new wave.
if ((time.time() - self.last_update) >= self.update_period):
self.last_update = time.time()
self.update()
def CalcUpdatePeriod(self, speed):
"""
# returns an update period for this wave based on speed
# speed is based on magnitude at time of spawn / max magnitude
# speed = 1.0 is fastest. speed = 0.0 is slowest
"""
speed = clamp(0,speed,1.0)
self.update_period = (updateSpeed_max - (pytweening.linear(speed) * (updateSpeed_max-updateSpeed_min)))
# ------------
# Make 1-2 waves depending on current axes accelerometer sample!
def align(axes, rollWave, pitchWave):
"""
:param axes: x,y,z of current sampled accelerometer axis
:return:
"""
x = axes['x']
y = axes['y']
z = axes['z']
retWaves = []
# http://stackoverflow.com/questions/3755059/3d-accelerometer-calculate-the-orientation
# math.atan2(y, x) The result is between -pi and pi.
# NOTE: formerly switch pitch and roll! Our sensor was wired... strangely.
Pitch = math.atan2(y, z * 180/math.pi)
Roll = math.atan2(-x, math.sqrt(y * y + z * z) * 180/math.pi)
Magnitude = GetMagnitude(axes)
MaxMagnitude = GetMagnitude({"x":g_tolerance, "y":g_tolerance, "z":g_tolerance})
print "Roll: ", Roll
print "Pitch: ", Pitch
print "Magnitude: ", Magnitude
print "MaxMagnitude", MaxMagnitude
# now calculate which wave type this should be.
if not (-roll_threshold <= Roll <= roll_threshold):
if not ((rollWave - waveAngleIncrement) <= Roll <= (rollWave + waveAngleIncrement)):
rollWave = Roll
if (0 <= Roll <= math.pi):
retWaves.append(Wave("TTB", Magnitude / MaxMagnitude))
elif (-math.pi <= Roll <= 0):
retWaves.append(Wave("BTT", Magnitude / MaxMagnitude))
if not (-pitch_threshold <= Pitch <= pitch_threshold):
if not ((pitchWave - waveAngleIncrement) <= Pitch <= (pitchWave + waveAngleIncrement)):
pitchWave = Pitch
if (0 <= Pitch <= math.pi):
retWaves.append(Wave("RTL", Magnitude / MaxMagnitude))
elif (-math.pi <= Pitch <= 0):
retWaves.append(Wave("LTR", Magnitude / MaxMagnitude))
stuffarray = [retWaves, rollWave, pitchWave]
print "Stuff:", stuffarray
return stuffarray
#-------------------------------------------------------------------------------
# command line
default_layout = "layouts/fadecandy8x8x2.json"
if RUNNINGONRPI:
default_server = "localhost:7890"
else:
default_server = "localhost:7890"
# default_server = "192.168.0.118:7890"
#-------------------------------------------------------------------------------
# command line
# currently used only to determine if gamma ramping is needed in pixel_color()
live = False
channel = 0 # default fadecandy channel 0
parser = optparse.OptionParser()
parser.add_option('-l', '--layout', dest='layout', default=default_layout,
action='store', type='string',
help='layout file')
parser.add_option('-s', '--server', dest='server', default=default_server,
action='store', type='string',
help='ip and port of server')
parser.add_option('-f', '--fps', dest='fps', default=default_fps,
action='store', type='int',
help='frames per second')
options, args = parser.parse_args()
if not options.layout:
parser.print_help()
print
print 'ERROR: you must specify a layout file using --layout'
print
sys.exit(1)
#-------------------------------------------------------------------------------
# parse layout file
print
print ' parsing layout file'
print
# array representing virtual pixels
coordinates = []
for item in json.load(open(options.layout)):
if 'point' in item:
coordinates.append(tuple(item['point']))
# use layout "fadecandy8x8.json"
# Fadecandy 8x8 board
LED_xsize = 16
LED_ysize = 8
numLEDs = LED_xsize * LED_ysize
black = [ (0,0,0) ] * numLEDs
white = [ (255,255,255) ] * numLEDs
# The normalArray is a list of floats from 0.0 -> 1.0 that indicates relative pixel 'fullness'
# this array gets translated to the PixelArray for passing to the OPC client.
normalArray = [[0.0 for x in range(LED_xsize)] for y in range(LED_ysize)]
#-------------------------------------------------------------------------------
# connect to server
client = opc.Client(options.server)
if client.can_connect():
print ' connected to %s' % options.server
else:
# can't connect, but keep running in case the server appears later
print ' WARNING: could not connect to %s' % options.server
#-------------------------------------------------------------------------------
# initialize accelerometer
if RUNNINGONRPI:
# uncomment this when running on the RPI - can't use smbus
accelerometer = adxl345.ADXL345()
print
#-------------------------------------------------------------------------------
# color function
def pixel_color(t, coord, ii):
"""Compute the color of a given pixel.
t: time in seconds since the program started.
ii: which pixel this is, starting at 0
coord: the (x, y, z) position of the pixel as a tuple
Returns an (r, g, b) tuple in the range 0-255
"""
x, y, z = coord
# make x, y, z -> r, g, b sine waves
r = color_utils.cos(x, offset=t / 4, period=2, minn=0, maxx=1)
g = color_utils.cos(y, offset=t / 4, period=2, minn=0, maxx=1)
b = color_utils.cos(z, offset=t / 4, period=2, minn=0, maxx=1)
# apply gamma curve
# only do this on live leds, not in the simulator
if live:
r, g, b = color_utils.gamma((r, g, b), 2.2)
return (r*256, g*256, b*256)
#-------------------------------------------------------------------------------
# Drain the normals of each element in handleArray by amount, clamp to 0
def drainNormals(amount):
# Now find its dimensions
rows = len(normalArray)
cols = len(normalArray[0])
# loop over every element
for row in range(rows):
for col in range(cols):
tmp = normalArray[row][col] - amount
if tmp < 0:
tmp = 0
normalArray[row][col] = tmp
#-------------------------------------------------------------------------------
# Make a pixel array from coordinate set
def make_pixelarray(coordinates, t):
pixel_array = [pixel_color(t * timeScale, coord, ii) for ii, coord in enumerate(coordinates)]
return pixel_array
FadeCandyList = []
nextFadeCandyID = 0
class FadeCandy(object):
"""
Define a single Fadecandy board virtual object for mapping from pixelarray.
"""
def __init__(self, x=0, y=0, id=0):
self.ID = id
self.x = x
self.y = y
self.xsize = 8
self.ysize = 8
self.array = [[0 for y in range(self.ysize)] for x in range(self.xsize)]
def Map(self, targetArray):
"""
copies pixels from the targetArray into self array
:param targetArray:
:return:
"""
# print "Map: ({0}, {1}) -> {2}, {3}".format(len(targetArray), len(targetArray[0]), self.x, self.y)
for ii in range(self.ysize):
#row
for jj in range(self.xsize):
#col
# print "Mapping: target({0},{1})={2} -> self({3},{4})".format(self.y+ii, self.x+jj, targetArray[self.y+ii][self.x+jj], ii, jj)
if ((self.y + ii) < len(targetArray)):
if ((self.x + jj) < len(targetArray[0])):
self.array[ii][jj] = targetArray[(self.y + ii)][(self.x + jj)]
else:
# mapped coordinates are outside targetarray
self.array[ii][jj] = color_white
else:
# mapped coordinates are outside targetarray
self.array[ii][jj] = color_white
def serialize(self):
retlist = []
for i in range(len(self.array)):
for j in range(len(self.array[i])):
retlist.append(self.array[i][j])
return retlist
FadeCandyList = []
nextFadeCandyID = 0
FadeCandyList.append(FadeCandy(0,0, nextFadeCandyID))
nextFadeCandyID += 1
FadeCandyList.append(FadeCandy(8,0, nextFadeCandyID))
#-------------------------------------------------------------------------------
# Make a pixel array from normals, corresponding to coordinate set
def convert2dListToPixels(passArray):
# print "Converting: passArray[{0}][{1}]".format(LED_ysize, LED_xsize)
# copy passed array for returning values.
retArray = [[(0,0,0) for x in range(LED_xsize)] for y in range(LED_ysize)]
# print "RetArray:", retArray
# iterate over each element in passArray, convert its value to pixel color and store in retArray
for row in range(len(passArray)):
for column in range(len(passArray[row])):
tmp = convertNormalToPixel(passArray[row][column])
retArray[row][column] = tmp
return retArray
#-------------------------------------------------------------------------------
# Make a pixel array from normals, corresponding to coordinate set
def make_pixelarray_from_normals(coordinates):
# convert our list of normal values into an equivalent list of pixel colors
pixel_array = convert2dListToPixels(normalArray)
serialized_array = []
# map our fadecandy boards to the pixel array
for fc in FadeCandyList:
fc.Map(pixel_array)
for pixel in fc.serialize():
serialized_array.append(pixel)
# print "SA len(%i)=" % len(serialized_array), serialized_array
return serialized_array
#-------------------------------------------------------------------------------
# For each point in a line, set corresponding point in normalArray to 1.0
def applyNormalPoints(line):
for point in line:
x = point[0]
y = point[1]
x = clamp(0,x,LED_xsize-1)
y = clamp(0,y,LED_ysize-1)
x = int(x)
y = int(y)
normalArray[y][x] = 1.0
#-------------------------------------------------------------------------------
# Convert a normal value to a pixel color
def convertNormalToPixel(norm):
rgb = [0,0,0]
if norm == 1.0:
rgb = color_white
elif norm > 0.8:
rgb = color_01
elif norm > 0.6:
rgb = color_02
elif norm > 0.4:
rgb = color_03
elif norm > 0.2:
rgb = color_04
else:
rgb = color_black
return rgb
def getNormalFor(coord):
x,y,z = coord
norm = normalArray[y][x]
return norm
#-------------------------------------------------------------------------------
# Make an array of random pixels
def make_pixels_random(n_pixels):
pixels = []
for ii in range(n_pixels):
pixels.append(randomColor())
return pixels
def randomColor():
rgb = [random.random()*255, random.random()*255, random.random()*255]
rgb = tuple(rgb)
return rgb
#-------------------------------------------------------------------------------
# Merely PRETEND to sample accelerometer and return XYZ values
def sample_accel_FAKE(prev_accel):
if accel_wobble == True:
x = clamp(-12, prev_accel['x']+random.uniform(-0.5,0.5), 12)
y = clamp(-12, prev_accel['y']+random.uniform(-0.5,0.5), 12)
z = clamp(-12, prev_accel['z']+random.uniform(-0.5,0.5), 12)
else:
x = clamp(-12, prev_accel['x'] + wobble_speed*2, 12)
y = clamp(-12, prev_accel['y'] + wobble_speed, 12)
z = clamp(-12, prev_accel['z'] + wobble_speed, 12)
accel_xyz = {"x": x,"y": y, "z": z}
return accel_xyz
def clamp(minimum, x, maximum):
return max(minimum, min(x, maximum))
#-------------------------------------------------------------------------------
# Sample accelerometer and return XYZ values
def sample_accel():
accel_axes = {"x": 0, "y": 0, "z": 0}
if RUNNINGONRPI:
axes = accelerometer.getAxes(True)
print "ADXL345 on address 0x%x:" % (accelerometer.address)
print " x = %.3fG" % ( axes['x'] )
print " y = %.3fG" % ( axes['y'] )
print " z = %.3fG" % ( axes['z'] )
accel_axes = {"x": axes['x'],"y": axes['y'],"z": axes['z']}
print
else:
accel_axes = sample_accel_FAKE(accel_axes )
return accel_axes
def GetUnitVector(axes):
magnitude = GetMagnitude(axes)
unit_axes = {"x": axes['x'] / magnitude, "y": axes['y']/ magnitude, "z": axes['z'] / magnitude}
return unit_axes
def GetMagnitude(axes):
x = (axes['x'])
y = (axes['y'])
z = (axes['z'])
magnitude = math.sqrt(math.pow(x,2) + math.pow(y,2) + math.pow(z,2))
return magnitude
#-------------------------------------------------------------------------------
# core pixel loop
print ' sending pixels forever (control-c to exit)...'
print
#-------------------------------------------------------------------------------
# calculate relevant display data
n_pixels = len(coordinates)
start_time = time.time()
# number of seconds in which each wave spawns.
wave_spawn_timer = 0.0
LastWaveCreatedAt = start_time
waveList =[Wave()]
accel_axes = sample_accel_FAKE({"x": 0, "y": 0, "z": 0})
# last angle at which we generated a wave
lastPitchWave = 0
lastRollWave = 0
while True:
# update time since loop began
t = time.time() - start_time
# if wave timer is reached, check accelerometer and spawn a new wave.
wave_spawn_timer = time.time() - LastWaveCreatedAt
if wave_spawn_timer >= wave_spawn_period:
if RUNNINGONRPI:
accel_axes = sample_accel()
print
else:
accel_axes = sample_accel_FAKE(accel_axes)
stuff = []
new_Waves = []
stuff = align(accel_axes, lastRollWave, lastPitchWave)
print "RECV Stuff:", stuff
new_Waves = stuff[0]
lastRollWave = stuff[1]
lastPitchWave = stuff[2]
# ugly hack but it should work! :)
for newWave in new_Waves:
waveIndex += 1
waveList.append(newWave)
print 'New Wave(t={0:.4f}) Type: {1}'.format(newWave.createdAt, newWave.wave_type)
LastWaveCreatedAt = time.time()
wave_spawn_timer = 0.0
for wave in waveList:
wave.TimerUpdate()
if wave.delete_flag:
print "Removing Wave: %s" % wave.name
waveList.remove(wave)
# create the correct line.
line = pytweening.getLine(wave.x1, wave.y1, wave.x2, wave.y2)
applyNormalPoints(line)
# drain normal values
drainNormals(drainAmount)
# calculate pixel color values based on normalArray
pixels = make_pixelarray_from_normals(coordinates)
#pixels = make_pixels_random(numLEDs)
## Create pixel array and push to client.
# pixels = make_pixelarray(coordinates, t)
client.put_pixels(pixels, channel)
time.sleep(1 / options.fps)