ThePiHut / rgbxmastree

Code examples for the RGB Xmas Tree
90 stars 38 forks source link

Threading while loop #15

Closed meatalhead closed 4 years ago

meatalhead commented 4 years ago

Is it possible to run through one of the sequences with a while loop, while allowing the while condition to be changed, would this need to be ran through two threads? For example:

def run_tree(value):
        while value:
            #sparkle

def set_value():
    if tree_on:
        run_tree(tree_on)
        tree_on = False
    else:
        run_tree(tree_on)
        tree_on = True
bennuttall commented 4 years ago

What kind of condition?

meatalhead commented 4 years ago

I'm trying to control it through an internet of thing server. Each time I change the state of the device it calls:

   def set_val(self, value):
        logging.debug(f'set {value}')
        run_tree(value)

with the value being True or False depending on the selection from the internet of things. I'm not sure how to get the tree code to run while still being able to allow that other function to run.

bennuttall commented 4 years ago

Oh I see. You want to set the source of the tree. Setting the source will run a background thread setting its value.

def hue_cycle():
    while True:
        color = tree.color + Hue(deg=1)
        yield [color.rgb] * 25

tree.source_delay = 0.2
tree.source = hue_cycle()

Now the tree value is being set to a new colour every 0.2 seconds, but that's being done in the background. You could run some other code, or unset the source when something else happens, e.g:

while True:
    if something_happens():
        tree.source = None
    else:
        tree.source = hue_cycle()

You just need to make sure that your source function is an iterator, and that it yields a list/tuple of 25 (r, g, b) tuples.

See background on this technique here: https://gpiozero.readthedocs.io/en/latest/source_values.html

Alternatively create your own thread and you can set tree.color or control individual pixels.

meatalhead commented 4 years ago

Great thanks