-
Notifications
You must be signed in to change notification settings - Fork 1
/
xmas-orig.py
executable file
·80 lines (56 loc) · 1.79 KB
/
xmas-orig.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
#!/usr/bin/python3
import asyncio
import random
import signal
import RPi.GPIO as GPIO
# time in seconds
ONTIME = 6
OFFTIME = 0.3
# Random range in the led on/off times (between 0 and 1)
PLUSORMINUS = 0.5
# The time that a given twinkle power is set, in msec
TWINKLEUPDATEPERIOD = 100
# The Twinkle PWM period, in msec
TWINKLEPWMPERIOD = 20
GPIO.setmode(GPIO.BCM)
def calcplusorminus(val, var):
"""return random number in the range val +/- (var*100)%"""
factor = (1.0 - var) + (random.random() * 2 * var)
return factor * val
async def blink_led(ledno):
"""The led blinking coroutine for one led."""
ontime = calcplusorminus(ONTIME, PLUSORMINUS)
offtime = calcplusorminus(OFFTIME, PLUSORMINUS)
GPIO.setup(ledno, GPIO.OUT)
try:
while True:
GPIO.output(ledno, GPIO.HIGH)
await asyncio.sleep(ontime)
GPIO.output(ledno, GPIO.LOW)
await asyncio.sleep(offtime)
except asyncio.CancelledError:
GPIO.setup(ledno, GPIO.IN)
async def amain():
# create a Task for each led.
# gpio 2 is the yellow star - 4-27 are the other tree lights
loop = asyncio.get_event_loop()
tasks = [loop.create_task(blink_led(x)) for x in range(2, 28) if x != 3]
try:
await asyncio.gather(*tasks)
except asyncio.CancelledError:
[task.cancel() for task in tasks]
await asyncio.gather(*tasks)
def do_sigterm():
"""SIGTERM triggers the KeyboardInterrupt handler."""
raise KeyboardInterrupt
def main():
loop = asyncio.get_event_loop()
loop.add_signal_handler(signal.SIGTERM, do_sigterm)
task = loop.create_task(amain())
try:
loop.run_forever()
except KeyboardInterrupt:
task.cancel()
loop.run_until_complete(task)
if __name__ == "__main__":
main()