Skip to content

Commit de3afb0

Browse files
committed
Change color sensor to return an enum
Use enum.IntEnum to keep backward compatibility with old scripts.
1 parent 12a8d5f commit de3afb0

2 files changed

Lines changed: 29 additions & 3 deletions

File tree

nxt/sensor/generic.py

Lines changed: 26 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -225,6 +225,30 @@ class Color(BaseAnalogSensor):
225225
light sensor included in the first version or in the Education set.
226226
"""
227227

228+
class DetectedColor(enum.IntEnum):
229+
"""Color detected by the sensor.
230+
231+
This is an :class:`enum.IntEnum` for backward compatibility.
232+
"""
233+
234+
BLACK = 1
235+
"""Black or low intensity."""
236+
237+
BLUE = 2
238+
"""Blue."""
239+
240+
GREEN = 3
241+
"""Green."""
242+
243+
YELLOW = 4
244+
"""Yellow."""
245+
246+
RED = 5
247+
"""Red."""
248+
249+
WHITE = 6
250+
"""White."""
251+
228252
def __init__(self, brick, port):
229253
super().__init__(brick, port)
230254
self.set_light_color(Type.COLOR_FULL)
@@ -258,13 +282,13 @@ def get_color(self):
258282
"""Get detected color.
259283
260284
:return: Detected color.
261-
:rtype: int
285+
:rtype: DetectedColor
262286
263287
This also sets the sensor mode to color detection (light is cycling quickly to
264288
determine color).
265289
"""
266290
self.get_reflected_light(Type.COLOR_FULL)
267-
return self.get_input_values().scaled_value
291+
return self.DetectedColor(self.get_input_values().scaled_value)
268292

269293
get_sample = get_color
270294

tests/test_sensors.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -129,7 +129,9 @@ def test_color(self, mbrick):
129129
(Port.S1, True, False, Type.COLOR_RED, Mode.RAW, 114, 46, 46, 46),
130130
(Port.S1, True, False, Type.COLOR_RED, Mode.RAW, 114, 46, 46, 46),
131131
]
132-
assert s.get_color() == 4
132+
color = s.get_color()
133+
assert color == 4
134+
assert color == s.DetectedColor.YELLOW
133135
assert s.get_reflected_light(Type.COLOR_RED) == 46
134136
assert s.get_light_color() == Type.COLOR_RED
135137
assert mbrick.mock_calls == [

0 commit comments

Comments
 (0)