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
|
#!/usr/bin/python
import argparse
import board
import neopixel
import time
from os.path import exists
# parse command line arguments
# TODO parse multiple LEDs e.g. ./ledctl --led 1 red --led 2 white
parser = argparse.ArgumentParser(description='Set LED colors')
parser.add_argument('--led', type=int, help='LED number to control, starting at 1')
parser.add_argument('color', type=str, help='color or command')
args = parser.parse_args();
# initialize LED array
leds_max = 6
leds_num = 0
leds_array = neopixel.NeoPixel(board.D18, leds_max)
# restore LED array from state file
statefile = '/tmp/ledctl.state'
if exists(statefile):
#print('reading ' + statefile)
with open(statefile, 'r') as f:
lines = f.readlines()
i = 0;
for line in lines:
values = [ int(number) for number in line.rstrip().split(' ')]
if (i < leds_max):
leds_array[i] = (values[0], values[1], values[2]);
i = i + 1
f.close()
# figure out if we want to control a single LED or all of them
if args.led:
if (args.led < 1) or (args.led > leds_max):
parser.error("led must be within range")
else:
leds_num = args.led;
# default color is white
leds_color = (255, 255, 255)
def rgbval(colorname):
switch = {
'on': (255, 255, 255),
'off': (0, 0, 0),
'white': (255, 255, 255),
'black': (0, 0, 0),
'red': (255, 0, 0),
'green': (0, 255, 0),
'blue': (0, 0, 255),
'yellow': (255, 255, 0),
'cyan': (0, 255, 255),
'pink': (255, 0, 255),
}
return switch.get(colorname, (255, 255, 255))
def hexval(letter):
switch = {
'0': 0,
'1': 1,
'2': 2,
'3': 3,
'4': 4,
'5': 5,
'6': 6,
'7': 7,
'8': 8,
'9': 9,
'A': 10,
'a': 10,
'B': 11,
'b': 11,
'C': 12,
'c': 12,
'D': 13,
'd': 13,
'E': 14,
'e': 14,
'F': 15,
'f': 15,
}
return switch.get(letter, 0)
if args.color:
#print('color ' + args.color)
if args.color[:1] == '#':
red = 16 * hexval(args.color[1:2]) + hexval(args.color[2:3]);
green = 16 * hexval(args.color[3:4]) + hexval(args.color[4:5]);
blue = 16 * hexval(args.color[5:6]) + hexval(args.color[6:7]);
leds_color = (red, green, blue);
#print ('color %d %d %d' % leds_color)
else:
leds_color = rgbval(args.color);
if (leds_num > 0):
#print('setting LED %d' % leds_num)
leds_array[leds_num - 1] = leds_color
else:
#print('setting all LEDs')
leds_array.fill(leds_color)
# write LED array to state file
#print('writing ' + statefile)
with open(statefile, 'w') as f:
for i in range(leds_max):
for c in range(3):
f.write ('%d ' % leds_array[i][c])
f.write('\n');
f.close()
|