forked from Sicness/pyNooLite
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnoolite.py
254 lines (214 loc) · 8.73 KB
/
noolite.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
#!/usr/bin/env python
# Python module for working with NooLite USB stick (PC118, PC1116, PC1132)
# Latest version at: https://github.com/Sicness/pyNooLite
import time
import warnings
try:
import usb.core
except:
raise ImportError(
"Can't import usb.core. Please install 'pyusb' package " +
"from PyPI: pip install pyusb --upgrade")
__author__ = "Anton Balashov"
__license__ = "GPL v3"
__maintainer__ = "Anton Balashov"
__email__ = "[email protected]"
__credits__ = [
"Anton Balashov",
"Yuri Karpenko",
"Alex Bogdanovich",
"Yaraslau Zhylko"
]
class NooLiteErr(Exception):
"""General NooLite error."""
def __init__(self, value):
self.value = value
def __str__(self):
return str(self.value)
class NooLiteDeviceLookupErr(NooLiteErr):
"""Specific NooLite error indicating that target
controller device is not found or not connected.
"""
class NooLite:
"""NooLite controller device.
Keyword arguments:
channels (int): number of controller channels (default: 8).
idVendor (int): ID of the controller device vendor (default: 0x16c0).
idProduct (int): product ID of the controller device (default: 0x05df).
repeats (int): number of times the original command
is repeated to ensure transfer reliability.
0 means no repeats (just one original command).
7 means original command plus 7 additional resends: 8 in total.
(Valid values: 0-7; default: 2).
**device_kwargs (dict): additional usb.core.find() arguments to help
distinguish between several controllers.
channals (int): deprecated version of 'channels' argument.
tests (bool): deprecated, not used any more.
"""
_base_command = [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]
_bitrate = 2 # Default command transfer bit rate
_base_command_interval = 0.15
def __init__(
self, channels=8, idVendor=0x16c0, idProduct=0x05df, repeats=2,
channals=None, tests=None, **device_kwargs):
# Channels
if not isinstance(channels, int):
raise TypeError("'channels' argument must be of int type")
self._channels = channels
# Deprecated 'channals'
if channals is not None:
warnings.warn(
"'channals' argument is deprecated: " +
"use 'channels' argument instead",
DeprecationWarning)
if not isinstance(channals, int):
raise TypeError("'channals' argument must be of int type")
self._channels = channals
# Number of channels limit
if self._channels < 1:
raise ValueError("'channels' argument must be greater than 0")
# idVendor, idProduct
if not isinstance(idVendor, int) or not isinstance(idProduct, int):
raise TypeError(
"'idVendor' and 'idProduct' arguments must be of int type")
self._idVendor = idVendor
self._idProduct = idProduct
# Get number of controller command repeats
if not isinstance(repeats, int):
raise TypeError("'repeats' argument must be of int type")
if not (0 <= repeats <= 7):
raise ValueError("'repeats' argument must be between 0 and 7")
# Set bit rate and number of repeats for initial controller command
self._initial_command = self._base_command[:]
self._initial_command[0] = (self._bitrate << 3) + (repeats << 5)
# Set command interval based on number of repeats
self._command_interval = self._base_command_interval * (repeats + 1)
self._latest_command_timestamp = 0
# Device kwargs for usb.core.find()
self._device_kwargs = device_kwargs
# Deprecated 'tests' argument
if tests is not None:
warnings.warn("'tests' argument is deprecated", DeprecationWarning)
# Public methods
def on(self, ch):
"""Turn power ON for specified channel.
First channel is 0.
"""
return self._send_command(ch, 0x02)
def off(self, ch):
"""Turn power OFF for specified channel.
First channel is 0.
"""
return self._send_command(ch, 0x00)
def switch(self, ch):
"""Switch power state between off and on for specified channel.
First channel is 0.
"""
return self._send_command(ch, 0x04)
def set(self, ch, level):
"""Set brightness level for specified channel.
Level must be between 0 and 120.
First channel is 0.
"""
try:
level = int(level)
except (TypeError, ValueError):
raise TypeError(
"Level value of %s cannot be correctly converted to int"
% (repr(level)))
if not (0 <= level <= 120):
raise NooLiteErr(
"Level value of %d is not valid: must be 0-120" % (level))
if level > 0:
level += 35
return self._send_command(ch, 0x06, level)
def save(self, ch):
"""Save current state as a scenario for specified channel.
First channel is 0.
"""
return self._send_command(ch, 0x08)
def load(self, ch):
"""Call saved scenario for specified channel.
First channel is 0.
"""
return self._send_command(ch, 0x07)
def bind(self, ch):
"""Send binding signal for specified channel.
First channel is 0.
"""
return self._send_command(ch, 0x0f)
def unbind(self, ch):
"""Send unbinding signal for specified channel.
First channel is 0.
"""
return self._send_command(ch, 0x09)
# Private methods
def _send_command(self, ch, action, value=None):
"""Prepare and send NooLite actuation command."""
cmd = self._get_initial_command()
self._set_channel(cmd, ch)
self._set_action(cmd, action, value)
self._send_data(cmd)
return 0 # Return 0 to indicate success
def _get_initial_command(self):
"""Get initial (empty) command."""
return self._initial_command[:]
def _set_channel(self, cmd, ch):
"""Set channel number."""
try:
ch = int(ch)
except (TypeError, ValueError):
raise TypeError(
"Channel %s cannot be correctly converted to int" % (repr(ch)))
if not (0 <= ch < self._channels):
raise NooLiteErr(
"Channel %d is not valid: only channels 0-%d are supported"
% (ch, self._channels - 1))
cmd[4] = ch # Set channel number
def _set_action(self, cmd, action, value):
"""Set specific command action and action value (if required)."""
cmd[1] = action # Set action type
if value is not None:
cmd[2] = 0x01 # Set flag to use single value
cmd[5] = value # Set single value
def _send_data(self, cmd):
"""Send prepared command data to controller device."""
# Find NooLite USB controller device
device = usb.core.find(
idVendor=self._idVendor, idProduct=self._idProduct,
**self._device_kwargs)
if device is None:
raise NooLiteDeviceLookupErr(
"Can't find controller device with %s"
% (self._format_device_data()))
# Detach kernel driver if required
if device.is_kernel_driver_active(0):
device.detach_kernel_driver(0)
# Set controller device configuration
device.set_configuration()
# Make sure command interval is observed
time_delta = time.time() - self._latest_command_timestamp
time.sleep(max(self._command_interval - time_delta, 0))
# Send actual actuation command
device.ctrl_transfer(0x21, 0x09, 0, 0, cmd)
# Record latest command timestamp
self._latest_command_timestamp = time.time()
def _format_channels_data(self):
"""Format number of channels for string output."""
return \
"1 channel" if self._channels == 1 \
else "%d channels" % (self._channels)
def _format_device_data(self):
"""Format idVendor, idProduct and device_kwargs for string output."""
device_data = \
"idVendor=%d, idProduct=%d" % (self._idVendor, self._idProduct)
if self._device_kwargs:
device_data += ", " + ", ".join(
["%s=%s" % (k, v) for k, v in self._device_kwargs.items()])
return device_data
def __str__(self):
return "NooLite controller (%s)" % (self._format_channels_data())
def __repr__(self):
return \
"<NooLite controller: %s, %s>" \
% (self._format_channels_data(), self._format_device_data())