Exemplo n.º 1
0
    def __init__(self,
                 driver_type,
                 led_layout=None,
                 brightness=DEFAULT_BRIGHTNESS):
        try:
            if driver_type == "PiWS281x":
                driver = PiWS281X(self.NUM_PIXELS)
            elif driver_type == "WS2801":
                driver = WS2801(self.NUM_PIXELS,
                                dev='/dev/spidev0.1',
                                spi_interface=SPI_INTERFACES.PERIPHERY,
                                spi_speed=1)
            elif driver_type == "SimPixel":
                driver = SimPixel(self.NUM_PIXELS)
                driver.open_browser()
            else:
                raise ValueError(
                    "driver_type {driver_type} unknow.".format(driver_type))
        except (ImportError, ValueError) as e:
            print("Not able to initialize the driver. Error{}".format(e))
            print("Use bibliopixel.drivers.dummy_driver")
            driver = DriverDummy(self.NUM_PIXELS)

        if led_layout is not None:
            self.layout = Strip(driver,
                                brightness=brightness,
                                threadedUpdate=True)
        else:
            self.layout = Strip(driver,
                                brightness=brightness,
                                threadedUpdate=True)
        self.layout.cleanup_drivers()
        self.layout.start()
        self.animation = None
Exemplo n.º 2
0
    def __init__(self, rows=ROWS, cols=COLS, brightness=DEFAULT_BRIGHTNESS):
        ROWS = rows 
        COLS = cols
        NUM_PIXELS = ROWS*COLS

        driver = PiWS281X(NUM_PIXELS)
        self.layout = Strip (driver, brightness=brightness,threadedUpdate=True)
        self.layout.cleanup_drivers()
        self.layout.start()
Exemplo n.º 3
0
    def test_serial(self):
        # Code taken from
        # https://gist.github.com/adammhaile/1b43fdde6ae6cbbd35560c68a9b90beb

        from bibliopixel import Strip
        from bibliopixel.drivers.channel_order import ChannelOrder
        from bibliopixel.drivers.serial import Serial, LEDTYPE
        from bibliopixel.drivers.serial.devices import Devices
        from bibliopixel.animation import StripChannelTest

        import bibliopixel.log as log
        import time

        log.setLogLevel(log.DEBUG)

        devs = Devices(hardware_id="1D50:60AB", baudrate=921600)

        log.info("Serial devices:")
        dev_list = devs.find_serial_devices()
        log.info(dev_list)

        first_dev = dev_list[list(dev_list.keys())[0]][0]

        log.info('Default device:')
        log.info(devs.get_device())

        log.info('Device ID for: ' + first_dev)
        old_id = devs.get_device_id(first_dev)
        log.info(old_id)

        log.info('Setting device ID to 42')
        devs.set_device_id(first_dev, 42, baudrate=921600)

        log.info('New Device ID for: ' + first_dev)
        log.info(devs.get_device_id(first_dev))

        log.info('Restoring device ID to ' + str(old_id))
        devs.set_device_id(first_dev, old_id, baudrate=921600)

        log.info('Device version for: ' + first_dev)
        log.info(devs._get_device_version(first_dev))

        driver = Serial(
            LEDTYPE.APA102, 600, SPISpeed=4, c_order=ChannelOrder.RGB)
        layout = Strip(driver)

        for b in range(7, 256, 8):
            log.info('Set brightness ' + str(b))
            layout.set_brightness(b)
            time.sleep(0.25)

        log.info('Run StripChannelTest')
        anim = StripChannelTest(layout)

        anim.run(amt=1, max_steps=8)

        layout.all_off()
        layout.update()

        print("Test Complete!")
Exemplo n.º 4
0
    def test_serial(self):
        # Code taken from
        # https://gist.github.com/adammhaile/1b43fdde6ae6cbbd35560c68a9b90beb

        log.setLogLevel(log.DEBUG)

        devs = Devices(hardware_id="1D50:60AB", baudrate=921600)

        log.info("Serial devices:")
        dev_list = devs.find_serial_devices()
        log.info(dev_list)

        first_dev = dev_list[list(dev_list.keys())[0]][0]

        log.info('Default device:')
        log.info(devs.get_device())

        log.info('Device ID for: ' + first_dev)
        old_id = devs.get_device_id(first_dev)
        log.info(old_id)

        log.info('Setting device ID to 42')
        devs.set_device_id(first_dev, 42, baudrate=921600)

        log.info('New Device ID for: ' + first_dev)
        log.info(devs.get_device_id(first_dev))

        log.info('Restoring device ID to ' + str(old_id))
        devs.set_device_id(first_dev, old_id, baudrate=921600)

        log.info('Device version for: ' + first_dev)
        log.info(devs._get_device_version(first_dev))

        driver = Serial(LEDTYPE.APA102,
                        600,
                        SPISpeed=4,
                        c_order=ChannelOrder.RGB)
        layout = Strip(driver)

        for b in range(7, 256, 8):
            log.info('Set brightness ' + str(b))
            layout.set_brightness(b)
            time.sleep(0.25)

        log.info('Run StripChannelTest')
        anim = StripChannelTest(layout)

        anim.run(amt=1, max_steps=8)

        layout.all_off()
        layout.update()

        log.printer("Test Complete!")
Exemplo n.º 5
0
    def __init__(self, 
                    driver_type, 
                    led_mapping=DEFAULT_LED_MAPPING_FILE, 
                    brightness=DEFAULT_BRIGHTNESS):
        #read led mapping
        led_mappimng_abs = os.path.join(os.path.dirname(__file__), led_mapping)
        with open(led_mappimng_abs) as json_file:
            try:
                data = json.load(json_file)
            except Exception as e:
                print("Json led mapping not a valid JSON.")
                raise e
            else:
                self.MAPPING = data
        
        try:
            num_pixels=self.MAPPING["num_pixels"]
        except:
            num_pixels=max(self.MAPPING.values())+1

        try:
            if driver_type == "PiWS281x":
                driver = PiWS281X(num_pixels)
            elif driver_type == "WS2801":
                driver = WS2801(num_pixels, dev='/dev/spidev0.1',spi_interface= SPI_INTERFACES.PERIPHERY,spi_speed=1)
            elif driver_type == "SimPixel":
                driver = SimPixel(num_pixels)
                driver.open_browser()
            else:
                raise ValueError("driver_type {driver_type} unknow.".format(driver_type) )
        except (ImportError, ValueError) as e:
            print("Not able to initialize the driver. Error{}".format(e))
            print("Use bibliopixel.drivers.dummy_driver")
            driver = DriverDummy(num_pixels)

        self.layout = Strip (driver, brightness=brightness,threadedUpdate=True)
        self.layout.cleanup_drivers()
        self.layout.start()
        self.animation = None
Exemplo n.º 6
0
def main(anim_cls, fps, json_params, sim, num, verify, args):
    params = {}
    if json_params:
        params = json.loads(json_params)

    if anim_cls.startswith('BPAS'):
        anim_cls = anim_cls.replace('BPAS', 'BiblioPixelAnimations.strip')

    if sim:
        driver = SimPixel(num=144)
        num = 0
    else:
        filename = './POV_Files/' + anim_cls.split('.')[::-1][0] + '.' + str(fps).zfill(3)
        cfg_filename = './POV_Files/' + anim_cls.split('.')[::-1][0] + '_' + str(fps) + '.json'
        if args:
            with open(cfg_filename, 'w') as cfg_json:
                json.dump(args, cfg_json)

        driver = POVGen(num=144, filename=filename)
        fps = None

    layout = Strip(driver)

    anim_obj = import_symbol(anim_cls)
    anim = anim_obj(layout, **params)

    anim.run(fps=fps, max_steps=num)
    driver.cleanup()
    if not sim and verify:
        with open(filename, 'rb') as data:
            data = list(bytearray(data.read()))
        color_list = [tuple(data[x:x + 3]) for x in range(0, len(data), 3)]
        rows = [color_list[x:x + NUM] for x in range(0, len(color_list), NUM)]
        row_count = len(rows)
        flat = [c for row in rows for c in row]
        img = Image.new('RGB', (NUM, row_count))
        img.putdata(flat)
        img.save(filename + '.png')
        fl_img = Image.new('RGB', (NUM, 2))
        fl_img.putdata(rows[-1] + rows[0])
        fl_img.save(filename + '_fl.png')
Exemplo n.º 7
0
class MoonBoard:
    DEFAULT_PROBLEM_COLORS = {'START':COLORS.blue,'TOP':COLORS.red,'MOVES':COLORS.green}
    DEFAULT_COLOR = COLORS.blue #FIXME ?
    X_GRID_NAMES = string.ascii_uppercase[0:11] # FIXME: del
    ROWS = 18 
    COLS = 11
    DEFAULT_BRIGHTNESS = 100 # FIXME: to config file
    SETUP = 'MoonboardMasters2017' # FIXME: to config file / Arg
    DEFAULT_LED_MAPPING_FILE='led_mapping.json'
    # generate with {C+str(n+1):int(i*18+ (1-((-1)**(i%2)))/2*17 + ((-1)**(i%2))*n) for  i, C in enumerate(string.ascii_uppercase[0:11]) for n in range(18) }
    def __init__(self, 
                    driver_type, 
                    led_mapping=DEFAULT_LED_MAPPING_FILE, 
                    brightness=DEFAULT_BRIGHTNESS):
        #read led mapping
        led_mappimng_abs = os.path.join(os.path.dirname(__file__), led_mapping)
        with open(led_mappimng_abs) as json_file:
            try:
                data = json.load(json_file)
            except Exception as e:
                print("Json led mapping not a valid JSON.")
                raise e
            else:
                self.MAPPING = data
        
        try:
            num_pixels=self.MAPPING["num_pixels"]
        except:
            num_pixels=max(self.MAPPING.values())+1

        try:
            if driver_type == "PiWS281x":
                driver = PiWS281X(num_pixels)
            elif driver_type == "WS2801":
                driver = WS2801(num_pixels, dev='/dev/spidev0.1',spi_interface= SPI_INTERFACES.PERIPHERY,spi_speed=1)
            elif driver_type == "SimPixel":
                driver = SimPixel(num_pixels)
                driver.open_browser()
            else:
                raise ValueError("driver_type {driver_type} unknow.".format(driver_type) )
        except (ImportError, ValueError) as e:
            print("Not able to initialize the driver. Error{}".format(e))
            print("Use bibliopixel.drivers.dummy_driver")
            driver = DriverDummy(num_pixels)

        self.layout = Strip (driver, brightness=brightness,threadedUpdate=True)
        self.layout.cleanup_drivers()
        self.layout.start()
        self.animation = None

    def clear(self):
        self.stop_animation()
        self.layout.all_off()
        self.layout.push_to_driver()

    def set_hold(self, hold, color=DEFAULT_COLOR):
        self.layout.set(self.MAPPING[hold], color)

    def show_hold(self, hold, color=DEFAULT_COLOR):
        self.set_hold(hold, color)
        self.layout.push_to_driver()

    def show_problem(self, holds, hold_colors={}):
        self.clear()
        for k in ['START', 'MOVES', 'TOP']:
            for hold in holds[k]:
                self.set_hold(
                    hold, 
                    hold_colors.get(k, self.DEFAULT_PROBLEM_COLORS[k]),
                    )
        self.layout.push_to_driver()

    def led_layout_test(self, duration, **kwds): 
        for c in self.X_GRID_NAMES:
            for j in range (1,self.ROWS+1):
                h = c+str(j)
                print (h)
                for color in [COLORS.red, COLORS.blue]:
                    self.layout.set(self.MAPPING[h], color)
                    self.layout.push_to_driver()
                    time.sleep(duration/400)
        
    def display_holdset(self, holdset="Hold Set A", duration=10, **kwds): 
        print ("Display holdset: " + str(holdset))

        with open('../problems/HoldSetup.json') as json_file: # FIXME: path 
            data = json.load(json_file)
            for hold in data[self.SETUP]:
                hs = (data[self.SETUP][hold]['HoldSet']) 
                color = COLORS.black
    
                if (hs == holdset):# FIXME
                        color = COLORS.green                    
    
                self.layout.set(self.MAPPING[hold], color)

                #self.set_hold (hold, color)
                #print "Orientation"
        
        self.layout.push_to_driver()

        wait_holdset_duration = duration # FIXME
        time.sleep(wait_holdset_duration)

        self.clear()
                
                
                
    def stop_animation(self):
        if self.animation is not None:
            self.animation.stop()
Exemplo n.º 8
0
class MoonBoard:
    DEFAULT_PROBLEM_COLORS = {
        'START': COLORS.blue,
        'TOP': COLORS.red,
        'MOVES': COLORS.green
    }
    DEFAULT_COLOR = COLORS.blue  #FIXME ?
    X_GRID_NAMES = string.ascii_uppercase[0:11]  # FIXME: del
    LED_SPACING = 3  # Use every n-th LED only - used for 3 x 4x5 LED strp      # FIXME: normal=1
    ROWS = 18 * LED_SPACING  # FIXME
    COLS = 11
    NUM_PIXELS = ROWS * COLS
    DEFAULT_BRIGHTNESS = 100  # FIXME: to config file
    SETUP = 'MoonboardMasters2017'  # FIXME: to config file / Arg

    # FIXME: json
    MAPPING = {}

    with open('/home/pi/moonboard/led/led_mapping.json') as json_file:
        data = json.load(json_file)
        MAPPING = data

    def __init__(self,
                 driver_type,
                 led_layout=None,
                 brightness=DEFAULT_BRIGHTNESS):
        try:
            if driver_type == "PiWS281x":
                driver = PiWS281X(self.NUM_PIXELS)
            elif driver_type == "WS2801":
                driver = WS2801(self.NUM_PIXELS,
                                dev='/dev/spidev0.1',
                                spi_interface=SPI_INTERFACES.PERIPHERY,
                                spi_speed=1)
            elif driver_type == "SimPixel":
                driver = SimPixel(self.NUM_PIXELS)
                driver.open_browser()
            else:
                raise ValueError(
                    "driver_type {driver_type} unknow.".format(driver_type))
        except (ImportError, ValueError) as e:
            print("Not able to initialize the driver. Error{}".format(e))
            print("Use bibliopixel.drivers.dummy_driver")
            driver = DriverDummy(self.NUM_PIXELS)

        if led_layout is not None:
            self.layout = Strip(driver,
                                brightness=brightness,
                                threadedUpdate=True)
        else:
            self.layout = Strip(driver,
                                brightness=brightness,
                                threadedUpdate=True)
        self.layout.cleanup_drivers()
        self.layout.start()
        self.animation = None

    def clear(self):
        self.stop_animation()
        self.layout.all_off()
        self.layout.push_to_driver()

    def set_hold(self, hold, color=DEFAULT_COLOR):
        self.layout.set(self.MAPPING[hold], color)

    def show_hold(self, hold, color=DEFAULT_COLOR):
        self.set_hold(hold, color)
        self.layout.push_to_driver()

    def show_problem(self, holds, hold_colors={}):
        self.clear()
        for k in ['START', 'MOVES', 'TOP']:
            for hold in holds[k]:
                self.set_hold(
                    hold,
                    hold_colors.get(k, self.DEFAULT_PROBLEM_COLORS[k]),
                )
        self.layout.push_to_driver()

    # run all colors in led´s to see if something is missing
    def led_test(self):
        print('led test')
        duration = 0.4
        COLORS = ['red', 'green', 'blue']

        for color in range(len(COLORS)):
            for i in range(1, self.ROWS + 1):
                for j in range(0, self.COLS):
                    le = chr(j + 65)
                    h = le + str(i)
                    #print (h)
                    self.layout.set(self.MAPPING[h], COLORS[color])
                self.layout.push_to_driver()
                time.sleep(duration)

        time.sleep(1.2)
        self.clear()

    def run_animation(self,
                      run_options={},
                      **kwds):  # FIXME: will it still work?
        duration = 0.001

        for i in range(1, self.ROWS + 1):
            for j in range(0, self.COLS):

                le = chr(j + 65)
                h = le + str(i)
                print(h)
                self.layout.set(self.MAPPING[h], COLORS.purple)
                #self.set_hold (h, COLORS.red)
            self.layout.push_to_driver()
            time.sleep(duration)

        time.sleep(1)
        self.clear()

        with open('../problems/HoldSetup.json') as json_file:  # FIXME: path
            data = json.load(json_file)
            for hold in data[self.SETUP]:
                holdset = (data[self.SETUP][hold]['HoldSet']
                           )  # A, B, OS for 2016
                color = COLORS.black
                #if (holdset == "Hold Set A"): # FIXME
                #    color = COLORS.red
                #    print (hold, data[self.SETUP][hold]["Orientation"])
                #if (holdset == "Original School Holds"):# FIXME
                #    color = COLORS.blue
                #    print (hold, data[self.SETUP][hold]["Orientation"])
                #if (holdset == "Hold Set B"):# FIXME
                #    color = COLORS.yellow
                #    print (hold, data[self.SETUP][hold]["Orientation"])
                if (holdset == "Hold Set C"):  # FIXME
                    color = COLORS.green
                self.layout.set(self.MAPPING[hold], color)
                #self.set_hold (hold, color)
                #print "Orientation"

        self.layout.push_to_driver()

        time.sleep(60 * 10)

        self.clear()

    def display_holdset(self, holdset="Hold Set A", duration=10, **kwds):
        print("Display holdset: " + str(holdset))

        with open('../problems/HoldSetup.json') as json_file:  # FIXME: path
            data = json.load(json_file)
            for hold in data[self.SETUP]:
                hs = (data[self.SETUP][hold]['HoldSet'])
                color = COLORS.black

                if (hs == holdset):  # FIXME
                    color = COLORS.green

                self.layout.set(self.MAPPING[hold], color)

                #self.set_hold (hold, color)
                #print "Orientation"

        self.layout.push_to_driver()

        time.sleep(60 * 10)

        self.clear()

    def stop_animation(self):
        if self.animation is not None:
            self.animation.stop()
Exemplo n.º 9
0
def init_pixels(type, npixels=MOONBOARD_PIXELS_COUNT, brightness=BRIGHTNESS):

    layout = Strip(driver, brightness=brightness)
    #layout.start()
    return layout
Exemplo n.º 10
0
class MoonBoard:
    DEFAULT_PROBLEM_COLORS = {'START':COLORS.blue,'TOP':COLORS.red,'MOVES':COLORS.green}
    DEFAULT_COLOR = COLORS.blue #FIXME ?
    X_GRID_NAMES = string.ascii_uppercase[0:11] # FIXME: del
    LED_SPACING = 3 # Use every n-th LED only - used for 3 x 4x5 LED strp      # FIXME: normal=1
    ROWS = 18 
    COLS = 11
    NUM_PIXELS = ROWS*COLS * LED_SPACING
    DEFAULT_BRIGHTNESS = 100 # FIXME: to config file
    SETUP = 'MoonboardMasters2017' # FIXME: to config file / Arg

    
    # FIXME: json
    MAPPING= { }

    with open('/home/pi/moonboard/led/led_mapping.json') as json_file:
        data = json.load(json_file)
        MAPPING = data


    def __init__(self, driver_type, led_layout=None, brightness=DEFAULT_BRIGHTNESS):
        try:
            if driver_type == "PiWS281x":
                driver = PiWS281X(self.NUM_PIXELS)
            elif driver_type == "WS2801":
                driver = WS2801(self.NUM_PIXELS, dev='/dev/spidev0.1',spi_interface= SPI_INTERFACES.PERIPHERY,spi_speed=1)
            elif driver_type == "SimPixel":
                driver = SimPixel(self.NUM_PIXELS)
                driver.open_browser()
            else:
                raise ValueError("driver_type {driver_type} unknow.".format(driver_type) )
        except (ImportError, ValueError) as e:
            print("Not able to initialize the driver. Error{}".format(e))
            print("Use bibliopixel.drivers.dummy_driver")
            driver = DriverDummy(self.NUM_PIXELS)

        if led_layout is not None:
            self.layout = Strip (driver, brightness=brightness,threadedUpdate=True)
        else:
            self.layout = Strip (driver, brightness=brightness,threadedUpdate=True) 
        self.layout.cleanup_drivers()
        self.layout.start()
        self.animation = None

    def clear(self):
        self.stop_animation()
        self.layout.all_off()
        self.layout.push_to_driver()

    def set_hold(self, hold, color=DEFAULT_COLOR):
        self.layout.set(self.MAPPING[hold], color)

    def show_hold(self, hold, color=DEFAULT_COLOR):
        self.set_hold(hold, color)
        self.layout.push_to_driver()

    def show_problem(self, holds, hold_colors={}):
        self.clear()
        for k in ['START', 'MOVES', 'TOP']:
            for hold in holds[k]:
                self.set_hold(
                    hold, 
                    hold_colors.get(k, self.DEFAULT_PROBLEM_COLORS[k]),
                    )
        self.layout.push_to_driver()

    # run all colors in led´s to see if something is missing
    def led_test(self):
        print('led test')
        duration = 0.4
        COLORS = ['red', 'green', 'blue']

        for color in range(len(COLORS)):
            for i in range(1,self.ROWS+1):
                for j in range (0,self.COLS):
                    le = chr(j+65)
                    h = le+str(i)
                    #print (h)
                    self.layout.set(self.MAPPING[h], COLORS[color])
                self.layout.push_to_driver()
                time.sleep(duration)

        time.sleep (1.2)
        self.clear()



    def run_flare(self, my_col="F", use_cols=False):
        # Reference: http://www.anirama.com/1000leds/1d-fireworks/
        NUM_LEDS = 18 # FIXME
        #NUM_SPARKS = NUM_LEDS/2 #// max number (could be NUM_LEDS / 2);
        
        sparkPos = [0,0,0,0,0,0,0,0,0] # width of flare: 3 LED
        sparkVel = [0,0,0,0,0,0,0,0,0]
        sparkCol = [0,0,0,0,0,0,0,0,0]
        tmp_col = ord (my_col)
        spark_col = [tmp_col,tmp_col,tmp_col,tmp_col,tmp_col,tmp_col,tmp_col,tmp_col,tmp_col]
        
        flarePos = 0.
        gravity = -.004 * 10 # m/s/s
        flareVel = random.randint(50,90) / 100.  *1.55 # trial and error to get reasonable range
        brightness = 1.

        # initialize launch sparks
        print ("Init launch sparks")
        for i in range (0,3): # FIXME nSparks
            sparkPos[i] = 0.
            sparkVel[i] = flareVel * float(random.randint(80,120) / 100)  # * (flareVel / 5)
            # random around 20% of flare velocity
            sparkCol[i] = sparkVel[i] * 1000
            sparkCol[i] = clamp(sparkCol[i], 0, 255)
            print (str(i)+ " with "+str(sparkVel[i])+" and "+str(sparkCol[i]))

        # Phase 1: Flare
        print ("Launch flare")
        self.clear()
        while flareVel >= -.2:
            # sparks
            print ("Run spark with velocity "+str(flareVel))

            # Disable all led in column
            for i in range (1,NUM_LEDS+1):
                tmp_led = my_col + str (i)
                self.layout.set(self.MAPPING[tmp_led], (0,0,0))

            for i in range (0,3):
                sparkPos[i] = sparkPos[i] + sparkVel[i]
                sparkPos[i] = clamp(sparkPos[i], 0.0, NUM_LEDS*1.0)
                sparkVel[i] = sparkVel[i] + gravity
                sparkCol[i] = sparkCol[i] -.8*7 # FIXME
                sparkCol[i] = clamp(sparkCol[i], 0.0, 255.0)
                tmp_row = clamp(int (sparkPos[i]), 1, NUM_LEDS)
                c = (sparkCol[i],0,0) # FIXME: cleanup
                tmp_led = my_col + str (tmp_row)
                print ("Spark position "+str(tmp_led)+" with "+str(sparkPos[i])+" and "+str(sparkCol[i]))
                self.layout.set(self.MAPPING[tmp_led], c)


            # flare
            tmp_row = clamp(int (flarePos), 1, NUM_LEDS)
            tmp_led = my_col + str (tmp_row)
            flareCol = (255.,0,0) # FIXME 
            print ("Flare position "+str(tmp_led)+" with "+str(flarePos)+" and "+str(flareCol))
            self.layout.set(self.MAPPING[tmp_led], flareCol)
            self.layout.push_to_driver()
            flarePos = flarePos + flareVel
            flarePos = clamp(flarePos, 0, NUM_LEDS)
            flareVel = flareVel + gravity
            brightness =  brightness * 0.9

        # Phase 2: Explosion
        print ("Run explosion")
        nSparks = int (flarePos / 2)

        # Initialize Sparks
        for i in range (0,nSparks):
            sparkPos[i] = flarePos
            sparkVel[i] = float(random.randint(-100,100) / 100) # from -1 to 1 
            sparkCol[i] = abs(sparkVel[i]) * 500 # set colors before scaling velocity to keep them bright 
            sparkCol[i] = clamp(sparkCol[i], 0., 255.)
            sparkVel[i] = sparkVel[i] * flarePos / NUM_LEDS # proportional to height 

        sparkCol[0] = 255 # // this will be our known spark 
        dying_gravity = gravity
        c1 = 120*1.5
        c2 = 50*2.7

        while sparkCol[0] > c2/128: # as long as our known spark is lit, work with all the sparks
            print ("Run spark with reference spark lit  "+str(sparkCol[0]))

            # Disable all led in column
            for i in range (1,NUM_LEDS+1):
                tmp_led = my_col + str (i)
                self.layout.set(self.MAPPING[tmp_led], (0,0,0))

            for i in range (0,nSparks):
                sparkPos[i] = sparkPos[i] + sparkVel[i]
                sparkPos[i] = clamp(sparkPos[i], 0, NUM_LEDS)
                sparkVel[i] = sparkVel[i] + dying_gravity
                sparkCol[i] = sparkCol[i] * .9 # FIXME 
                sparkCol[i] = clamp(sparkCol[i], 0, 255) #  // red cross dissolve 
                
                tmp_col = my_col
                if use_cols:
                    spark_col[i] = spark_col[i] + sparkVel[i]
                    spark_col[i] = clamp(spark_col[i],65,65+11-1) # FIXME
                    tmp_col = chr(int(spark_col[i]))

                c = (0,0,0)
                tmp_row = clamp(int (sparkPos[i]), 1, NUM_LEDS)
                tmp_led = tmp_col + str (tmp_row)
                if(sparkCol[i] > c1): #// fade white to yellow
                    c = (255, 255, (255 * (sparkCol[i] - c1)) / (255 - c1))
                elif sparkCol[i] < c2: # // fade from red to black
                    c = ((255 * sparkCol[i]) / c2, 0, 0)
                else: # // fade from yellow to red
                    c = (255, (255 * (sparkCol[i] - c2)) / (c1 - c2), 0)     

                print ("Spark position "+str(tmp_led)+" with "+str(sparkPos[i])+" and "+str(tmp_col)+" and "+str(c))

                self.layout.set(self.MAPPING[tmp_led], c)

            dying_gravity = dying_gravity * .995 #// as sparks burn out they fall slower
            self.layout.push_to_driver()

    def run_flare_multi(self, my_col="F", use_cols=False):
        # Reference: http://www.anirama.com/1000leds/1d-fireworks/
        NUM_LEDS = 18 # FIXME
        #NUM_SPARKS = NUM_LEDS/2 #// max number (could be NUM_LEDS / 2);
        
        sparkPos = [0,0,0,0,0,0,0,0,0] # width of flare: 3 LED
        sparkVel = [0,0,0,0,0,0,0,0,0]
        sparkCol = [0,0,0,0,0,0,0,0,0]
        tmp_col = ord (my_col)
        spark_col = [tmp_col,tmp_col,tmp_col,tmp_col,tmp_col,tmp_col,tmp_col,tmp_col,tmp_col]
        
        flarePos = 0.
        gravity = -.004 * 10 # m/s/s
        flareVel = random.randint(50,90) / 100.  *1.55 # trial and error to get reasonable range
        brightness = 1.

        # initialize launch sparks
        print ("Init launch sparks")
        for i in range (0,3): # FIXME nSparks
            sparkPos[i] = 0.
            sparkVel[i] = flareVel * float(random.randint(80,120) / 100)  # * (flareVel / 5)
            # random around 20% of flare velocity
            sparkCol[i] = sparkVel[i] * 1000
            sparkCol[i] = clamp(sparkCol[i], 0, 255)
            print (str(i)+ " with "+str(sparkVel[i])+" and "+str(sparkCol[i]))

        # Phase 1: Flare
        print ("Launch flare")
        self.clear()
        while flareVel >= -.2:
            # sparks
            print ("Run spark with velocity "+str(flareVel))

            # Disable all led in column
            for i in range (1,NUM_LEDS+1):
                for my_col in ["A","B","C","D","E","F","G","H","I","J","K"]:
                    tmp_led = my_col + str (i)
                    self.layout.set(self.MAPPING[tmp_led], (0,0,0))

            for i in range (0,3):
                sparkPos[i] = sparkPos[i] + sparkVel[i]
                sparkPos[i] = clamp(sparkPos[i], 0.0, NUM_LEDS*1.0)
                sparkVel[i] = sparkVel[i] + gravity
                sparkCol[i] = sparkCol[i] -.8*7 # FIXME
                sparkCol[i] = clamp(sparkCol[i], 0.0, 255.0)
                tmp_row = clamp(int (sparkPos[i]), 1, NUM_LEDS)
                c = (sparkCol[i],0,0) # FIXME: cleanup
                for my_col in ["A","B","C","D","E","F","G","H","I","J","K"]:
                    tmp_led = my_col + str (tmp_row)
                    print ("Spark position "+str(tmp_led)+" with "+str(sparkPos[i])+" and "+str(sparkCol[i]))
                    self.layout.set(self.MAPPING[tmp_led], c)


            # flare
            tmp_row = clamp(int (flarePos), 1, NUM_LEDS)
            for my_col in ["A","B","C","D","E","F","G","H","I","J","K"]:
                tmp_led = my_col + str (tmp_row)
                flareCol = (255.,0,0) # FIXME 
                print ("Flare position "+str(tmp_led)+" with "+str(flarePos)+" and "+str(flareCol))
                self.layout.set(self.MAPPING[tmp_led], flareCol)

            self.layout.push_to_driver()
            flarePos = flarePos + flareVel
            flarePos = clamp(flarePos, 0, NUM_LEDS)
            flareVel = flareVel + gravity
            brightness =  brightness * 0.9

        # Phase 2: Explosion
        print ("Run explosion")
        nSparks = int (flarePos / 2)

        # Initialize Sparks
        for i in range (0,nSparks):
            sparkPos[i] = flarePos
            sparkVel[i] = float(random.randint(-100,100) / 100) # from -1 to 1 
            sparkCol[i] = abs(sparkVel[i]) * 500 # set colors before scaling velocity to keep them bright 
            sparkCol[i] = clamp(sparkCol[i], 0., 255.)
            sparkVel[i] = sparkVel[i] * flarePos / NUM_LEDS # proportional to height 

        sparkCol[0] = 255 # // this will be our known spark 
        dying_gravity = gravity
        c1 = 120*1.5
        c2 = 50*2.7

        while sparkCol[0] > c2/128: # as long as our known spark is lit, work with all the sparks
            print ("Run spark with reference spark lit  "+str(sparkCol[0]))

            # Disable all led in column
            for i in range (1,NUM_LEDS+1):
                for my_col in ["A","B","C","D","E","F","G","H","I","J","K"]:
                    tmp_led = my_col + str (i)
                    self.layout.set(self.MAPPING[tmp_led], (0,0,0))

            for i in range (0,nSparks):
                sparkPos[i] = sparkPos[i] + sparkVel[i]
                sparkPos[i] = clamp(sparkPos[i], 0, NUM_LEDS)
                sparkVel[i] = sparkVel[i] + dying_gravity
                sparkCol[i] = sparkCol[i] * .9 # FIXME 
                sparkCol[i] = clamp(sparkCol[i], 0, 255) #  // red cross dissolve 

                if(sparkCol[i] > c1): #// fade white to yellow
                    c = (255, 255, (255 * (sparkCol[i] - c1)) / (255 - c1))
                elif sparkCol[i] < c2: # // fade from red to black
                    c = ((255 * sparkCol[i]) / c2, 0, 0)
                else: # // fade from yellow to red
                    c = (255, (255 * (sparkCol[i] - c2)) / (c1 - c2), 0)    

                for my_col in ["A","B","C","D","E","F","G","H","I","J","K"]:
                    tmp_col = my_col

                    c = (0,0,0)
                    tmp_row = clamp(int (sparkPos[i]), 1, NUM_LEDS)
                    tmp_led = tmp_col + str (tmp_row)
                  

                    print ("Spark position "+str(tmp_led)+" with "+str(sparkPos[i])+" and "+str(tmp_col)+" and "+str(c))

                    self.layout.set(self.MAPPING[tmp_led], c)

            dying_gravity = dying_gravity * .995 #// as sparks burn out they fall slower
            self.layout.push_to_driver()

    def run_animation(self, duration = 0.01): 
        # The moonboard can serve a (x,y) = (11,18) --> 198 Pixel display 
        # Refs: 
        # - http://www.anirama.com/1000leds/1d-fireworks/
        duration2 = duration * 0

        for i in range(1,self.ROWS+1):
            for j in range (0,self.COLS):

                le = chr(j+65)
                h = le+str(i)
                print (h)
                for c in [COLORS.purple, COLORS.blue, COLORS.red]:
                    self.layout.set(self.MAPPING[h], c)
                    self.layout.push_to_driver()
                    time.sleep(duration)
    
        time.sleep(duration2)

        self.clear()

    def display_melon(self):
        # Ref: http://pixelartmaker.com/art/d8f3ce82dd215ed
        self.clear()
        red = (255,0,0)
        black = (0,0,0)
        lila = hex2rgb("#ff99dd") #(255,100,200) #ff99dd
        green1 = hex2rgb("#118233") #COLORS.lime)
        green2 = hex2rgb("#089c48") #COLORS.limegreen

        for h in ["C1","D1","E1","F1","G1"]:
            self.layout.set(self.MAPPING[h], green2)
        for h in ["B2","H2"]:
            self.layout.set(self.MAPPING[h], green2)
        for h in ["C2","D2","E2","F2","G2"]:
            self.layout.set(self.MAPPING[h], green1)
        for h in ["A3","I3"]:
            self.layout.set(self.MAPPING[h], green2)
        for h in ["H3"]:
            self.layout.set(self.MAPPING[h], green1)
        for h in ["B3","C3","D3","E3","F3","G3"]:
            self.layout.set(self.MAPPING[h], lila)
        for h in ["A4","C4","D4","E4","F4","G4"]:
            self.layout.set(self.MAPPING[h], red)
        for h in ["H4"]:
            self.layout.set(self.MAPPING[h], lila)
        for h in ["I4"]:
            self.layout.set(self.MAPPING[h], green1)
        for h in ["J4"]:
            self.layout.set(self.MAPPING[h], green2)
        for h in ["A5","B5","C5","E5","G4"]:
            self.layout.set(self.MAPPING[h], red)
        for h in ["H5"]:
            self.layout.set(self.MAPPING[h], lila)
        for h in ["I5"]:
            self.layout.set(self.MAPPING[h], green1)
        for h in ["J5"]:
            self.layout.set(self.MAPPING[h], green2)
        for h in ["B6","C6","D6","E6","F6","G6"]:
            self.layout.set(self.MAPPING[h], red)
        for h in ["H6"]:
            self.layout.set(self.MAPPING[h], lila)
        for h in ["I6"]:
            self.layout.set(self.MAPPING[h], green1)
        for h in ["J6"]:
            self.layout.set(self.MAPPING[h], green2)
        for h in ["C7","D7","F7","G7"]:
            self.layout.set(self.MAPPING[h], red)
        for h in ["H7"]:
            self.layout.set(self.MAPPING[h], lila)
        for h in ["I7"]:
            self.layout.set(self.MAPPING[h], green1)
        for h in ["J7"]:
            self.layout.set(self.MAPPING[h], green2)
        for h in ["D8","E8","F8"]:
            self.layout.set(self.MAPPING[h], red)
        for h in ["H8"]:
            self.layout.set(self.MAPPING[h], lila)
        for h in ["I8"]:
            self.layout.set(self.MAPPING[h], green1)
        for h in ["J8"]:
            self.layout.set(self.MAPPING[h], green2)
        for h in ["E9","F9"]:
            self.layout.set(self.MAPPING[h], red)
        for h in ["G9"]:
            self.layout.set(self.MAPPING[h], lila)
        for h in ["H9"]:
            self.layout.set(self.MAPPING[h], green1)
        for h in ["I9"]:
            self.layout.set(self.MAPPING[h], green2)
        for h in ["F10"]:
            self.layout.set(self.MAPPING[h], lila)
        for h in ["G10"]:
            self.layout.set(self.MAPPING[h], green1)
        for h in ["H10"]:
            self.layout.set(self.MAPPING[h], green2)

        self.layout.push_to_driver()
        time.sleep(10)


        
    def run_animation_single_color(self, duration = 5,color=(255,0,0)): 
        for i in range(1,self.ROWS+1):
            for j in range (0,self.COLS):

                le = chr(j+65)
                h = le+str(i)
                print (h)
                self.layout.set(self.MAPPING[h], color)

        self.layout.push_to_driver()

        time.sleep(duration)

        self.clear()

    def run_animation_xmas(self, duration = 0.01): 

        duration2 = 1#duration * 10

        for c in [COLORS.purple, COLORS.blue, COLORS.red, COLORS.green]:

            for i in range(1,self.ROWS+1):
                for j in range (0,self.COLS):

                    le = chr(j+65)
                    h = le+str(i)
                    print (h)
                    self.layout.set(self.MAPPING[h], c)

                self.layout.push_to_driver()

                time.sleep(duration)

            time.sleep(duration2)





        self.clear()
        
    def display_holdset(self, holdset="Hold Set A", duration=10, **kwds): 
        print ("Display holdset: " + str(holdset))

        with open('../problems/HoldSetup.json') as json_file: # FIXME: path 
            data = json.load(json_file)
            for hold in data[self.SETUP]:
                hs = (data[self.SETUP][hold]['HoldSet']) 
                color = COLORS.black
    
                if (hs == holdset):# FIXME
                        color = COLORS.green                    
    
                self.layout.set(self.MAPPING[hold], color)

                #self.set_hold (hold, color)
                #print "Orientation"
        
        self.layout.push_to_driver()

        wait_holdset_duration = duration # FIXME
        time.sleep(wait_holdset_duration)

        self.clear()
                
                
                
    def stop_animation(self):
        if self.animation is not None:
            self.animation.stop()
Exemplo n.º 11
0
def init_pixels(type, npixels = MOONBOARD_PIXELS_COUNT, brightness=BRIGHTNESS):
xx
    layout = Strip(type,  brightness=brightness)
    return layout
Exemplo n.º 12
0
class LedManager:
    ROWS = 18 
    COLS = 11
    NUM_PIXELS = ROWS*COLS
    DEFAULT_BRIGHTNESS = 100
    DEFAULT_COLOR = COLORS.blue

    with open(os.path.join(os.path.abspath(os.getcwd()),'src','led_mapping.json')) as json_file:
        MAPPING = json.load(json_file)
           
    def __init__(self, rows=ROWS, cols=COLS, brightness=DEFAULT_BRIGHTNESS):
        ROWS = rows 
        COLS = cols
        NUM_PIXELS = ROWS*COLS

        driver = PiWS281X(NUM_PIXELS)
        self.layout = Strip (driver, brightness=brightness,threadedUpdate=True)
        self.layout.cleanup_drivers()
        self.layout.start()

    def clear(self):
        self.layout.all_off()
        self.layout.push_to_driver()

    def set_led(self, led, color=DEFAULT_COLOR):
        self.layout.set(self.MAPPING[led], color)

    def send_to_leds(self):
        self.layout.push_to_driver()

    def draw_array(self, led_array):
        #Turn off all leds
        self.clear()

        for led in led_array:
            self.set_led(led)

        self.send_to_leds()