Skip to content

LED animation support - #567

Merged
dwalton76 merged 15 commits into
ev3dev:ev3dev-stretchfrom
dwalton76:led
Mar 28, 2019
Merged

dwalton76 merged 15 commits into
ev3dev:ev3dev-stretchfrom
dwalton76:led

Conversation

@dwalton76

Copy link
Copy Markdown
Collaborator

For issue #357 and #324

@dwalton76

Copy link
Copy Markdown
Collaborator Author

This is what this looks like in action
https://www.youtube.com/watch?v=WJN8cdpbzec

Tested via

#!/usr/bin/env python3

"""
Used to experiment with the MoveDifferential class
"""

from ev3dev2.led import Led, Leds, LedPoliceLights, LedFlash, LedCycle, LedRainbow
from ev3dev2.sound import Sound
from time import sleep
import logging
import sys

# logging
logging.basicConfig(level=logging.DEBUG,
                    format="%(asctime)s %(levelname)5s: %(message)s")
log = logging.getLogger(__name__)

spkr = Sound()
my_leds = Leds()

for x in range(4):

    if x == 0:
        spkr.speak("police lights")
        pl = LedPoliceLights('RED', 'GREEN')
    elif x == 1:
        spkr.speak("flash")
        pl = LedFlash('AMBER')
    elif x == 2:
        spkr.speak("cycle")
        pl = LedCycle(('RED', 'GREEN', 'AMBER'))
    elif x == 3:
        spkr.speak("rainbow")
        pl = LedRainbow()

    pl.start()
    sleep(7)
    pl.join()

spkr.speak("the end")
my_leds.reset()

@dwalton76

dwalton76 commented Nov 15, 2018 •

Copy link
Copy Markdown
Collaborator Author

The LedRainbow class might be overkill. This was my daughter's request so that the lights would cycle the same way her nightlight does :)

Yell if you can think of any other common animations that might be useful and I will add them.

@dwalton76
dwalton76 requested a review from WasabiFan November 21, 2018 14:05

@WasabiFan WasabiFan left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sorry about this; I had started reviewing, realized it was something I would need to do on my PC rather than phone, and then... completely forgot. I like the new functionality!

Comment thread ev3dev2/led.py Outdated
if not self.leds:
return

self.set_color('LEFT', 'GREEN')

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What about platforms that don't have green LEDs?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yeah I think for this we need a LED_COLOR_DEFAULT in the _platforms file for each platform with a LED...will add that

Comment thread ev3dev2/led.py Resolved
Comment thread ev3dev2/led.py Outdated
self.set_color('RIGHT', 'GREEN')


class LedAnimate(threading.Thread):

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Would there be a sane way to abstract away the fact that each implementation is a Thread object so the thread isn't publically-accesssible? Perhaps instead have a generic LedAnimateThread which takes a function to run? That would seem cleaner to me in that it hides the Thread API surface from the user... It seems to me that we'd want to be able to wrap the default thread methods to A) protect implementation details and B) enable exposing our own interface.

It's also worth noting that exposing a Thread directly probably precludes Micropython support.

Related to my comment on API methods.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That is kind of what we already have it is just via this parent LedAnimateThread class. The child classes primarily only have to define their run method. I like this model myself...to me it is easier to follow than passing a function pointer to run.

As far as exposing the Thread class, we already do so in ev3dev-lang-python-demo. Not sure what to do about that for micropython :(

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Putting aside other pros/cons of the pattern, depending on the API of Thread breaks micropython compatibility, so to protect that I would like to avoid tying our public API surface to that of Python threads. The demo repository is its own case as breaking changes don't impact users. I believe it can be done by replacing the superclass with a line in the constructor which instantiates a Thread with target=self.run and then adding a class method which starts the thread. It would be nice to also add micropython support with its respective threading API, but we can handle that separately.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What if we lazy load the thread module? Then we can say that the animation of LEDs is not supported on micropython but it shouldn't break anything else on micropython.

I need to restructure some things to do this...will give it a try and see what it looks like.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd prefer to design our APIs so that we can support Micropython. As long as the public interface doesn't involve the Thread type, that should be fairly easy using the threading primitives available on Micropython.

Comment thread ev3dev2/led.py Outdated
.. code:: python
from ev3dev2.led import LedFlash
from time import sleep
leds = LedFlash('AMBER')

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In the Move* examples we adopted a pattern where we put the type of move object in the example variable name; can we do the same here? e.g. flash_leds or flash_leds_amber

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍

Comment thread ev3dev2/led.py Outdated
.. code:: python
from ev3dev2.led import LedFlash
from time import sleep
leds = LedFlash('AMBER')

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ugh, now that I think about it we probably should have constants for these strings, I think that's a separate issue though.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yeah...I don't remember whey we did the strings when we implemented this.

Comment thread ev3dev2/led.py Outdated
# Stop event for animate thread
self.done = threading.Event()

def join(self, timeout=None):

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think join is an unnatural API for someone who isn't familiar with threading. In my mind, a typical user would want to be able to:

  • start the animation and have it run in the background
  • stop the animation that was running in the background
  • start the animation and have it run in the background for a particular amount of time (seconds)
  • start the animation and have it run for a particular amount of time, blocking until completion

Personally, I think we should expose these behaviors here rather than the raw Thread interface.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How about stop() instead of join()? I'll add a run_for_ms option so the user can set a limit on how long it should run. blocking....need to think about this some, the fact that we are using threads means we aren't going to block. I could add a block method to LedAnimate that drops into a while loop until done is set. That feels a little clunky but would work.

Comment thread ev3dev2/led.py Outdated
leds.join()
"""

def __init__(self, group1='LEFT', group2='RIGHT', increment_by=0.1, sleeptime=0.1):

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How does this work on non-EV3-like platforms (different LED color combos)?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I need to test this on my brickpi and get back to you

Comment thread ev3dev2/led.py Outdated
self.leds.set_color(self.group1, (left_value, right_value))
self.leds.set_color(self.group2, (left_value, right_value))

if state == 0 and left_value == MAX_VALUE:

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think you can eliminate the if checks and special bounds cases if you use a counter, modulo, and absolute value rather than a state machine.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not following you?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The code in this loop, minus the actual call to set the LEDs, can be replaced with a math expression. If I'm understanding correctly, this should get the same behavior (using a counter, time, etc.): https://www.desmos.com/calculator/tsfanl2e2v

image

This would also make it easy to support different numbers of colors and LEDs.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ok for me that is much much harder to follow than a basic state machine :) With w=4 (so that the max is 1 like we need) this ends up cycling through the following

2018-11-24 13:35:31,396  INFO: left_value 1.0, right_value 0.0
2018-11-24 13:35:31,552  INFO: left_value 1.0, right_value 1.0
2018-11-24 13:35:31,684  INFO: left_value 0.0, right_value 1.0
2018-11-24 13:35:31,812  INFO: left_value 1.0, right_value 1.0
2018-11-24 13:35:31,939  INFO: left_value 1.0, right_value 0.0

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If you'd prefer to use the state machine approach and it works for the various platforms, feel free to go ahead with that — whatever works is fine with me as long as it isn't super ugly.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I should have some time to finish this one up over the holidays

@dwalton76

Copy link
Copy Markdown
Collaborator Author

Haven’t forgotten this just haven’t had enough free time to fix everything

@WasabiFan

Copy link
Copy Markdown
Member

Here's a design choice to ponder...

Right now we have the Leds class which you use to centrally control all the LEDs for the device. With these additions we'd be adding independent classes, that operate on those LEDs with no interaction between independent animation classes. Consider this use case...

buttons = Button()

def on_up(is_pressed):
    if is_pressed:
        animation = LedPoliceLights('RED', 'GREEN')
        # theoretical API
        animation.start()
buttons.on_up = on_up

def on_down(is_pressed):
    if is_pressed:
        animation = LedCycle(('RED', 'GREEN', 'AMBER'))
        # theoretical API
        animation.start()
buttons.on_down = on_down

buttons.process_forever()

The goal is to be able to choose the animation that's playing based on which button you press. The thing is... they will just play on top of each other: there is no mutex logic or centralized controller to prevent this. Same with any combination of animations and normal LED control.

Personally, I think this would be an issue: it should be easy to combine animations without worrying about the runaway threads stepping on each other. In particular, rather than managing animations by instantiating independent objects, I'm thinking it probably makes more sense to build it into the Leds class -- or at least have it interact with it somehow. The key is, animations should interrupt other animations and so should setting LEDs directly.

What do you think?

@dwalton76

Copy link
Copy Markdown
Collaborator Author

Personally, I think this would be an issue: it should be easy to combine animations without worrying about the runaway threads stepping on each other. In particular, rather than managing animations by instantiating independent objects, I'm thinking it probably makes more sense to build it into the Leds class -- or at least have it interact with it somehow. The key is, animations should interrupt other animations and so should setting LEDs directly.

What do you think?

yeah...I can see how the current model is really suspect to having these animate threads step all over each other. Let me add the functionality to the Leds class and see how this looks.

@dwalton76

Copy link
Copy Markdown
Collaborator Author

@WasabiFan sorry it took me 3 months to get to this :( I moved all of the animation functionality to the Leds class and am now using the _thread module instead of threading. I tested starting a new animation thread while an existing animation thread is running. We can correctly signal the existing thread to exit so the two animations do not step all over each other.

@dwalton76

Copy link
Copy Markdown
Collaborator Author

Am scratching my head at the moment on why the docstring test for animate_police_lights is failing

@dwalton76

Copy link
Copy Markdown
Collaborator Author

ok the errors for the sphinx test failures are

/home/robot/ev3dev-lang-python/ev3dev2/led.py:docstring of ev3dev2.led.Leds.animate_police_lights:9: ERROR: Error in "code" directive:
maximum 1 argument(s) allowed, 10 supplied.

.. code:: python
    from ev3dev2.led import Leds
    leds = Leds()
    leds.animate_police_lights('RED', 'GREEN')
/home/robot/ev3dev-lang-python/ev3dev2/led.py:docstring of ev3dev2.led.Leds.animate_flash:7: ERROR: Error in "code" directive:
maximum 1 argument(s) allowed, 9 supplied.

.. code:: python
    from ev3dev2.led import Leds
    leds = Leds()
    leds.animate_flash('AMBER')
/home/robot/ev3dev-lang-python/ev3dev2/led.py:docstring of ev3dev2.led.Leds.animate_cycle:8: ERROR: Error in "code" directive:
maximum 1 argument(s) allowed, 11 supplied.

.. code:: python
    from ev3dev2.led import Leds
    leds = Leds()
    leds.animate_cyle(('RED', 'GREEN', 'AMBER'))
/home/robot/ev3dev-lang-python/ev3dev2/led.py:docstring of ev3dev2.led.Leds.animate_rainbow:7: ERROR: Error in "code" directive:
maximum 1 argument(s) allowed, 9 supplied.

.. code:: python
    from ev3dev2.led import Leds
    leds = Leds()
    leds.animate_rainbow()

These are all in the docstrings for methods in the Leds class but all of the other places where we use .. code:: python are in the docstrings for classes themselves. @WasabiFan do you know if this is supported for methods? I have been trying for about two hours and cannot get these to pass.

@dlech

dlech commented Mar 24, 2019

Copy link
Copy Markdown
Member
.. code-block:: python

    from ev3dev2.led import Leds
    leds = Leds()
    leds.animate_police_lights('RED', 'GREEN')

http://www.sphinx-doc.org/en/master/usage/restructuredtext/directives.html#directive-code-block

@dwalton76

Copy link
Copy Markdown
Collaborator Author
.. code-block:: python

    from ev3dev2.led import Leds
    leds = Leds()
    leds.animate_police_lights('RED', 'GREEN')

http://www.sphinx-doc.org/en/master/usage/restructuredtext/directives.html#directive-code-block

@dlech same problem/error when using code-block

@dlech

dlech commented Mar 24, 2019

Copy link
Copy Markdown
Member

looks like you are missing the blank line

@dwalton76

Copy link
Copy Markdown
Collaborator Author

doh!! Thanks :)

Comment thread ev3dev2/led.py
def __init__(self,
name_pattern=SYSTEM_DEVICE_NAME_CONVENTION, name_exact=False,
desc=None, **kwargs):
self.desc = desc

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is used in __str__() so we need to set it before calling the super init

@dwalton76

Copy link
Copy Markdown
Collaborator Author

Any objections to merging this one in?

@WasabiFan

Copy link
Copy Markdown
Member

I'll review all the open PRs this evening; I've been out of town for the past few days and didn't have time to sit down and read through it.

@WasabiFan WasabiFan left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This looks pretty good! Just some possible refactorings.


LED_COLORS = OrderedDict()
LED_COLORS['BLACK'] = (0,)
LED_COLORS['BLUE'] = (1,)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Are the LEDs actually amber and we've been calling them blue?

This change probably should show up as a changelog entry as well.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yeah it is actually amber...not sure how we goofed that up way back when. Will update the changelog.

LED_COLORS['CYAN'] = (0, 1, 1)
LED_COLORS['MAGENTA'] = (1, 0, 1) No newline at end of file
LED_COLORS['YELLOW'] = (1, 1, 0)
LED_COLORS['CYAN'] = (0, 1, 1)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What changed here? I'm confused...

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I can't spot a delta either. git appears to have lost its mind on these two lines. The MAGENTA line below had a newline added but the YELLOW and CYAN lines look identical to before to me.

@ddemidov ddemidov Mar 28, 2019 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The difference on the YELLOW line is that there was a trailing whitespace.
The difference on the CYAN line that it misses the EOL symbol now.
Same applies to CYAN line (removed trailing whitespace).

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Normally github will show the trailing whitespace in the diff...they must have changed something

Comment thread ev3dev2/led.py
Returns the maximum allowable brightness value.
"""
self._max_brightness, value = self.get_attr_int(self._max_brightness, 'max_brightness')
self._max_brightness, value = self.get_cached_attr_int(self._max_brightness, 'max_brightness')

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍

Comment thread ev3dev2/led.py

def reset(self):
"""
Put all LEDs back to their default color

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does this need to also reset the animation thread?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch will add that.

Comment thread ev3dev2/led.py
for group in self.led_groups:
self.set_color(group, LED_DEFAULT_COLOR)

def animate_stop(self):

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I initially read this name as "animate the LEDs stopping" rather than "stop the LED animation"... can we rename this to something like stop_animation?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I guess it fits with the names of the other animation methods, so maybe it's better as-is. Up to you.

Comment thread ev3dev2/led.py
while self.animate_thread_id:
pass

def animate_police_lights(self, color1, color2, group1='LEFT', group2='RIGHT', sleeptime=0.5, duration=5, block=True):

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Am I correct that on non-EV3 platforms, you must specify groups because these two don't exist?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

correct. My gut says these LED animation methods will probably only really be used on EV3 just because it has much more visible LEDs than all of the other platforms. I think pistorms has two but they are really small.

Comment thread ev3dev2/led.py
else:
self.animate_thread_id = _thread.start_new_thread(_animate_police_lights, ())

def animate_flash(self, color, groups=('LEFT', 'RIGHT'), sleeptime=0.5, duration=5, block=True):

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can this be implemented in terms of animate_cycle? (i.e., one of the colors is the provided one and the other is BLACK)

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think it can. animate_cycle is changing all of the LEDs from one color to the next through a list of colors where animate_police_lights is toggling two groups of LEDs back and forth between two colors.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This was about animate_flash rather than police lights. Not a big issue though.

Comment thread ev3dev2/led.py Outdated

from ev3dev2.led import Leds
leds = Leds()
leds.animate_flash('AMBER')

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we should include setting the duration and sleep time in some/all of these so that a user can see how to do it when glancing at the example.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Will add that for a couple of these so we show with and without those args

Comment thread ev3dev2/led.py
self.animate_stop()

if block:
_animate_flash()

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we want to break this common logic into a method like animate(do_animate, ...) so it's easy to extend with custom animations? (do_animate would be a function). It would be really nice if we could find a way to include the boilerplate logic within the thread (e.g. stopping after time or when cancelled) "for free" but I'm not sure how would be best. Maybe the lambda just runs one LED update step and tracks its own state?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I am not a big fan of lambda myself...I find the resulting code much harder to read/follow :( There is a some repetitive logic in these animate methods but not a crazy amount. I would like to leave it as-is.

@dwalton76
dwalton76 merged commit fecbe4b into ev3dev:ev3dev-stretch Mar 28, 2019
@dwalton76
dwalton76 deleted the led branch March 28, 2019 16:42
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants