Repository navigation
Expand file tree
/
Copy pathmagicband.py
More file actions
371 lines (326 loc) · 11.1 KB
/
Copy pathmagicband.py
File metadata and controls
371 lines (326 loc) · 11.1 KB
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
#!/usr/bin/env python
from __future__ import print_function
import pygame
import argparse
import binascii
import logging
import hashlib
import struct
#import ndef
import hmac
import cli
import sys
import os
import time
import board
import neopixel
import time
import os.path
from os import path
import random
import configobj
from json import dumps
from httplib2 import Http
import urllib
import threading
import atexit
import RPi.GPIO as GPIO
import MFRC522
import signal
DEBUG = False
os.environ['PYGAME_HIDE_SUPPORT_PROMPT'] = "hide"
config = configobj.ConfigObj('settings.conf')
print_band_id = config['Settings']['print_band_id']
reverse_circle = config['Settings']['reverse_circle']
ring_pixels = int(config['Settings']['ring_pixels'])
mickey_pixels = int(config['Settings']['mickey_pixels'])
# Format is (R, G, B)
COLORS = {
"red": (255, 0, 0),
"electricred": (228, 3, 3),
"orange": (255, 165, 0),
"dark orange": (255, 140, 0),
"yellow": (255, 255, 0),
"canaryyellow": (255, 237, 0),
"green": (0, 255, 0),
"lasallegreen": (0, 128, 38),
"teal": (0, 128, 128),
"blue": (0, 0, 255),
"patriarch": (117, 7, 135),
"lightblue": (153, 204, 255),
"white": (255, 255, 255),
"purple": (0, 153, 153),
"gray": (128, 128, 128),
"pink": (255, 105, 180),
"stitch": (0, 39, 144),
"rainbow": (0, 0, 0),
"pride": (0, 0, 1),
}
sequences = config['sequences']
# GPIO Pin (Recommend GPIO18) GPIO13 is also a good choice
pixel_pin = board.D21
if sys.version_info.major < 3:
sys.exit("This script requires Python 3")
log = logging.getLogger('main')
log.setLevel(logging.CRITICAL)
# Pre init helps to get rid of sound lag
pygame.mixer.pre_init(44100, -16, 1, 512)
pygame.mixer.init()
pygame.init()
totalPixels = ring_pixels+mickey_pixels
currentBandId = ""
repeatCount = 0
repeatBandId = ""
repeatTime = time.time()
whiteIdleActive = True
pixels = neopixel.NeoPixel(pixel_pin, totalPixels, brightness=0.9, auto_write=False, pixel_order=neopixel.GRB)
# Capture SIGINT for cleanup when the script is aborted
def end_read(signal,frame):
if (DEBUG):
print ("Ctrl+C captured, ending read.")
GPIO.cleanup()
sys.exit()
def playLightSequence(magicBandScannedEvent, successEvent, ringPixels, totalPixels):
lightSpeed = .1
pixelRingArray = list(range(0, ringPixels-1))
if reverse_circle == 'True':
pixelRingArray.reverse()
global pixels
if (DEBUG):
print("Playing light sequence")
global whiteIdleActive
while True:
if (not whiteIdleActive) and (not magicBandScannedEvent.isSet()):
continue
if not magicBandScannedEvent.isSet():
lightSpeed = .1
else:
if lightSpeed == .1:
lightSpeed = lightSpeed * .50
else:
lightSpeed = lightSpeed * .95
if lightSpeed < 0.001:
successEvent.set()
if lightSpeed < 0.000001:
global currentBandId
sequence = getSequence(currentBandId)
runSuccess(magicBandScannedEvent, successEvent, sequence)
lightSpeed = .1
else:
leadingIndex = pixelRingArray[4]
trailingIndex = pixelRingArray[0]
color = COLORS['white']
if magicBandScannedEvent.isSet():
sequence = getSequence(currentBandId)
color = COLORS[sequence.get('color_ring')]
if color == COLORS['rainbow']:
rainbowCycle(1, 1)
successEvent.set()
runSuccess(magicBandScannedEvent, successEvent, sequence)
else:
pixels[leadingIndex] = fadePixel(False, pixels[leadingIndex], color)
pixels[trailingIndex] = fadePixel(True, pixels[trailingIndex], color)
pixels.show()
pixelRingArray = rotateArray(pixelRingArray)
time.sleep(lightSpeed)
def runSuccess(bandEvent, successEvent, sequence):
showAllColored(pixels, COLORS[sequence.get('color_mouse')])
time.sleep(int(sequence.get('hold_seconds')))
magicBandScannedEvent.clear()
successEvent.clear()
doLightFadeOff(pixels)
pixels.brightness = 0.9
def wheel(pos):
if pos < 85:
return (pos * 3, 255 - pos * 3, 0)
elif pos < 170:
pos -= 85
return (255 - pos * 3, 0, pos * 3)
else:
pos -= 170
return (0, pos * 3, 255 - pos * 3)
def rainbowCycle(wait, iterations):
for j in range(256 * iterations):
for i in range(ring_pixels):
pixels[i] = wheel((int(i * 256 / ring_pixels) + j) & 255)
pixels.show()
time.sleep(wait/1000)
def theaterChase(wait, iterations):
for j in range(256 * iterations):
for i in range(ring_pixels):
if (i + j) % 3 == 0:
pixels[i] = (255, 0, 0)
else:
pixels[i] = (0, 255, 0)
pixels.show()
time.sleep(wait/1000)
def doLightFadeOff(pixels):
brightness = 1.01
for x in range(100):
brightness = brightness - .01
pixels.brightness = brightness
pixels.show()
time.sleep(.0005)
doLightsOff(pixels)
def doLightsOff(pixels):
for i in range(totalPixels):
pixels[i] = 0
pixels.show()
def showAllColored(pixels, color):
for i in range(totalPixels):
pixels[i] = color
pixels.show()
def rotateArray(arr):
firstValue = arr.pop(0)
arr.append(firstValue)
return arr
def exit_handler():
doLightsOff(pixels)
def printArray(arr):
for i in range(len(arr)):
if (DEBUG):
print ("%d"% arr[i],end=" ")
def fadePixel(out, pixel, color):
if out:
return (0, 0, 0)
if not out:
return color
def getSequence(bandid):
sequences = config['bands'].get(str(bandid)) or config['bands']['unknown']
if sequences:
sequences = sequences if type(sequences) == list else [sequences,]
sequence = config['sequences'][random.choice(sequences)]
if (DEBUG):
print("getsequences = " + str(sequences))
return sequence
class MagicBand():
def __init__(self):
self.success = True
self.successSequence = []
class BandScannerAndSound():
def __init__(self, scannedEvent, successEvent):
if (DEBUG):
print("Scanning")
self.scannedEvent = scannedEvent
self.successEvent = successEvent
# Scan for cards
uid = [0,0,0,0,0]
bandid = 0
(status,TagType) = MIFAREReader.MFRC522_Request(MIFAREReader.PICC_REQIDL)
# If a card is found
if status == MIFAREReader.MI_OK:
(status,uid) = MIFAREReader.MFRC522_Anticoll()
if len(uid) == 5:
HexUID = format(int(uid[0]),'02X')
HexUID = HexUID + format(int(uid[1]),'02X')
HexUID = HexUID + format(int(uid[2]),'02X')
HexUID = HexUID + format(int(uid[3]),'02X')
bandid = int(HexUID,16)
if (DEBUG):
print("MagicBandId = " + str(bandid))
if self.scannedEvent.isSet():
return
if (bandid != 0):
global repeatBandId
global repeatTime
global repeatCount
if (repeatBandId == str(bandid)):
if (time.time()-repeatTime <60):
repeatCount = repeatCount + 1
if (time.time()-repeatTime >=60):
repeatTime = time.time()
repeatCount = 1
if (repeatCount == 3):
print ("Still Running - Toggle White Spinner")
global whiteIdleActive
whiteIdleActive = not whiteIdleActive
if (repeatCount == 5):
print ("Powering Down System")
repeatCount = 0
os.system("/usr/bin/sudo /sbin/shutdown -h now")
os.kill(os.getpid(),signal.SIGUSR1)
else:
repeatTime = time.time()
repeatCount = 1
repeatBandId = str(bandid)
global currentBandId
currentBandId = bandid
self.scannedEvent.set()
sequence = getSequence(bandid)
if (DEBUG):
print("Playing sound")
self.playSound(sequence.get('spin_sound'))
while not self.successEvent.isSet():
continue
self.playSound(sequence.get('sound'))
self.runWebHook(sequence)
def runWebHook(self, sequence):
global currentBandId
webhooks = sequence.get('webhooks', [])
message_data={}
if webhooks:
webhooks = webhooks if type(webhooks) == list else [webhooks,]
for hook in webhooks:
message_headers = {'Authorization': 'Bearer rNGlneNGSgnLqHpuR7ZRPXc3oSHix7tqwRgw8vST1sA', 'Content-Type': 'application/json; charset=UTF-8'}
message_body="{\"Band\": \"%s\"}" %str(currentBandId)
if (DEBUG):
print(message_data)
http_obj = Http()
response = http_obj.request(
uri=hook,
method='POST',
headers=message_headers,
body=message_body)
if (DEBUG):
print(response)
# Preload sound
def loadSound(self, fname):
if fname == '':
return False
if not path.exists(fname):
print("Missing sound file :" + fname)
return False
if (DEBUG):
print("Found file: " + fname)
return True
# play sound
def playSound(self, fname):
if self.loadSound(fname) == True:
if (DEBUG):
print("Playing sound now")
pygame.mixer.music.load(fname)
pygame.mixer.music.set_volume(1)
pygame.mixer.music.play()
# while pygame.mixer.get_busy() == True:
# time.sleep(1)
class ArgparseError(SystemExit):
def __init__(self, prog, message):
super(ArgparseError, self).__init__(2, prog, message)
def __str__(self):
return '{0}: {1}'.format(self.args[1], self.args[2])
class ArgumentParser(argparse.ArgumentParser):
def error(self, message):
raise ArgparseError(self.prog, message)
if __name__ == '__main__':
atexit.register(exit_handler)
# Hook the SIGINT and create an object of MFRC522 for the card reader
signal.signal(signal.SIGINT, end_read)
MIFAREReader = MFRC522.MFRC522()
GPIO.cleanup()
MIFAREReader = MFRC522.MFRC522()
magicBandScannedEvent = threading.Event()
successEvent = threading.Event()
magicBandObject = MagicBand()
try:
lightsThread = threading.Thread(name='lights',
target=playLightSequence, args=(magicBandScannedEvent, successEvent, ring_pixels, ring_pixels+mickey_pixels), daemon = True)
lightsThread.start()
while True:
bandAndSound = BandScannerAndSound(magicBandScannedEvent, successEvent)
lightsThread.join()
except ArgparseError as e:
print("exception")
print(e)
_prog = e.args[1].split()
else:
sys.exit(0)