Пример #1
0
    def __init__(self, ipcon):
        self.okay = False
        self.ipcon = ipcon

        if not config.UID_LED_STRIP_BRICKLET:
            print("Not Configured: LED Strip (required)")
            return

        self.led_strip = LEDStrip(config.UID_LED_STRIP_BRICKLET, self.ipcon)

        try:
            self.led_strip.get_frame_duration()
            print("Found: LED Strip ({0})".format(
                config.UID_LED_STRIP_BRICKLET))
        except:
            print("Not Found: LED Strip ({0})".format(
                config.UID_LED_STRIP_BRICKLET))
            return

        self.kp = KeyPress(self.ipcon)
        self.speaker = PongSpeaker(self.ipcon)

        self.okay = True

        self.led_strip.set_frame_duration(40)
        self.led_strip.register_callback(
            self.led_strip.CALLBACK_FRAME_RENDERED, self.frame_rendered)

        self.init_game()
Пример #2
0
    def __init__(self, ipcon):
        self.okay = False
        self.ipcon = ipcon

        if not config.UID_LED_STRIP_BRICKLET:
            print("Not Configured: LED Strip (required)")
            return

        self.led_strip = LEDStrip(config.UID_LED_STRIP_BRICKLET, self.ipcon)

        try:
            self.led_strip.get_frame_duration()
            print("Found: LED Strip ({0})".format(
                config.UID_LED_STRIP_BRICKLET))
        except:
            print("Not Found: LED Strip ({0})".format(
                config.UID_LED_STRIP_BRICKLET))
            return

        for i in range(config.LED_ROWS * config.LED_COLS):
            r, g, b = colorsys.hsv_to_rgb(
                1.0 * i / (config.LED_ROWS * config.LED_COLS), 1, 0.1)
            self.rainbow[i] = (int(r * 255), int(g * 255), int(b * 255))

        self.okay = True

        self.update_frame_rate()
        self.led_strip.register_callback(
            self.led_strip.CALLBACK_FRAME_RENDERED, self.frame_rendered)
Пример #3
0
    def __init__(self, ipcon):
        self.letter_table = {}

        for form in letter_forms:
            if '|' in form:
                self.letter_table[form[-2]] = form[:-3].split('|')

        self.set_new_text('Starter Kit: Blinkenlights')

        self.okay = False
        self.ipcon = ipcon

        if not config.UID_LED_STRIP_BRICKLET:
            print("Not Configured: LED Strip (required)")
            return

        self.led_strip = LEDStrip(config.UID_LED_STRIP_BRICKLET, self.ipcon)

        try:
            self.led_strip.get_frame_duration()
            print("Found: LED Strip ({0})").format(config.UID_LED_STRIP_BRICKLET)
        except:
            print("Not Found: LED Strip ({0})").format(config.UID_LED_STRIP_BRICKLET)
            return

        self.okay = True

        self.update_frame_rate()
        self.led_strip.register_callback(self.led_strip.CALLBACK_FRAME_RENDERED,
                                         self.frame_rendered)
Пример #4
0
    def __init__(self, ipcon):
        self.okay = False
        self.ipcon = ipcon

        if not config.UID_LED_STRIP_BRICKLET:
            print("Not Configured: LED Strip (required)")
            return

        self.led_strip = LEDStrip(config.UID_LED_STRIP_BRICKLET, self.ipcon)

        try:
            self.led_strip.get_frame_duration()
            print("Found: LED Strip ({0})".format(config.UID_LED_STRIP_BRICKLET))
        except:
            print("Not Found: LED Strip ({0})".format(config.UID_LED_STRIP_BRICKLET))
            return

        self.kp = KeyPress(self.ipcon)
        self.display = TetrisSegmentDisplay(self.ipcon)
        self.speaker = TetrisSpeaker(self.ipcon)

        self.okay = True

        self.led_strip.set_frame_duration(40)
        self.led_strip.register_callback(self.led_strip.CALLBACK_FRAME_RENDERED,
                                         self.frame_rendered)

        self.init_game()
Пример #5
0
    def __init__(self, ipcon):
        self.okay = False
        self.ipcon = ipcon

        if not config.UID_LED_STRIP_BRICKLET:
            print("Not Configured: LED Strip (required)")
            return

        self.led_strip = LEDStrip(config.UID_LED_STRIP_BRICKLET, self.ipcon)

        try:
            self.led_strip.get_frame_duration()
            print("Found: LED Strip ({0})".format(config.UID_LED_STRIP_BRICKLET))
        except:
            print("Not Found: LED Strip ({0})".format(config.UID_LED_STRIP_BRICKLET))
            return

        for i in range(config.LED_ROWS*config.LED_COLS):
            r, g, b = colorsys.hsv_to_rgb(1.0*i/(config.LED_ROWS*config.LED_COLS), 1, 0.1)
            self.rainbow[i] = (int(r*255), int(g*255), int(b*255))

        self.okay = True

        self.update_frame_rate()
        self.led_strip.register_callback(self.led_strip.CALLBACK_FRAME_RENDERED,
                                         self.frame_rendered)
Пример #6
0
    def __init__(self, ipcon):
        self.okay = False
        self.ipcon = ipcon

        if not config.UID_LED_STRIP_BRICKLET:
            print('Not Configured: LED Strip (required)')
            return

        self.led_strip = LEDStrip(config.UID_LED_STRIP_BRICKLET, self.ipcon)

        try:
            self.led_strip.get_frame_duration()
            print('Found: LED Strip ({0})'.format(config.UID_LED_STRIP_BRICKLET))
        except:
            print('Not Found: LED Strip ({0})'.format(config.UID_LED_STRIP_BRICKLET))
            return

        self.okay = True

        self.update_frame_rate()
        self.led_strip.register_callback(self.led_strip.CALLBACK_FRAME_RENDERED,
                                         self.frame_rendered)
Пример #7
0
 def cb_enumerate(self, uid, connected_uid, position, hardware_version, firmware_version, device_identifier, enumeration_type):
     if enumeration_type == IPConnection.ENUMERATION_TYPE_CONNECTED or enumeration_type == IPConnection.ENUMERATION_TYPE_AVAILABLE:
         if device_identifier == LEDStrip.DEVICE_IDENTIFIER and uid == self.UID_LED_STRIP_ONE: #LED-Strip 1
             try:
                 self.led_strip_1 = LEDStrip(uid, self.ipcon)
                 log.info('LED-Strip 1 initialized.')
             except Error as e:
                 log.error('LED-Strip 1 init failed: ' + str(e.description))
                 self.led_strip_1 = None
         elif device_identifier == LEDStrip.DEVICE_IDENTIFIER and uid == self.UID_LED_STRIP_TWO: #LED-Strip 2
             try:
                 self.led_strip_2 = LEDStrip(uid, self.ipcon)
                 log.info('LED-Strip 2 initialized.')
             except Error as e:
                 log.error('LED-Strip 2 init failed: ' + str(e.description))
                 self.led_strip_2 = None
         elif device_identifier == MultiTouch.DEVICE_IDENTIFIER: # MulitTouch for changing colors etc.
             try:
                 self.multi_touch = MultiTouch(uid, self.ipcon)
                 self.multi_touch.register_callback(self.multi_touch.CALLBACK_TOUCH_STATE, self.cb_buttons)
                 self.multi_touch.set_electrode_config(0x0FFF)
                 self.multi_touch.recalibrate()
                 log.info('Set proximity off.')
                 log.info('Multi-Touch initialized.')
             except Error as e:
                 log.error('Multi-Touch init failed: ' + str(e.description))
                 self.multi_touch = None
         elif device_identifier == RotaryPoti.DEVICE_IDENTIFIER: # Rotary Poti for picking a color or changing the saturation
             try:
                 self.rotary_poti = RotaryPoti(uid, self.ipcon)
                 self.rotary_poti.register_callback(self.rotary_poti.CALLBACK_POSITION, self.cb_position)
                 self.rotary_poti.set_position_callback_period(50)
                 log.info('Rotary Poti initialized.')
             except Error as e:
                 log.error('Rotary Poti init failed: ' + str(e.description))
                 self.rotary_poti = None
Пример #8
0
    def __init__(self, ipcon):
        self.okay = False
        self.ipcon = ipcon

        if not config.UID_LED_STRIP_BRICKLET:
            print("Not Configured: LED Strip or LED Strip V2 (required)")
            return

        if not config.IS_LED_STRIP_V2:
            self.led_strip = LEDStrip(config.UID_LED_STRIP_BRICKLET, self.ipcon)
        else:
            self.led_strip = LEDStripV2(config.UID_LED_STRIP_BRICKLET, self.ipcon)

        try:
            self.led_strip.get_frame_duration()
            if not config.IS_LED_STRIP_V2:
                print("Found: LED Strip ({0})".format(config.UID_LED_STRIP_BRICKLET))
            else:
                print("Found: LED Strip V2 ({0})".format(config.UID_LED_STRIP_BRICKLET))
        except:
            if not config.IS_LED_STRIP_V2:
                print("Not Found: LED Strip ({0})".format(config.UID_LED_STRIP_BRICKLET))
            else:
                print("Not Found: LED Strip V2({0})".format(config.UID_LED_STRIP_BRICKLET))
            return

        self.kp = KeyPress(self.ipcon)
        self.speaker = PongSpeaker(self.ipcon)

        self.okay = True

        self.led_strip.set_frame_duration(40)

        if not config.IS_LED_STRIP_V2:
            self.led_strip.register_callback(self.led_strip.CALLBACK_FRAME_RENDERED,
                                             self.frame_rendered)
        else:
            self.led_strip.register_callback(self.led_strip.CALLBACK_FRAME_STARTED,
                                             self.frame_rendered)

        self.led_strip.set_channel_mapping(config.CHANNEL_MAPPING)

        self.init_game()
Пример #9
0
class Text:
    leds = [x[:] for x in [[(0, 0, 0)]*config.LED_COLS]*config.LED_ROWS]
    text_position = 0
    rainbow_length = 32
    rainbow_index = 0

    def __init__(self, ipcon):
        self.letter_table = {}

        for form in letter_forms:
            if '|' in form:
                self.letter_table[form[-2]] = form[:-3].split('|')

        self.set_new_text('Starter Kit: Blinkenlights')

        self.okay = False
        self.ipcon = ipcon

        if not config.UID_LED_STRIP_BRICKLET:
            print("Not Configured: LED Strip (required)")
            return

        self.led_strip = LEDStrip(config.UID_LED_STRIP_BRICKLET, self.ipcon)

        try:
            self.led_strip.get_frame_duration()
            print("Found: LED Strip ({0})").format(config.UID_LED_STRIP_BRICKLET)
        except:
            print("Not Found: LED Strip ({0})").format(config.UID_LED_STRIP_BRICKLET)
            return

        self.okay = True

        self.update_frame_rate()
        self.led_strip.register_callback(self.led_strip.CALLBACK_FRAME_RENDERED,
                                         self.frame_rendered)

    def stop_rendering(self):
        if not self.okay:
            return

        self.led_strip.register_callback(self.led_strip.CALLBACK_FRAME_RENDERED,
                                         None)

    def update_frame_rate(self):
        if not self.okay:
            return

        self.led_strip.set_frame_duration(int(1000.0 / config.TEXT_FRAME_RATE))

    def set_new_text(self, text):
        text = '   ' + text
        self.text_cols = ['','','','','','','']

        for col in range(len(self.text_cols)):
            for c in text:
                try:
                    self.text_cols[col] += self.letter_table[c][col]
                except:
                    self.text_cols[col] += ' '

        self.text_position = 0

    def frame_rendered(self, _):
        self.frame_upload()
        self.frame_prepare_next()

    def frame_upload(self):
        if not self.okay:
            return

        # Reorder LED data into R, G and B channel
        r = []
        g = []
        b = []
        for row in range(config.LED_ROWS):
            col_range = range(config.LED_COLS)
            if row % 2 == 0:
                col_range = reversed(col_range)
            for col in col_range:
                r.append(self.leds[row][col][config.R_INDEX])
                g.append(self.leds[row][col][config.G_INDEX])
                b.append(self.leds[row][col][config.B_INDEX])

        # Make chunks of size 16
        r_chunk = [r[i:i+16] for i in range(0, len(r), 16)]
        g_chunk = [g[i:i+16] for i in range(0, len(g), 16)]
        b_chunk = [b[i:i+16] for i in range(0, len(b), 16)]

        for i in range(len(r_chunk)):
            length = len(r_chunk[i])

            # Fill up chunks with zeros
            r_chunk[i].extend([0]*(16-len(r_chunk[i])))
            g_chunk[i].extend([0]*(16-len(g_chunk[i])))
            b_chunk[i].extend([0]*(16-len(b_chunk[i])))

            try:
                self.led_strip.set_rgb_values(i*16, length, r_chunk[i], g_chunk[i], b_chunk[i])
            except:
                break

    def frame_prepare_next(self):
        self.leds = [x[:] for x in [[(0, 0, 0)]*config.LED_COLS]*config.LED_ROWS]

        if not config.TEXT_COLOR:
            r, g, b = colorsys.hsv_to_rgb(1.0*self.rainbow_index/self.rainbow_length, 1, 0.1)
            r, g, b = int(r*255), int(g*255), int(b*255)
            self.rainbow_index = (self.rainbow_index + 1) % self.rainbow_length
        else:
            r, g, b = config.TEXT_COLOR

        for col in range(len(self.text_cols)):
            for row in range(config.LED_ROWS):
                if self.text_cols[col][(self.text_position+row) % len(self.text_cols[0])] == 'X':
                    self.leds[row][col + 1] = (r, g, b)
                else:
                    self.leds[row][col + 1] = (0, 0, 0)

        self.text_position += 1
Пример #10
0
class Tetris:
    FIELD_ROWS = config.LED_ROWS+4 # 22 rows in playfield, with only 20 columns visible and 2 coloms border
    FIELD_COLS = config.LED_COLS+2 # 10 columns in playfield, 2 column border

    FIELD_ROW_START = 2
    FIELD_COL_START = 4

    COLORS = [
        ( 10,  10,  10), # grey
        (255,   0,   0), # red
        (255,  80,   0), # orange
        (255, 255,   0), # yellow
        (  0, 255,   0), # green
        (  0,   0, 255), # blue
        (255,   0, 150), # violet
        (255,   0,  40), # purple
    ]

    TETROMINOS = {
        None: [[[0], [0], [0], [0]]],

        'I': [[[0,0,0,0], [0,0,2,0], [0,0,0,0], [0,2,0,0]],
              [[2,2,2,2], [0,0,2,0], [0,0,0,0], [0,2,0,0]],
              [[0,0,0,0], [0,0,2,0], [2,2,2,2], [0,2,0,0]],
              [[0,0,0,0], [0,0,2,0], [0,0,0,0], [0,2,0,0]]],

        'J': [[[6,0,0], [0,6,6], [0,0,0], [0,6,0]],
              [[6,6,6], [0,6,0], [6,6,6], [0,6,0]],
              [[0,0,0], [0,6,0], [0,0,6], [6,6,0]]],

        'L': [[[0,0,5], [0,5,0], [0,0,0], [5,5,0]],
              [[5,5,5], [0,5,0], [5,5,5], [0,5,0]],
              [[0,0,0], [0,5,5], [5,0,0], [0,5,0]]],

        'O': [[[0,0,0,0], [0,0,0,0], [0,0,0,0], [0,0,0,0]],
              [[0,1,1,0], [0,1,1,0], [0,1,1,0], [0,1,1,0]],
              [[0,1,1,0], [0,1,1,0], [0,1,1,0], [0,1,1,0]]],

        'S': [[[0,3,3], [0,3,0], [0,0,0], [3,0,0]],
              [[3,3,0], [0,3,3], [0,3,3], [3,3,0]],
              [[0,0,0], [0,0,3], [3,3,0], [0,3,0]]],

        'T': [[[0,7,0], [0,7,0], [0,0,0], [0,7,0]],
              [[7,7,7], [0,7,7], [7,7,7], [7,7,0]],
              [[0,0,0], [0,7,0], [0,7,0], [0,7,0]]],

        'Z': [[[4,4,0], [0,0,4], [0,0,0], [0,4,0]],
              [[0,4,4], [0,4,4], [4,4,0], [4,4,0]],
              [[0,0,0], [0,4,0], [0,4,4], [4,0,0]]]
    }

    GAME_OVER_TEXT = [
        "GameOverGameOverGameOverGameOverGameOverGameOverGameOve",
        "                                                       ",
        "         GGGG                      OO                  ",
        "        G   GG                    O  O                 ",
        "        G      aaa  mmm mm   ee   O  O v   v  ee   rr  ",
        "        G  GG     a m  m  m e  e  O  O v   v e  e r  r ",
        "        G    G aaaa m  m  m eeee  O  O  v v  eeee r    ",
        "        G    G a  a m  m  m e     O  O  v v  e    r    ",
        "         GGGG  aaaa m  m  m  eee   OO    v    eee r    ",
        "                                                       ",
        "                                                       ",
        "GameOverGameOverGameOverGameOverGameOverGameOverGameOve"
    ]

    GAME_OVER_COLORS = {
        ' ': 0,
        'G': 1,
        'a': 2,
        'm': 3,
        'e': 4,
        'O': 5,
        'v': 6,
        'r': 7
    }

    drop_timer = None
    tetromino_current = 'O'
    tetromino_form = 0
    tetromino_pos_row = FIELD_ROW_START
    tetromino_pos_col = FIELD_COL_START
    playfield = [x[:] for x in [[0]*FIELD_COLS]*FIELD_ROWS]
    random_bag = ['O', 'I', 'S', 'Z', 'L', 'J', 'T']
    random_bag_index = len(random_bag)-1
    game_over_position = 0
    is_game_over = False
    loop = True

    def __init__(self, ipcon):
        self.okay = False
        self.ipcon = ipcon

        if not config.UID_LED_STRIP_BRICKLET:
            print("Not Configured: LED Strip or LED Strip V2 (required)")
            return

        if not config.IS_LED_STRIP_V2:
            self.led_strip = LEDStrip(config.UID_LED_STRIP_BRICKLET, self.ipcon)
        else:
            self.led_strip = LEDStripV2(config.UID_LED_STRIP_BRICKLET, self.ipcon)

        try:
            self.led_strip.get_frame_duration()
            if not config.IS_LED_STRIP_V2:
                print("Found: LED Strip ({0})".format(config.UID_LED_STRIP_BRICKLET))
            else:
                print("Found: LED Strip V2 ({0})".format(config.UID_LED_STRIP_BRICKLET))
        except:
            if not config.IS_LED_STRIP_V2:
                print("Not Found: LED Strip ({0})".format(config.UID_LED_STRIP_BRICKLET))
            else:
                print("Not Found: LED Strip V2({0})".format(config.UID_LED_STRIP_BRICKLET))
            return

        self.kp = KeyPress(self.ipcon)
        self.display = TetrisSegmentDisplay(self.ipcon)
        self.speaker = TetrisSpeaker(self.ipcon)

        self.okay = True

        self.led_strip.set_frame_duration(40)
        if not config.IS_LED_STRIP_V2:
            self.led_strip.register_callback(self.led_strip.CALLBACK_FRAME_RENDERED,
                                             self.frame_rendered)
        else:
            self.led_strip.register_callback(self.led_strip.CALLBACK_FRAME_STARTED,
                                             self.frame_rendered)

        self.led_strip.set_channel_mapping(config.CHANNEL_MAPPING)

        self.init_game()

    def init_game(self):
        self.tetromino_current = 'O'
        self.tetromino_form = 0
        self.tetromino_pos_row = self.FIELD_ROW_START
        self.tetromino_pos_col = self.FIELD_COL_START

        # Add border to playfield
        self.playfield = [x[:] for x in [[0]*self.FIELD_COLS]*self.FIELD_ROWS]
        self.playfield[0] = [255]*self.FIELD_COLS
        self.playfield[-1] = [255]*self.FIELD_COLS
        for col in self.playfield[1:-1]:
            col[0] = 255
            col[-1] = 255

        # initialize current tetronimo randomly
        self.tetromino_current = self.get_random_tetromino()
        self.is_game_over = False
        if self.drop_timer:
            self.drop_timer.interval = 1

    def frame_rendered(self, length):
        self.write_playfield()

    # See http://tetris.wikia.com/wiki/Random_Generator for
    # details of random bag implementation according to tetris specification
    def get_random_tetromino(self):
        self.random_bag_index += 1
        if self.random_bag_index >= len(self.random_bag):
            self.random_bag_index = 0
            random.shuffle(self.random_bag)

        return self.random_bag[self.random_bag_index]

    def add_tetromino_to_field(self, field, pos_row, pos_col, tetromino, form):
        for index_col, col in enumerate(self.TETROMINOS[tetromino]):
            for index_row, color in enumerate(col[form]):
                if color != 0:
                    row = pos_row + index_row
                    col = pos_col + index_col
                    if row >= 0 and row < self.FIELD_ROWS and col >= 0 and col < self.FIELD_COLS:
                        field[row][col] = color

    def tetromino_fits(self, field, pos_row, pos_col, tetromino, form):
        for index_col, col in enumerate(self.TETROMINOS[tetromino]):
            for index_row, color in enumerate(col[form]):
                if color != 0:
                    row = pos_row + index_row
                    col = pos_col + index_col
                    if row >= 0 and row < self.FIELD_ROWS and col >= 0 and col < self.FIELD_COLS:
                        if field[row][col] != 0:
                            return False
        return True

    def write_playfield(self):
        if not self.okay:
            return

        field = copy.deepcopy(self.playfield)
        if not self.is_game_over:
            self.add_tetromino_to_field(field, self.tetromino_pos_row,
                                        self.tetromino_pos_col,
                                        self.tetromino_current,
                                        self.tetromino_form)

        # Reorder LED data into R, G and B channel
        r = []
        g = []
        b = []
        frame = []

        for row in reversed(range(3, self.FIELD_ROWS-1)):
            col_range = range(1, self.FIELD_COLS-1)
            if row % 2 == 0:
                col_range = reversed(col_range)
            for col in col_range:
                r.append(self.COLORS[field[row][col]][0])
                g.append(self.COLORS[field[row][col]][1])
                b.append(self.COLORS[field[row][col]][2])
                frame.append(self.COLORS[field[row][col]][0])
                frame.append(self.COLORS[field[row][col]][1])
                frame.append(self.COLORS[field[row][col]][2])

        if not config.IS_LED_STRIP_V2:
            # Make chunks of size 16
            r_chunk = [r[i:i+16] for i in range(0, len(r), 16)]
            g_chunk = [g[i:i+16] for i in range(0, len(g), 16)]
            b_chunk = [b[i:i+16] for i in range(0, len(b), 16)]

            for i in range(len(r_chunk)):
                length = len(r_chunk[i])

                # Fill up chunks with zeros
                r_chunk[i].extend([0]*(16-len(r_chunk[i])))
                g_chunk[i].extend([0]*(16-len(g_chunk[i])))
                b_chunk[i].extend([0]*(16-len(b_chunk[i])))

                try:
                    self.led_strip.set_rgb_values(i*16, length, r_chunk[i], g_chunk[i], b_chunk[i])
                except:
                    break
        else:
            try:
                self.led_strip.set_led_values(0, frame)
            except:
                return

    def clear_lines(self, rows_to_clear):
        if not self.okay:
            return

        self.drop_timer.stop()
        rows_save = {}

        for to_clear in rows_to_clear:
            rows_save[to_clear] = self.playfield[to_clear]

        self.display.increase_line_count(len(rows_to_clear))
        self.speaker.beep_delete_line(len(rows_to_clear))

        for i in range(6):
            if i % 2 == 0:
                for to_clear in rows_to_clear:
                    self.playfield[to_clear] = [255] + [0]*(self.FIELD_COLS-2) + [255]
            else:
                for to_clear in rows_to_clear:
                    self.playfield[to_clear] = rows_save[to_clear]

            time.sleep(0.1)

        for to_clear in rows_to_clear:
            for row in reversed(range(1, to_clear+1)):
                self.playfield[row] = self.playfield[row-1]

            self.playfield[1] = [255] + [0]*(self.FIELD_COLS-2) + [255]

        self.drop_timer.start()

    def check_for_lines_to_clear(self):
        rows_to_clear = []

        for row_index, col in enumerate(self.playfield[1:-1]):
            to_clear = True

            for color in col[1:-1]:
                if color == 0:
                    to_clear = False
                    break

            if to_clear:
                rows_to_clear.append(row_index+1)

        if len(rows_to_clear) > 0:
            self.clear_lines(rows_to_clear)

    def new_tetromino(self):
        self.add_tetromino_to_field(self.playfield, self.tetromino_pos_row,
                                    self.tetromino_pos_col, self.tetromino_current,
                                    self.tetromino_form)
        self.tetromino_current = None

        self.check_for_lines_to_clear()

        self.tetromino_current = self.get_random_tetromino()
        self.tetromino_pos_row = self.FIELD_ROW_START
        self.tetromino_pos_col = self.FIELD_COL_START
        self.tetromino_form = 0

        if not self.tetromino_fits(self.playfield, self.tetromino_pos_row,
                                   self.tetromino_pos_col, self.tetromino_current,
                                   self.tetromino_form):
            self.is_game_over = True
            self.game_over_position = 0
            self.drop_timer.interval = 0.15

    def next_game_over_step(self):
        for row in range(len(self.GAME_OVER_TEXT)):
            for col in range(config.LED_COLS):
                k = (self.game_over_position+col) % len(self.GAME_OVER_TEXT[0])
                self.playfield[7+row][1+col] = self.GAME_OVER_COLORS[self.GAME_OVER_TEXT[row][k]]

        self.game_over_position += 1

    def drop_tetromino(self):
        if self.is_game_over:
            self.next_game_over_step()
            return

        if self.tetromino_fits(self.playfield, self.tetromino_pos_row+1,
                               self.tetromino_pos_col, self.tetromino_current,
                               self.tetromino_form):
            self.tetromino_pos_row += 1
        else:
            self.new_tetromino()

    def move_tetromino(self, row, col, form):
        if self.is_game_over:
            return

        if self.tetromino_fits(self.playfield, self.tetromino_pos_row+row,
                               self.tetromino_pos_col+col, self.tetromino_current, form):
            self.tetromino_pos_row += row
            self.tetromino_pos_col += col
            self.tetromino_form = form

            if row > 0:
                # restart drop timer, so we don't drop two tetrominos in a row
                self.drop_timer.stop()
                self.drop_timer.start()
        elif row == 1: # user is at bottom and hits button to go down again
            self.new_tetromino()

    def run_game_loop(self):
        self.frame_rendered(0)

        self.drop_timer = RepeatedTimer(1.0, self.drop_tetromino)

        while self.loop:
            key = self.kp.read_single_keypress()

            if key == 'a':
                self.speaker.beep_input()
                self.move_tetromino(0, -1, self.tetromino_form)
            elif key == 'd':
                self.speaker.beep_input()
                self.move_tetromino(0, 1, self.tetromino_form)
            elif key == 's':
                self.speaker.beep_input()
                self.move_tetromino(1, 0, self.tetromino_form)
            elif key == 'k':
                self.speaker.beep_input()
                self.move_tetromino(0, 0, (self.tetromino_form-1) % 4)
            elif key == 'l':
                self.speaker.beep_input()
                self.move_tetromino(0, 0, (self.tetromino_form+1) % 4)
            elif key == 'r':
                self.init_game()
            elif not config.HAS_GUI and key == 'q':
                break

        if not config.IS_LED_STRIP_V2:
            self.led_strip.register_callback(self.led_strip.CALLBACK_FRAME_RENDERED, None)
        else:
            self.led_strip.register_callback(self.led_strip.CALLBACK_FRAME_STARTED, None)

        self.drop_timer.stop()
        self.kp.stop()
Пример #11
0
class Pong:
    PADDLE_SIZE = 3

# Antialased ball?
#    PONG_COLOR_INDEX_BALL_TOP = 8
#    PONG_COLOR_INDEX_BALL_LEFT = 9
#    PONG_COLOR_INDEX_BALL_RIGHT = 10
#    PONG_COLOR_INDEX_BALL_BOTTOM = 11

    COLORS = [
        (  0,   0,   0), # off
#       ( 10,  10,  10), # grey
        (255,   0,   0), # red
        (255,  80,   0), # orange
        (255, 255,   0), # yellow
        (  0, 255,   0), # green
        (  0,   0, 255), # blue
        (255,   0, 150), # violet
        (255,   0,  40), # purple
        (  0,   0,   0), # ball top
        (  0,   0,   0), # ball left
        (  0,   0,   0), # ball right
        (  0,   0,   0)  # ball bottom
    ]

    SCORE_FONT = {
        0: ["222",
            "202",
            "202",
            "202",
            "222"],
        1: ["020",
            "020",
            "020",
            "020",
            "020"],
        2: ["222",
            "002",
            "222",
            "200",
            "222"],
        3: ["222",
            "002",
            "222",
            "002",
            "222"],
        4: ["202",
            "202",
            "222",
            "002",
            "002"],
        5: ["222",
            "200",
            "222",
            "002",
            "222"],
        6: ["222",
            "200",
            "222",
            "202",
            "222"],
        7: ["222",
            "002",
            "002",
            "002",
            "002"],
        8: ["222",
            "202",
            "222",
            "202",
            "222"],
        9: ["222",
            "202",
            "222",
            "002",
            "002"],
    }

    playfield = [x[:] for x in [[0]*config.LED_COLS]*config.LED_ROWS]
    score = [0, 0]
    paddle_position_x = [4, 15]
    paddle_position_y = [3, 3]
    ball_position = [10, 5]
    ball_direction = [0.1, 0.2]
    timer = None
    loop = True

    def __init__(self, ipcon):
        self.okay = False
        self.ipcon = ipcon

        if not config.UID_LED_STRIP_BRICKLET:
            print("Not Configured: LED Strip or LED Strip V2 (required)")
            return

        if not config.IS_LED_STRIP_V2:
            self.led_strip = LEDStrip(config.UID_LED_STRIP_BRICKLET, self.ipcon)
        else:
            self.led_strip = LEDStripV2(config.UID_LED_STRIP_BRICKLET, self.ipcon)

        try:
            self.led_strip.get_frame_duration()
            if not config.IS_LED_STRIP_V2:
                print("Found: LED Strip ({0})".format(config.UID_LED_STRIP_BRICKLET))
            else:
                print("Found: LED Strip V2 ({0})".format(config.UID_LED_STRIP_BRICKLET))
        except:
            if not config.IS_LED_STRIP_V2:
                print("Not Found: LED Strip ({0})".format(config.UID_LED_STRIP_BRICKLET))
            else:
                print("Not Found: LED Strip V2({0})".format(config.UID_LED_STRIP_BRICKLET))
            return

        self.kp = KeyPress(self.ipcon)
        self.speaker = PongSpeaker(self.ipcon)

        self.okay = True

        self.led_strip.set_frame_duration(40)

        if not config.IS_LED_STRIP_V2:
            self.led_strip.register_callback(self.led_strip.CALLBACK_FRAME_RENDERED,
                                             self.frame_rendered)
        else:
            self.led_strip.register_callback(self.led_strip.CALLBACK_FRAME_STARTED,
                                             self.frame_rendered)

        self.led_strip.set_channel_mapping(config.CHANNEL_MAPPING)

        self.init_game()

    def init_game(self):
        self.new_ball()
        self.paddle_position_y = [3, 3]
        self.score = [0, 0]

    def frame_rendered(self, length):
        self.write_playfield()

    def write_playfield(self):
        if not self.okay:
            return

        field = copy.deepcopy(self.playfield)

        self.add_score_to_playfield(field)
        self.add_paddles_to_playfield(field)
        self.add_ball_to_playfield(field)

        # Reorder LED data into R, G and B channel
        r = []
        g = []
        b = []
        frame = []

        for row in range(config.LED_ROWS):
            col_range = range(config.LED_COLS)
            if row % 2 == 0:
                col_range = reversed(col_range)
            for col in col_range:
                r.append(self.COLORS[field[row][col]][0])
                g.append(self.COLORS[field[row][col]][1])
                b.append(self.COLORS[field[row][col]][2])
                frame.append(self.COLORS[field[row][col]][0])
                frame.append(self.COLORS[field[row][col]][1])
                frame.append(self.COLORS[field[row][col]][2])

        if not config.IS_LED_STRIP_V2:
            # Make chunks of size 16
            r_chunk = [r[i:i+16] for i in range(0, len(r), 16)]
            g_chunk = [g[i:i+16] for i in range(0, len(g), 16)]
            b_chunk = [b[i:i+16] for i in range(0, len(b), 16)]

            for i in range(len(r_chunk)):
                length = len(r_chunk[i])

                # Fill up chunks with zeros
                r_chunk[i].extend([0]*(16-len(r_chunk[i])))
                g_chunk[i].extend([0]*(16-len(g_chunk[i])))
                b_chunk[i].extend([0]*(16-len(b_chunk[i])))

                try:
                    self.led_strip.set_rgb_values(i*16, length, r_chunk[i], g_chunk[i], b_chunk[i])
                except:
                    break
        else:
            try:
                self.led_strip.set_led_values(0, frame)
            except:
                return

    def add_score_to_playfield(self, field):
        for row in range(3):
            for col in range(5):
                field[row][col+1] = int(self.SCORE_FONT[self.score[0]][col][row])
                field[row+17][col+1] = int(self.SCORE_FONT[self.score[1]][col][row])

    def add_ball_to_playfield(self, field):
        x = max(0, min(19, int(self.ball_position[0])))
        y = max(0, min(9, int(self.ball_position[1])))
        field[x][y] = config.PONG_COLOR_INDEX_BALL

# Antialased ball?
#        x = max(0, min(19, self.ball_position[0]))
#        y = max(0, min(9, self.ball_position[1]))
#        ix = int(x)
#        iy = int(y)
#        field[ix][iy] = config.PONG_COLOR_INDEX_BALL
#        if ix + 1 < config.LED_ROWS:
#            field[ix+1][iy] = PONG_COLOR_INDEX_BALL_RIGHT
#        if ix - 1 > 0:
#            field[ix-1][iy] = PONG_COLOR_INDEX_BALL_LEFT
#        if iy + 1 < config.LED_COLS:
#            field[ix][iy+1] = PONG_COLOR_INDEX_BALL_TOP
#        if iy - 1 > 0:
#            field[ix][iy-1] = PONG_COLOR_INDEX_BALL_BOTTOM
#
#        dx = x - int(x)
#        dy = x - int(x)
#        self.COLORS[PONG_COLOR_INDEX_BALL_RIGHT] = (0, 255*dx/64, 0)
#        self.COLORS[PONG_COLOR_INDEX_BALL_LEFT] = (0, 255*(1-dx)/64, 0)
#        self.COLORS[PONG_COLOR_INDEX_BALL_TOP] = (0, 255*dy/64, 0)
#        self.COLORS[PONG_COLOR_INDEX_BALL_BOTTOM] = (0, 255*(1-dy)/64, 0)

    def add_paddles_to_playfield(self, field):
        for player in range(2):
            for i in range(self.PADDLE_SIZE):
                field[self.paddle_position_x[player]][self.paddle_position_y[player]+i] = config.PONG_COLOR_INDEX_PLAYER[player]

    def move_paddle(self, player, change):
        new_pos = self.paddle_position_y[player] + change
        if new_pos >= 0 and new_pos <= config.LED_COLS - self.PADDLE_SIZE:
            self.paddle_position_y[player] = new_pos

    def new_ball(self):
        self.ball_position = [(config.LED_ROWS - 1.0) / 2.0, (config.LED_COLS - 1.0) / 2.0]
        self.ball_direction = [random.choice([-0.2, 0.2]), random.choice([random.randrange(1, 9)/10.0, random.randrange(-9, -1)/10.0])]

    def tick(self):
        # Move ball
        for i in range(2):
            self.ball_position[i] += self.ball_direction[i]

        # Wall collision top/bottom
        if self.ball_position[1] < 0 or self.ball_position[1] >= config.LED_COLS:
            self.ball_direction[1] = -self.ball_direction[1]

        # Wall collision left/right
        def hit_left_right(player):
            self.speaker.beep_sirene()
            self.new_ball()

            self.score[player] += 1
            if self.score[player] > 9:
                self.score[player] = 0

        if self.ball_position[0] < 0:
            hit_left_right(1)

        if self.ball_position[0] >= config.LED_ROWS:
            hit_left_right(0)

        # Paddle collision
        def hit_paddle(skew):
            self.speaker.beep_paddle_hit()
            self.ball_direction[0] = -self.ball_direction[0]
            self.ball_direction[1] -= skew
            for i in range(2):
                self.ball_direction[i] *= 1.1 # Increase speed

        if self.ball_direction[0] < 0:
            if self.paddle_position_x[0] + 0.5 <= self.ball_position[0] <= self.paddle_position_x[0] + 1.5:
                if self.paddle_position_y[0] - 0.5 <= self.ball_position[1] <= self.paddle_position_y[0] + self.PADDLE_SIZE + 0.5:
                    paddle_skew = (self.paddle_position_y[0] + self.PADDLE_SIZE/2.0 - self.ball_position[1])/10.0
                    hit_paddle(paddle_skew)

        if self.ball_direction[0] > 0:
            if self.paddle_position_x[1] - 0.5 <= self.ball_position[0] <= self.paddle_position_x[1] + 0.5:
                if self.paddle_position_y[1] - 0.5 <= self.ball_position[1] <= self.paddle_position_y[1] + self.PADDLE_SIZE + 0.5:
                    paddle_skew = (self.paddle_position_y[1] + self.PADDLE_SIZE/2.0 - self.ball_position[1])/10.0
                    hit_paddle(paddle_skew)

    def run_game_loop(self):
        self.frame_rendered(0)

        self.timer = RepeatedTimer(0.1, self.tick)

        while self.loop:
            key = self.kp.read_single_keypress().lower()

            if key == 'a':
                self.move_paddle(0, -1)
            elif key == 's':
                self.move_paddle(0, 1)
            elif key == 'k':
                self.move_paddle(1, -1)
            elif key == 'l':
                self.move_paddle(1, 1)
            elif key == 'r':
                self.init_game()
            elif not config.HAS_GUI and key == 'q':
                break

        if not config.IS_LED_STRIP_V2:
            self.led_strip.register_callback(self.led_strip.CALLBACK_FRAME_RENDERED, None)
        else:
            self.led_strip.register_callback(self.led_strip.CALLBACK_FRAME_STARTED, None)

        self.timer.stop()
        self.kp.stop()
Пример #12
0
class Fire:
    values = [
        [ 32,  16,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,  16,  32],
        [ 64,  32,  16,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,  16,  32,  64],
        [ 96,  64,  32,  32,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,  32,  32,  64,  96],
        [128,  96,  64,  64,  32,  32,   0,   0,   0,   0,   0,   0,   0,   0,  32,  32,  64,  64,  96, 128],
        [160, 128,  96,  96,  64,  64,  32,  32,   0,   0,   0,   0,  32,  32,  64,  64,  96,  96, 128, 160],
        [192, 160, 128, 128,  96,  96,  64,  64,  32,   0,   0,  32,  64,  64,  96,  96, 128, 128, 160, 192],
        [255, 192, 160, 160, 128, 128,  96,  96,  64,  32,  32,  64,  96,  96, 128, 128, 160, 160, 192, 255],
        [255, 255, 192, 192, 160, 160, 128, 128,  96,  64,  64,  96, 128, 128, 160, 160, 192, 192, 255, 255],
        [255, 255, 255, 255, 192, 192, 160, 160, 128,  96,  96, 128, 160, 160, 192, 192, 255, 255, 255, 255],
        [255, 255, 255, 255, 255, 255, 192, 192, 160, 128, 128, 160, 192, 192, 255, 255, 255, 255, 255, 255]
    ]

    hues = [
        [1, 3, 4, 5, 7, 8, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 6, 4, 3, 1],
        [1, 2, 3, 3, 5, 6, 7, 7, 8, 8, 8, 8, 9, 9, 8, 7, 5, 3, 2, 1],
        [1, 2, 3, 3, 5, 5, 6, 6, 5, 6, 6, 7, 7, 7, 6, 6, 4, 3, 2, 1],
        [1, 1, 2, 3, 4, 4, 5, 5, 4, 4, 5, 5, 6, 5, 5, 5, 3, 2, 1, 1],
        [1, 1, 2, 2, 4, 4, 4, 4, 4, 4, 5, 5, 4, 4, 4, 4, 2, 2, 1, 1],
        [0, 0, 1, 1, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 1, 1, 0, 0],
        [0, 0, 0, 0, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
    ]

#    values = [
#        [ 32,   0,   0,   0,   0,   0,   0,   0,   0,  32],
#        [ 64,   0,   0,   0,   0,   0,   0,   0,   0,  64],
#        [ 96,  32,   0,   0,   0,   0,   0,   0,  32,  96],
#        [128,  64,  32,   0,   0,   0,   0,  32,  64, 128],
#        [160,  96,  64,  32,   0,   0,  32,  64,  96, 160],
#        [192, 128,  96,  64,  32,  32,  64,  96, 128, 192],
#        [255, 160, 128,  96,  64,  64,  96, 128, 160, 255],
#        [255, 192, 160, 128,  96,  96, 128, 160, 192, 255],
#        [255, 255, 192, 160, 128, 128, 160, 192, 255, 255],
#        [255, 255, 255, 192, 160, 160, 192, 255, 255, 255]
#    ]

#    hues = [
#        [1, 4, 7, 9, 9, 9, 9, 8, 4, 1],
#        [1, 3, 5, 7, 8, 8, 9, 7, 3, 1],
#        [1, 3, 5, 6, 5, 6, 7, 6, 3, 1],
#        [1, 2, 4, 5, 4, 5, 5, 5, 2, 1],
#        [1, 2, 4, 4, 4, 5, 4, 4, 2, 1],
#        [0, 1, 2, 3, 3, 3, 3, 2, 1, 0],
#        [0, 0, 1, 2, 2, 2, 2, 1, 0, 0],
#        [0, 0, 0, 1, 1, 1, 1, 0, 0, 0],
#        [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
#        [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
#    ]

    line = [0]*config.LED_ROWS
    matrix = [x[:] for x in [[0]*config.LED_COLS]*config.LED_ROWS]
    leds = [x[:] for x in [[(0, 0, 0)]*config.LED_COLS]*config.LED_ROWS]
    percent = 0

    def __init__(self, ipcon):
        self.okay = False
        self.ipcon = ipcon

        if not config.UID_LED_STRIP_BRICKLET:
            print('Not Configured: LED Strip (required)')
            return

        self.led_strip = LEDStrip(config.UID_LED_STRIP_BRICKLET, self.ipcon)

        try:
            self.led_strip.get_frame_duration()
            print('Found: LED Strip ({0})'.format(config.UID_LED_STRIP_BRICKLET))
        except:
            print('Not Found: LED Strip ({0})'.format(config.UID_LED_STRIP_BRICKLET))
            return

        self.okay = True

        self.update_frame_rate()
        self.led_strip.register_callback(self.led_strip.CALLBACK_FRAME_RENDERED,
                                         self.frame_rendered)

    def stop_rendering(self):
        if not self.okay:
            return

        self.led_strip.register_callback(self.led_strip.CALLBACK_FRAME_RENDERED,
                                         None)

    def update_frame_rate(self):
        if not self.okay:
            return

        self.led_strip.set_frame_duration(int(1000.0 / config.FIRE_FRAME_RATE))

    def frame_rendered(self, _):
        self.frame_upload()
        self.frame_prepare_next()

    def frame_upload(self):
        if not self.okay:
            return

        # Reorder LED data into R, G and B channel
        r = []
        g = []
        b = []
        for row in range(config.LED_ROWS):
            col_range = range(config.LED_COLS)
            if row % 2 == 0:
                col_range = reversed(col_range)
            for col in col_range:
                r.append(self.leds[row][col][config.R_INDEX])
                g.append(self.leds[row][col][config.G_INDEX])
                b.append(self.leds[row][col][config.B_INDEX])

        # Make chunks of size 16
        r_chunk = [r[i:i+16] for i in range(0, len(r), 16)]
        g_chunk = [g[i:i+16] for i in range(0, len(g), 16)]
        b_chunk = [b[i:i+16] for i in range(0, len(b), 16)]

        for i in range(len(r_chunk)):
            length = len(r_chunk[i])

            # Fill up chunks with zeros
            r_chunk[i].extend([0]*(16-len(r_chunk[i])))
            g_chunk[i].extend([0]*(16-len(g_chunk[i])))
            b_chunk[i].extend([0]*(16-len(b_chunk[i])))

            try:
                self.led_strip.set_rgb_values(i*16, length, r_chunk[i], g_chunk[i], b_chunk[i])
            except:
                break

    def frame_prepare_next(self):
        def shift_up():
            for y in reversed(range(1, config.LED_COLS)):
                for x in range(config.LED_ROWS):
                    self.matrix[x][y] = self.matrix[x][y-1]

            for x in range(config.LED_ROWS):
                self.matrix[x][0] = self.line[x]

        def generate_line():
            start = min(config.FIRE_RAND_VALUE_START, config.FIRE_RAND_VALUE_END)
            end = config.FIRE_RAND_VALUE_END

            for x in range(config.LED_ROWS):
                self.line[x] = random.randint(start, end)

        def make_frame():
            def hsv_to_rgb(h, s, v):
                r, g, b = colorsys.hsv_to_rgb(h/255.0, s/255.0, v/255.0)
                return ((int(255*r), int(255*g), int(255*b)))

            def interpolate2(x, y):
                p0 = 100.0 - self.percent
                p1 = self.percent
                m0 = self.matrix[x][y]
                m1 = self.matrix[x][y-1]

                return (p0*m0 + p1*m1) / 100.0

            def interpolate1(x):
                p0 = 100.0 - self.percent
                p1 = self.percent
                m0 = self.matrix[x][0]
                m1 = self.line[x]

                return (p0*m0 + p1*m1) / 100.0

            for y in reversed(range(1, config.LED_COLS)):
                for x in range(config.LED_ROWS):
                    rgb = hsv_to_rgb(self.hues[y][x]*config.FIRE_HUE_FACTOR, 255,
                                     max(0, interpolate2(x, y) - self.values[y][x]))
                    self.leds[x][config.LED_COLS-1-y] = rgb

            for x in range(config.LED_ROWS):
                rgb = hsv_to_rgb(self.hues[0][x]*config.FIRE_HUE_FACTOR, 255,
                                 max(0, interpolate1(x)))
                self.leds[x][config.LED_COLS-1] = rgb

        self.percent += 20
        if self.percent >= 100:
            shift_up()
            generate_line()
            self.percent = 0

        make_frame()
Пример #13
0
class Pong:
    PADDLE_SIZE = 3

    # Antialased ball?
    #    PONG_COLOR_INDEX_BALL_TOP = 8
    #    PONG_COLOR_INDEX_BALL_LEFT = 9
    #    PONG_COLOR_INDEX_BALL_RIGHT = 10
    #    PONG_COLOR_INDEX_BALL_BOTTOM = 11

    COLORS = [
        (0, 0, 0),  # off
        #       ( 10,  10,  10), # grey
        (255, 0, 0),  # red
        (255, 80, 0),  # orange
        (255, 255, 0),  # yellow
        (0, 255, 0),  # green
        (0, 0, 255),  # blue
        (255, 0, 150),  # violet
        (255, 0, 40),  # purple
        (0, 0, 0),  # ball top
        (0, 0, 0),  # ball left
        (0, 0, 0),  # ball right
        (0, 0, 0)  # ball bottom
    ]

    SCORE_FONT = {
        0: ["222", "202", "202", "202", "222"],
        1: ["020", "020", "020", "020", "020"],
        2: ["222", "002", "222", "200", "222"],
        3: ["222", "002", "222", "002", "222"],
        4: ["202", "202", "222", "002", "002"],
        5: ["222", "200", "222", "002", "222"],
        6: ["222", "200", "222", "202", "222"],
        7: ["222", "002", "002", "002", "002"],
        8: ["222", "202", "222", "202", "222"],
        9: ["222", "202", "222", "002", "002"],
    }

    playfield = [x[:] for x in [[0] * config.LED_COLS] * config.LED_ROWS]
    score = [0, 0]
    paddle_position_x = [4, 15]
    paddle_position_y = [3, 3]
    ball_position = [10, 5]
    ball_direction = [0.1, 0.2]
    timer = None
    loop = True

    def __init__(self, ipcon):
        self.okay = False
        self.ipcon = ipcon

        if not config.UID_LED_STRIP_BRICKLET:
            print("Not Configured: LED Strip (required)")
            return

        self.led_strip = LEDStrip(config.UID_LED_STRIP_BRICKLET, self.ipcon)

        try:
            self.led_strip.get_frame_duration()
            print("Found: LED Strip ({0})".format(
                config.UID_LED_STRIP_BRICKLET))
        except:
            print("Not Found: LED Strip ({0})".format(
                config.UID_LED_STRIP_BRICKLET))
            return

        self.kp = KeyPress(self.ipcon)
        self.speaker = PongSpeaker(self.ipcon)

        self.okay = True

        self.led_strip.set_frame_duration(40)
        self.led_strip.register_callback(
            self.led_strip.CALLBACK_FRAME_RENDERED, self.frame_rendered)

        self.init_game()

    def init_game(self):
        self.new_ball()
        self.paddle_position_y = [3, 3]
        self.score = [0, 0]

    def frame_rendered(self, length):
        self.write_playfield()

    def write_playfield(self):
        if not self.okay:
            return

        field = copy.deepcopy(self.playfield)

        self.add_score_to_playfield(field)
        self.add_paddles_to_playfield(field)
        self.add_ball_to_playfield(field)

        # Reorder LED data into R, G and B channel
        r = []
        g = []
        b = []
        for row in range(config.LED_ROWS):
            col_range = range(config.LED_COLS)
            if row % 2 == 0:
                col_range = reversed(col_range)
            for col in col_range:
                r.append(self.COLORS[field[row][col]][config.R_INDEX])
                g.append(self.COLORS[field[row][col]][config.G_INDEX])
                b.append(self.COLORS[field[row][col]][config.B_INDEX])

        # Make chunks of size 16
        r_chunk = [r[i:i + 16] for i in range(0, len(r), 16)]
        g_chunk = [g[i:i + 16] for i in range(0, len(g), 16)]
        b_chunk = [b[i:i + 16] for i in range(0, len(b), 16)]

        for i in range(len(r_chunk)):
            length = len(r_chunk[i])

            # Fill up chunks with zeros
            r_chunk[i].extend([0] * (16 - len(r_chunk[i])))
            g_chunk[i].extend([0] * (16 - len(g_chunk[i])))
            b_chunk[i].extend([0] * (16 - len(b_chunk[i])))

            try:
                self.led_strip.set_rgb_values(i * 16, length, r_chunk[i],
                                              g_chunk[i], b_chunk[i])
            except:
                break

    def add_score_to_playfield(self, field):
        for row in range(3):
            for col in range(5):
                field[row][col + 1] = int(
                    self.SCORE_FONT[self.score[0]][col][row])
                field[row + 17][col + 1] = int(
                    self.SCORE_FONT[self.score[1]][col][row])

    def add_ball_to_playfield(self, field):
        x = max(0, min(19, int(self.ball_position[0])))
        y = max(0, min(9, int(self.ball_position[1])))
        field[x][y] = config.PONG_COLOR_INDEX_BALL


# Antialased ball?
#        x = max(0, min(19, self.ball_position[0]))
#        y = max(0, min(9, self.ball_position[1]))
#        ix = int(x)
#        iy = int(y)
#        field[ix][iy] = config.PONG_COLOR_INDEX_BALL
#        if ix + 1 < config.LED_ROWS:
#            field[ix+1][iy] = PONG_COLOR_INDEX_BALL_RIGHT
#        if ix - 1 > 0:
#            field[ix-1][iy] = PONG_COLOR_INDEX_BALL_LEFT
#        if iy + 1 < config.LED_COLS:
#            field[ix][iy+1] = PONG_COLOR_INDEX_BALL_TOP
#        if iy - 1 > 0:
#            field[ix][iy-1] = PONG_COLOR_INDEX_BALL_BOTTOM
#
#        dx = x - int(x)
#        dy = x - int(x)
#        self.COLORS[PONG_COLOR_INDEX_BALL_RIGHT] = (0, 255*dx/64, 0)
#        self.COLORS[PONG_COLOR_INDEX_BALL_LEFT] = (0, 255*(1-dx)/64, 0)
#        self.COLORS[PONG_COLOR_INDEX_BALL_TOP] = (0, 255*dy/64, 0)
#        self.COLORS[PONG_COLOR_INDEX_BALL_BOTTOM] = (0, 255*(1-dy)/64, 0)

    def add_paddles_to_playfield(self, field):
        for player in range(2):
            for i in range(self.PADDLE_SIZE):
                field[self.paddle_position_x[player]][
                    self.paddle_position_y[player] +
                    i] = config.PONG_COLOR_INDEX_PLAYER[player]

    def move_paddle(self, player, change):
        new_pos = self.paddle_position_y[player] + change
        if new_pos >= 0 and new_pos <= config.LED_COLS - self.PADDLE_SIZE:
            self.paddle_position_y[player] = new_pos

    def new_ball(self):
        self.ball_position = [(config.LED_ROWS - 1.0) / 2.0,
                              (config.LED_COLS - 1.0) / 2.0]
        self.ball_direction = [
            random.choice([-0.2, 0.2]),
            random.choice([
                random.randrange(1, 9) / 10.0,
                random.randrange(-9, -1) / 10.0
            ])
        ]

    def tick(self):
        # Move ball
        for i in range(2):
            self.ball_position[i] += self.ball_direction[i]

        # Wall collision top/bottom
        if self.ball_position[1] < 0 or self.ball_position[
                1] >= config.LED_COLS:
            self.ball_direction[1] = -self.ball_direction[1]

        # Wall collision left/right
        def hit_left_right(player):
            self.speaker.beep_sirene()
            self.new_ball()

            self.score[player] += 1
            if self.score[player] > 9:
                self.score[player] = 0

        if self.ball_position[0] < 0:
            hit_left_right(1)

        if self.ball_position[0] >= config.LED_ROWS:
            hit_left_right(0)

        # Paddle collision
        def hit_paddle(skew):
            self.speaker.beep_paddle_hit()
            self.ball_direction[0] = -self.ball_direction[0]
            self.ball_direction[1] -= skew
            for i in range(2):
                self.ball_direction[i] *= 1.1  # Increase speed

        if self.ball_direction[0] < 0:
            if self.paddle_position_x[0] + 0.5 <= self.ball_position[
                    0] <= self.paddle_position_x[0] + 1.5:
                if self.paddle_position_y[0] - 0.5 <= self.ball_position[
                        1] <= self.paddle_position_y[
                            0] + self.PADDLE_SIZE + 0.5:
                    paddle_skew = (self.paddle_position_y[0] +
                                   self.PADDLE_SIZE / 2.0 -
                                   self.ball_position[1]) / 10.0
                    hit_paddle(paddle_skew)

        if self.ball_direction[0] > 0:
            if self.paddle_position_x[1] - 0.5 <= self.ball_position[
                    0] <= self.paddle_position_x[1] + 0.5:
                if self.paddle_position_y[1] - 0.5 <= self.ball_position[
                        1] <= self.paddle_position_y[
                            1] + self.PADDLE_SIZE + 0.5:
                    paddle_skew = (self.paddle_position_y[1] +
                                   self.PADDLE_SIZE / 2.0 -
                                   self.ball_position[1]) / 10.0
                    hit_paddle(paddle_skew)

    def run_game_loop(self):
        self.frame_rendered(0)

        self.timer = RepeatedTimer(0.1, self.tick)

        while self.loop:
            key = self.kp.read_single_keypress().lower()

            if key == 'a':
                self.move_paddle(0, -1)
            elif key == 's':
                self.move_paddle(0, 1)
            elif key == 'k':
                self.move_paddle(1, -1)
            elif key == 'l':
                self.move_paddle(1, 1)
            elif key == 'r':
                self.init_game()
            elif not config.HAS_GUI and key == 'q':
                break

        self.led_strip.register_callback(
            self.led_strip.CALLBACK_FRAME_RENDERED, None)
        self.timer.stop()
        self.kp.stop()
Пример #14
0
    def cb_enumerate(cls, uid, connected_uid, position, hardware_version,
                     firmware_version, device_identifier, enumeration_type):
        #global self.led
        found = False
        if enumeration_type == IPConnection.ENUMERATION_TYPE_CONNECTED or \
           enumeration_type == IPConnection.ENUMERATION_TYPE_AVAILABLE:
            # Enumeration for LED
            if device_identifier == LEDStrip.DEVICE_IDENTIFIER:
                cls.LEDs.append(LEDStrip(uid, cls.ipcon))
                temp_uid = str(cls.LEDs[-1].get_identity()[1]) + "." + str(
                    cls.LEDs[-1].get_identity()[0])
                cls.LEDList.addLED(cls.LEDs[-1], temp_uid)
                cls.LEDs[-1].set_frame_duration(200)
                if settings.LEDs.get(temp_uid) <> None:
                    cls.LEDs[-1].set_chip_type(settings.LEDs.get(temp_uid)[0])
                    cls.LEDs[-1].set_frame_duration(
                        settings.LEDs.get(temp_uid)[1])
                    found = True
                #self.led.register_callback(self.led.CALLBACK_FRAME_RENDERED,
                #                lambda x: __cb_frame_rendered__(self.led, x))
                #self.led.set_rgb_values(0, self.NUM_LEDS, self.r, self.g, self.b)
                #self.led.set_rgb_values(15, self.NUM_LEDS, self.r, self.g, self.b)
                #self.led.set_rgb_values(30, self.NUM_LEDS, self.r, self.g, self.b)

            if device_identifier == IO16.DEVICE_IDENTIFIER:
                cls.io.append(IO16(uid, cls.ipcon))
                temp_uid = str(cls.io[-1].get_identity()[1]) + "." + str(
                    cls.io[-1].get_identity()[0])
                cls.io16list.addIO(cls.io[-1], temp_uid, 16)
                cls.io[-1].set_debounce_period(100)
                if settings.IO16.get(temp_uid) <> None:
                    cls.io[-1].set_port_interrupt(
                        'a',
                        settings.IO16.get(temp_uid)[0])
                    cls.io[-1].set_port_interrupt(
                        'b',
                        settings.IO16.get(temp_uid)[1])
                    cls.io[-1].set_port_configuration(
                        'a',
                        settings.IO16.get(temp_uid)[0], 'i', True)
                    cls.io[-1].set_port_configuration(
                        'b',
                        settings.IO16.get(temp_uid)[1], 'i', True)
                    cls.io[-1].set_port_configuration(
                        'a',
                        settings.IO16.get(temp_uid)[2], 'o', False)
                    cls.io[-1].set_port_configuration(
                        'b',
                        settings.IO16.get(temp_uid)[3], 'o', False)
                    #self.io[-1].set_port_monoflop('a', tifo_config.IO16.get(temp_uid)[4],0,tifo_config.IO16.get(temp_uid)[6])
                    #self.io[-1].set_port_monoflop('b', tifo_config.IO16.get(temp_uid)[5],0,tifo_config.IO16.get(temp_uid)[6])
                    cls.io[-1].register_callback(
                        cls.io[-1].CALLBACK_INTERRUPT,
                        partial(cls.cb_interrupt,
                                device=cls.io[-1],
                                uid=temp_uid))
                    found = True

            if device_identifier == AmbientLight.DEVICE_IDENTIFIER:
                cls.al.append(AmbientLight(uid, cls.ipcon))
                cls.al[-1].set_illuminance_callback_threshold('o', 0, 0)
                cls.al[-1].set_debounce_period(10)
                #self.al.set_illuminance_callback_threshold('<', 30, 30)
                #self.al.set_analog_value_callback_period(10000)
                #self.al.set_illuminance_callback_period(10000)
                #self.al.register_callback(self.al.CALLBACK_ILLUMINANCE, self.cb_ambLight)
                #self.al.register_callback(self.al.CALLBACK_ILLUMINANCE_REACHED, self.cb_ambLight)
                args = cls.al[-1]
                #self.al[-1].register_callback(self.al[-1].CALLBACK_ILLUMINANCE_REACHED, lambda event1, event2, event3, args=args: self.cb_ambLight(event1, event2, event3, args))

                cls.al[-1].register_callback(
                    cls.al[-1].CALLBACK_ILLUMINANCE_REACHED,
                    partial(cls.cb_ambLight, device=args))
                temp_uid = str(cls.al[-1].get_identity()[1]) + "." + str(
                    cls.al[-1].get_identity()[0])

                thread_cb_amb = Timer(60, cls.thread_ambLight, [cls.al[-1]])
                thread_cb_amb.start()

            if device_identifier == BrickletCO2.DEVICE_IDENTIFIER:
                cls.co2.append(BrickletCO2(uid, cls.ipcon))
                temp_uid = str(cls.co2[-1].get_identity()[1]) + "." + str(
                    cls.co2[-1].get_identity()[0])
                thread_co2_ = Timer(5, cls.thread_CO2, [cls.co2[-1]])
                thread_co2_.start()
                cls.threadliste.append(thread_co2_)

            if device_identifier == BrickletDualRelay.DEVICE_IDENTIFIER:
                cls.drb.append(BrickletDualRelay(uid, cls.ipcon))


#
#            if device_identifier == Moisture.DEVICE_IDENTIFIER:
#                self.moist = Moisture(uid, self.ipcon)
#                self.moist.set_moisture_callback_period(10000)
#                self.moist.register_callback(self.moist.CALLBACK_MOISTURE, self.cb_moisture)

            if device_identifier == BrickletMotionDetector.DEVICE_IDENTIFIER:
                cls.md.append(BrickletMotionDetector(uid, cls.ipcon))
                temp_uid = str(cls.md[-1].get_identity()[1]) + "." + str(
                    cls.md[-1].get_identity()[0])
                cls.md[-1].register_callback(
                    cls.md[-1].CALLBACK_MOTION_DETECTED,
                    partial(cls.cb_md, device=cls.md[-1], uid=temp_uid))
                cls.md[-1].register_callback(
                    cls.md[-1].CALLBACK_DETECTION_CYCLE_ENDED,
                    partial(cls.cb_md_end, device=cls.md[-1], uid=temp_uid))

            if device_identifier == BrickletSoundIntensity.DEVICE_IDENTIFIER:
                cls.si.append(BrickletSoundIntensity(uid, cls.ipcon))
                temp_uid = str(cls.si[-1].get_identity()[1]) + "." + str(
                    cls.si[-1].get_identity()[0])

                cls.si[-1].set_debounce_period(1000)
                cls.si[-1].register_callback(
                    cls.si[-1].CALLBACK_INTENSITY_REACHED,
                    partial(cls.cb_si, device=cls.si[-1], uid=temp_uid))
                cls.si[-1].set_intensity_callback_threshold('>', 200, 0)

            if device_identifier == BrickletPTC.DEVICE_IDENTIFIER:
                cls.ptc.append(BrickletPTC(uid, cls.ipcon))
                temp_uid = str(cls.ptc[-1].get_identity()[1]) + "." + str(
                    cls.ptc[-1].get_identity()[0])
                thread_pt_ = Timer(5, cls.thread_pt, [cls.ptc[-1]])
                thread_pt_.start()
                cls.threadliste.append(thread_pt_)

            if device_identifier == BrickletTemperature.DEVICE_IDENTIFIER:
                cls.temp.append(BrickletTemperature(uid, cls.ipcon))
                temp_uid = str(cls.temp[-1].get_identity()[1]) + "." + str(
                    cls.temp[-1].get_identity()[0])
                thread_pt_ = Timer(5, cls.thread_pt, [cls.temp[-1]])
                thread_pt_.start()
                cls.threadliste.append(thread_pt_)

            if device_identifier == BrickMaster.DEVICE_IDENTIFIER:
                cls.master.append(BrickMaster(uid, cls.ipcon))
                thread_rs_error = Timer(60, cls.thread_RSerror, [])
                #thread_rs_error.start()
                if settings.inputs.get(uid) <> None:
                    found = True

            if not found:
                toolbox.log(connected_uid, uid, device_identifier)
                print connected_uid, uid, device_identifier
Пример #15
0
class Rainbow:
    leds = [x[:] for x in [(0, 0, 0)] * config.LED_ROWS * config.LED_COLS]
    rainbow = [x[:] for x in [(0, 0, 0)] * config.LED_ROWS * config.LED_COLS]
    rainbow_position = 0

    def __init__(self, ipcon):
        self.okay = False
        self.ipcon = ipcon

        if not config.UID_LED_STRIP_BRICKLET:
            print("Not Configured: LED Strip (required)")
            return

        self.led_strip = LEDStrip(config.UID_LED_STRIP_BRICKLET, self.ipcon)

        try:
            self.led_strip.get_frame_duration()
            print("Found: LED Strip ({0})".format(
                config.UID_LED_STRIP_BRICKLET))
        except:
            print("Not Found: LED Strip ({0})".format(
                config.UID_LED_STRIP_BRICKLET))
            return

        for i in range(config.LED_ROWS * config.LED_COLS):
            r, g, b = colorsys.hsv_to_rgb(
                1.0 * i / (config.LED_ROWS * config.LED_COLS), 1, 0.1)
            self.rainbow[i] = (int(r * 255), int(g * 255), int(b * 255))

        self.okay = True

        self.update_frame_rate()
        self.led_strip.register_callback(
            self.led_strip.CALLBACK_FRAME_RENDERED, self.frame_rendered)

    def stop_rendering(self):
        if not self.okay:
            return

        self.led_strip.register_callback(
            self.led_strip.CALLBACK_FRAME_RENDERED, None)

    def update_frame_rate(self):
        if not self.okay:
            return

        self.led_strip.set_frame_duration(
            int(1000.0 / config.RAINBOW_FRAME_RATE))

    def frame_rendered(self, _):
        self.frame_upload()
        self.frame_prepare_next()

    def frame_upload(self):
        if not self.okay:
            return

        # Reorder LED data into R, G and B channel
        r = []
        g = []
        b = []
        for i in range(config.LED_ROWS * config.LED_COLS):
            r.append(self.leds[i][config.R_INDEX])
            g.append(self.leds[i][config.G_INDEX])
            b.append(self.leds[i][config.B_INDEX])

        # Make chunks of size 16
        r_chunk = [r[i:i + 16] for i in range(0, len(r), 16)]
        g_chunk = [g[i:i + 16] for i in range(0, len(g), 16)]
        b_chunk = [b[i:i + 16] for i in range(0, len(b), 16)]

        for i in range(len(r_chunk)):
            length = len(r_chunk[i])

            # Fill up chunks with zeros
            r_chunk[i].extend([0] * (16 - len(r_chunk[i])))
            g_chunk[i].extend([0] * (16 - len(g_chunk[i])))
            b_chunk[i].extend([0] * (16 - len(b_chunk[i])))

            try:
                self.led_strip.set_rgb_values(i * 16, length, r_chunk[i],
                                              g_chunk[i], b_chunk[i])
            except:
                break

    def frame_prepare_next(self):
        self.leds = self.rainbow[int(self.rainbow_position) % (
            config.LED_ROWS * config.LED_COLS
        ):] + self.rainbow[:int(self.rainbow_position) %
                           (config.LED_ROWS * config.LED_COLS)]
        self.rainbow_position += (config.LED_ROWS *
                                  config.LED_COLS) * config.RAINBOW_STEP
Пример #16
0
class Rainbow:
    leds = [x[:] for x in [(0, 0, 0)]*config.LED_ROWS*config.LED_COLS]
    rainbow = [x[:] for x in [(0, 0, 0)]*config.LED_ROWS*config.LED_COLS]
    rainbow_position = 0

    def __init__(self, ipcon):
        self.okay = False
        self.ipcon = ipcon

        if not config.UID_LED_STRIP_BRICKLET:
            print("Not Configured: LED Strip (required)")
            return

        self.led_strip = LEDStrip(config.UID_LED_STRIP_BRICKLET, self.ipcon)

        try:
            self.led_strip.get_frame_duration()
            print("Found: LED Strip ({0})".format(config.UID_LED_STRIP_BRICKLET))
        except:
            print("Not Found: LED Strip ({0})".format(config.UID_LED_STRIP_BRICKLET))
            return

        for i in range(config.LED_ROWS*config.LED_COLS):
            r, g, b = colorsys.hsv_to_rgb(1.0*i/(config.LED_ROWS*config.LED_COLS), 1, 0.1)
            self.rainbow[i] = (int(r*255), int(g*255), int(b*255))

        self.okay = True

        self.update_frame_rate()
        self.led_strip.register_callback(self.led_strip.CALLBACK_FRAME_RENDERED,
                                         self.frame_rendered)

    def stop_rendering(self):
        if not self.okay:
            return

        self.led_strip.register_callback(self.led_strip.CALLBACK_FRAME_RENDERED,
                                         None)

    def update_frame_rate(self):
        if not self.okay:
            return

        self.led_strip.set_frame_duration(int(1000.0 / config.RAINBOW_FRAME_RATE))

    def frame_rendered(self, _):
        self.frame_upload()
        self.frame_prepare_next()

    def frame_upload(self):
        if not self.okay:
            return

        # Reorder LED data into R, G and B channel
        r = []
        g = []
        b = []
        for i in range(config.LED_ROWS*config.LED_COLS):
            r.append(self.leds[i][config.R_INDEX])
            g.append(self.leds[i][config.G_INDEX])
            b.append(self.leds[i][config.B_INDEX])

        # Make chunks of size 16
        r_chunk = [r[i:i+16] for i in range(0, len(r), 16)]
        g_chunk = [g[i:i+16] for i in range(0, len(g), 16)]
        b_chunk = [b[i:i+16] for i in range(0, len(b), 16)]

        for i in range(len(r_chunk)):
            length = len(r_chunk[i])

            # Fill up chunks with zeros
            r_chunk[i].extend([0]*(16-len(r_chunk[i])))
            g_chunk[i].extend([0]*(16-len(g_chunk[i])))
            b_chunk[i].extend([0]*(16-len(b_chunk[i])))

            try:
                self.led_strip.set_rgb_values(i*16, length, r_chunk[i], g_chunk[i], b_chunk[i])
            except:
                break

    def frame_prepare_next(self):
        self.leds = self.rainbow[int(self.rainbow_position) % (config.LED_ROWS*config.LED_COLS):] + self.rainbow[:int(self.rainbow_position) % (config.LED_ROWS*config.LED_COLS)]
        self.rainbow_position += (config.LED_ROWS*config.LED_COLS) * config.RAINBOW_STEP
Пример #17
0
class Images:
    leds = [x[:] for x in [[(0, 0, 0)]*config.LED_COLS]*config.LED_ROWS]
    images = []
    image_position = 0

    def __init__(self, ipcon):
        self.okay = False
        self.ipcon = ipcon

        if not config.UID_LED_STRIP_BRICKLET:
            print("Not Configured: LED Strip or LED Strip V2 (required)")
            return

        if not config.IS_LED_STRIP_V2:
            self.led_strip = LEDStrip(config.UID_LED_STRIP_BRICKLET, self.ipcon)
        else:
            self.led_strip = LEDStripV2(config.UID_LED_STRIP_BRICKLET, self.ipcon)

        try:
            self.led_strip.get_frame_duration()
            if not config.IS_LED_STRIP_V2:
                print("Found: LED Strip ({0})".format(config.UID_LED_STRIP_BRICKLET))
            else:
                print("Found: LED Strip V2 ({0})".format(config.UID_LED_STRIP_BRICKLET))
        except:
            if not config.IS_LED_STRIP_V2:
                print("Not Found: LED Strip ({0})".format(config.UID_LED_STRIP_BRICKLET))
            else:
                print("Not Found: LED Strip V2({0})".format(config.UID_LED_STRIP_BRICKLET))
            return

        self.okay = True

        self.update_frame_rate()
        if not config.IS_LED_STRIP_V2:
            self.led_strip.register_callback(self.led_strip.CALLBACK_FRAME_RENDERED,
                                             self.frame_rendered)
        else:
            self.led_strip.register_callback(self.led_strip.CALLBACK_FRAME_STARTED,
                                             self.frame_rendered)

        self.led_strip.set_channel_mapping(config.CHANNEL_MAPPING)
    def stop_rendering(self):
        if not self.okay:
            return

        if not config.IS_LED_STRIP_V2:
            self.led_strip.register_callback(self.led_strip.CALLBACK_FRAME_RENDERED,
                                             None)
        else:
            self.led_strip.register_callback(self.led_strip.CALLBACK_FRAME_STARTED,
                                             None)

    def update_frame_rate(self):
        if not self.okay:
            return

        self.led_strip.set_frame_duration(int(1000.0 / config.IMAGES_FRAME_RATE))

    def set_new_images(self, image_urls):
        self.images = []

        for url in image_urls:
            loader = ImageLoader(url)
            image = [x[:] for x in [[(0, 0, 0)]*config.LED_COLS]*config.LED_ROWS]

            for y in range(config.LED_ROWS):
                for x in range(config.LED_COLS):
                    image[y][x] = loader.get_pixel(y, x)

            self.images.append(image)

        self.image_position = 0

    def frame_rendered(self, _):
        self.frame_upload()
        self.frame_prepare_next()

    def frame_upload(self):
        if not self.okay:
            return

        # Reorder LED data into R, G and B channel
        r = []
        g = []
        b = []
        frame = []

        for row in range(config.LED_ROWS):
            col_range = range(config.LED_COLS)
            if row % 2 == 0:
                col_range = reversed(col_range)
            for col in col_range:
                r.append(self.leds[row][col][0])
                g.append(self.leds[row][col][1])
                b.append(self.leds[row][col][2])
                frame.append(self.leds[row][col][0])
                frame.append(self.leds[row][col][1])
                frame.append(self.leds[row][col][2])

        if not config.IS_LED_STRIP_V2:
            # Make chunks of size 16
            r_chunk = [r[i:i+16] for i in range(0, len(r), 16)]
            g_chunk = [g[i:i+16] for i in range(0, len(g), 16)]
            b_chunk = [b[i:i+16] for i in range(0, len(b), 16)]

            for i in range(len(r_chunk)):
                length = len(r_chunk[i])

                # Fill up chunks with zeros
                r_chunk[i].extend([0]*(16-len(r_chunk[i])))
                g_chunk[i].extend([0]*(16-len(g_chunk[i])))
                b_chunk[i].extend([0]*(16-len(b_chunk[i])))

                try:
                    self.led_strip.set_rgb_values(i*16, length, r_chunk[i], g_chunk[i], b_chunk[i])
                except:
                    break
        else:
            try:
                self.led_strip.set_led_values(0, frame)
            except:
                return

    def frame_prepare_next(self):
        if len(self.images) == 0:
            return

        self.leds = self.images[self.image_position]
        self.image_position = (self.image_position + 1) % len(self.images)
Пример #18
0
class led_strips:
    HOST = "localhost"
    PORT = 4223

    UID_LED_STRIP_ONE = "jGy"
    UID_LED_STRIP_TWO = "jHE"

    MODE = 0
    MODE_HUE = 1
    MODE_SATURATION = 2
    MODE_VALUE = 3
    MODE_VELOCITY = 4
    MODE_COLOR_GRADIENT = 5
    MODE_COLOR_DOT = 6
    MODE_COLOR_FADING = 7
    MODE_COLOR_RANDOMLY = 8
    MODE_LEDS = 9
    MODE_OFF = 10

    MODE_STRIPS = 0
    MODE_LEFT_STRIP = 1
    MODE_RIGHT_STRIP = 2
    MODE_BOTH_STRIPS = 3

    POSITION_HUE = 1
    POSITION_SATURATION = 1
    POSITION_VALUE = 0.3
    POSITION_VELOCITY = 1

    R = [255]*16
    G = [0]*16
    B = [0]*16
    
    MAX_LEDS = 16
    ACTIVE_LEDS = 16

    ipcon = None
    led_strip_1 = None
    led_strip_2 = None
    multi_touch = None
    rotary_poti = None

    def __init__(self):
        # Create IP Connection
        self.ipcon = IPConnection()
        while True:
            try:
                self.ipcon.connect(led_strips.HOST, led_strips.PORT)
                break
            except Error as e:
                log.error('Connection error: ' + str(e.description))
                time.sleep(1)
            except socket.error as e:
                log.error('Socket error: ' + str(e))
                time.sleep(1)

        # Register IP Connection callbacks
        self.ipcon.register_callback(IPConnection.CALLBACK_ENUMERATE, self.cb_enumerate)
        self.ipcon.register_callback(IPConnection.CALLBACK_CONNECTED, self.cb_connected)

        while True:
            try:
                self.ipcon.enumerate()
                break
            except Error as e:
                log.error('Enumerate error: ' + str(e.description))
                time.sleep(1)

    # Callback handels device connections and configures possibly lost configuration
    def cb_enumerate(self, uid, connected_uid, position, hardware_version, firmware_version, device_identifier, enumeration_type):
        if enumeration_type == IPConnection.ENUMERATION_TYPE_CONNECTED or enumeration_type == IPConnection.ENUMERATION_TYPE_AVAILABLE:
            if device_identifier == LEDStrip.DEVICE_IDENTIFIER and uid == self.UID_LED_STRIP_ONE: #LED-Strip 1
                try:
                    self.led_strip_1 = LEDStrip(uid, self.ipcon)
                    log.info('LED-Strip 1 initialized.')
                except Error as e:
                    log.error('LED-Strip 1 init failed: ' + str(e.description))
                    self.led_strip_1 = None
            elif device_identifier == LEDStrip.DEVICE_IDENTIFIER and uid == self.UID_LED_STRIP_TWO: #LED-Strip 2
                try:
                    self.led_strip_2 = LEDStrip(uid, self.ipcon)
                    log.info('LED-Strip 2 initialized.')
                except Error as e:
                    log.error('LED-Strip 2 init failed: ' + str(e.description))
                    self.led_strip_2 = None
            elif device_identifier == MultiTouch.DEVICE_IDENTIFIER: # MulitTouch for changing colors etc.
                try:
                    self.multi_touch = MultiTouch(uid, self.ipcon)
                    self.multi_touch.register_callback(self.multi_touch.CALLBACK_TOUCH_STATE, self.cb_buttons)
                    self.multi_touch.set_electrode_config(0x0FFF)
                    self.multi_touch.recalibrate()
                    log.info('Set proximity off.')
                    log.info('Multi-Touch initialized.')
                except Error as e:
                    log.error('Multi-Touch init failed: ' + str(e.description))
                    self.multi_touch = None
            elif device_identifier == RotaryPoti.DEVICE_IDENTIFIER: # Rotary Poti for picking a color or changing the saturation
                try:
                    self.rotary_poti = RotaryPoti(uid, self.ipcon)
                    self.rotary_poti.register_callback(self.rotary_poti.CALLBACK_POSITION, self.cb_position)
                    self.rotary_poti.set_position_callback_period(50)
                    log.info('Rotary Poti initialized.')
                except Error as e:
                    log.error('Rotary Poti init failed: ' + str(e.description))
                    self.rotary_poti = None

    # Callback handels reconnection of IP Connection
    def cb_connected(self, connected_reason):
        if connected_reason == IPConnection.CONNECT_REASON_AUTO_RECONNECT:
            log.info('Auto reconnect.')
            while True:
                try:
                    self.ipcon.enumerate()
                    break
                except Error as e:
                    log.error('Enumerate error:' + str(e.description))
                    time.sleep(1)

    # Check which mode is set: the left LED strip, the right LED strip or both LED strips
    def set_mode(self, mode, i, leds, r, b, g):
        if self.MODE_STRIPS == self.MODE_BOTH_STRIPS:
            self.led_strip_1.set_rgb_values(i, leds, r, b, g)
            self.led_strip_2.set_rgb_values(i, leds, r, b, g)
        elif self.MODE_STRIPS == self.MODE_LEFT_STRIP:
            self.led_strip_1.set_rgb_values(i, leds, r, b, g)
        elif self.MODE_STRIPS == self.MODE_RIGHT_STRIP:
            self.led_strip_2.set_rgb_values(i, leds, r, b, g)
    
    # Turn off the LED strips depending on the given mode
    def leds_off(self):
        r = [0]*self.MAX_LEDS
        g = [0]*self.MAX_LEDS
        b = [0]*self.MAX_LEDS
        self.set_mode(self.MODE_STRIPS, 0, self.MAX_LEDS, r, b, g)

    # Some simple color functions to turn the strips to red, green or blue
    def led_strips_red(self):
        r = [255]*self.MAX_LEDS
        g = [0]*self.MAX_LEDS
        b = [0]*self.MAX_LEDS
        self.set_mode(self.MODE_STRIPS, 0, self.MAX_LEDS, r, b, g)

    def led_strips_green(self):
        r = [0]*self.MAX_LEDS
        g = [255]*self.MAX_LEDS
        b = [0]*self.MAX_LEDS
        self.set_mode(self.MODE_STRIPS, 0, self.MAX_LEDS, r, b, g)

    def led_strips_blue(self):
        r = [0]*self.MAX_LEDS
        g = [0]*self.MAX_LEDS
        b = [255]*self.MAX_LEDS
        self.set_mode(self.MODE_STRIPS, 0, self.MAX_LEDS, r, b, g)

    # Match the hue (color) to the position by the rotary poti.
    def set_hue(self, position):
        # The position returned by the rotary poti (o to +300) must be mapped to 0°-360° in the HSV colorspace
        hue = ((position / 360) * 432)
        # Convert the HSV color (hue,saturation,value) to the RGB color
        # The function expects hue to be in the range 0-1 not 0-360
        r, g, b = colorsys.hsv_to_rgb(hue/360, self.POSITION_SATURATION, self.POSITION_VALUE)
        #print('Hue: {0:.1f}'.format(hue),'Saturation: {0:.2f}'.format(self.POSITION_SATURATION),'Value: {0:.2f}'.format(self.POSITION_VALUE))
        # Build the LED strip
        self.build_led_strip(r, g, b) 
        # Save the value in the variable
        self.POSITION_HUE = hue/360

    # Match the saturation to the position by the rotary poti.
    def set_saturation(self, position):
        # The position returned by the rotary poti must be mapped to 0-1 in the HSV colorspace
        saturation = (position / 300)
        # Convert the HSV color (hue,saturation,value) to the RGB color
        r, g, b = colorsys.hsv_to_rgb(self.POSITION_HUE, saturation, self.POSITION_VALUE) 
        #print('Hue: {0:.1f}'.format(self.POSITION_HUE*360),'Saturation: {0:.2f}'.format(saturation),'Value: {0:.2f}'.format(self.POSITION_VALUE))
        # Build the LED strip
        self.build_led_strip(r, g, b)
        # Save the value in the variable
        self.POSITION_SATURATION = saturation
    
    # Match the value to the position by the rotary poti.
    def set_value(self, position):
        # The position returned by the rotary poti must be mapped to 0-1 in the HSV colorspace
        value = (position / 300)
        # Convert the HSV color (hue,saturation,value) to the RGB color
        r, g, b = colorsys.hsv_to_rgb(self.POSITION_HUE, self.POSITION_SATURATION, value)
        #print('Hue: {0:.1f}'.format(self.POSITION_HUE*360),'Saturation: {0:.2f}'.format(self.POSITION_SATURATION),'Value: {0:.2f}'.format(value))
        # Build the LED strip
        self.build_led_strip(r, g, b)
        # Save the value in the variable
        self.POSITION_VALUE = value

    # NOT USED AT THE MOMENT
    # The veolcity for some functions can be adjusted by the rotary poti.
    def set_velocity(self, position):
        velocity = (position / 3)
        #print('Velocity: {0:0.1f}'.format(velocity))
        # Save the velocity in the variable
        self.POSITION_VELOCITY = velocity

    # Function to generate a rainbow gradient. Can be adjusted by the velocity.
    def set_color_gradient(self, position):
        # use all LEDs for the gradient
        active_leds = self.MAX_LEDS
        loop_counter = 0
        r = []
        g = []
        b = []
        for led in list(range(active_leds)):
            rv, gv, bv = colorsys.hsv_to_rgb(1.*led/active_leds, self.POSITION_SATURATION, self.POSITION_VALUE)
            r.append(int(rv*255))
            g.append(int(gv*255))
            b.append(int(bv*255))
        for leds in range(active_leds):
            #print("Loop counter: " + str(loop_counter))
            first_red = r.pop(0)
            r.append(first_red)
            first_green = g.pop(0)
            g.append(first_green)
            first_blue = b.pop(0)
            b.append(first_blue)
            #print('R: ' + str(r) + '\n','G: ' + str(g) + '\n','B: ' + str(b) + '\n')
            self.set_mode(self.MODE, 0, self.MAX_LEDS, r, b, g)
            loop_counter = loop_counter + 1            
            time.sleep(0.075)

    # Fade and change the color for the whole strip
    def set_color_gradient_fading(self):
        # Outer loop for changing the color
        for hue in range(0, 360, 30):
            hue = (hue / 360)
            #print("Hue: " + str(hue))
            # Inner loop for fading the actual color
            for value in range(1, 21):
                value = value / 20
                #print("Value: " + str(value))
                r, g, b = colorsys.hsv_to_rgb(hue, self.POSITION_SATURATION, value)
                self.build_led_strip(r, g, b)
                time.sleep(0.075)
            for value in reversed(range(1, 21)):
                value = value / 20
                #print("Value: " + str(value))
                r, g, b = colorsys.hsv_to_rgb(hue, self.POSITION_SATURATION, value)
                self.build_led_strip(r, g, b)
                time.sleep(0.075)
 
    # The LEDs are fading from 0.1 to 1.0 in the value space. The fading can be adjusted by the velocity.
    def set_color_fading(self, position):
        loop_counter = 0
        while loop_counter < 5:
            #print("Loop counter: " + str(loop_counter))
            for value in range(1, 21):
                value = value / 20
                #print("Value: " + str(value))
                r, g, b = colorsys.hsv_to_rgb(self.POSITION_HUE, self.POSITION_SATURATION, value)
                self.build_led_strip(r, g, b)
                time.sleep(0.075)
            for value in reversed(range(1, 21)):
                value = value / 20
                #print("Value: " + str(value))
                r, g, b = colorsys.hsv_to_rgb(self.POSITION_HUE, self.POSITION_SATURATION, value)
                self.build_led_strip(r, g, b)
                time.sleep(0.075)
                loop_counter = loop_counter + 1

    # Only one LED is active and moves from one end to the other end of the strip.
    def set_color_dot(self, position):
        # Build the initial array
        r = self.R[0]
        g = self.G[0]
        b = self.B[0]
        r = [r]
        g = [g]
        b = [b]
        r.extend([0]*15)
        g.extend([0]*15)
        b.extend([0]*15)
        #print('R: ' + str(r) + '\n','G: ' + str(g) + '\n','B: ' + str(b) + '\n')
        # Now get the dot moving
        i = 0
        while i < 15:
            dot_r = r[i]
            dot_g = g[i]
            dot_b = b[i]
            r[i] = 0
            g[i] = 0
            b[i] = 0
            r[i+1] = dot_r
            g[i+1] = dot_g
            b[i+1] = dot_b
            #print('R: ' + str(r) + '\n','G: ' + str(g) + '\n','B: ' + str(b) + '\n')
            i = i + 1
            self.set_mode(self.MODE, 0, self.MAX_LEDS, r, b, g)
            time.sleep(0.1)
        while i > 0:
            dot_r = r[i]
            dot_g = g[i]
            dot_b = b[i]
            r[i] = 0
            g[i] = 0
            b[i] = 0
            r[i-1] = dot_r
            g[i-1] = dot_g
            b[i-1] = dot_b
            #print('R: ' + str(r) + '\n','G: ' + str(g) + '\n','B: ' + str(b) + '\n')
            i = i - 1
            self.set_mode(self.MODE, 0, self.MAX_LEDS, r, b, g)
            time.sleep(0.1)

    # Build random color values and place them randomly on the strips.
    def set_color_randomly(self, position):
        active_leds = self.ACTIVE_LEDS
        """
        r = []
        g = []
        b = []
        # 1. Variant
        for led in list(range(active_leds)):
            rv = random.randrange(1, 256)
            gv = random.randrange(1, 256)
            bv = random.randrange(1, 256)
            r.append(rv)
            g.append(gv)
            b.append(bv)
        # 2. Variant
        for led in list(range(active_leds)):
            rv, gv, bv = colorsys.hsv_to_rgb(1.*led/active_leds, self.POSITION_SATURATION, self.POSITION_VALUE)
            r.append(int(rv*255))
            g.append(int(gv*255))
            b.append(int(bv*255))
        for leds in range(active_leds):
            random.shuffle(r)
            random.shuffle(g)
            random.shuffle(b)
            print('R: ' + str(r) + '\n','G: ' + str(g) + '\n','B: ' + str(b) + '\n')
            self.set_mode(self.MODE, 0, self.MAX_LEDS, r, b, g)
            time.sleep(0.075)
        """
        # 3. Variant
        for leds in range(active_leds):
            r = []
            g = []
            b = []
            range_leds = list(range(active_leds))
            random.shuffle(range_leds)
            #print("LEDs: " + str(range_leds))
            for led in range_leds:
                rv, gv, bv = colorsys.hsv_to_rgb(1.*led/active_leds, self.POSITION_SATURATION, self.POSITION_VALUE)
                r.append(int(rv*255))
                g.append(int(gv*255))
                b.append(int(bv*255))
            #print('R: ' + str(r) + '\n','G: ' + str(g) + '\n','B: ' + str(b) + '\n')
            self.set_mode(self.MODE, 0, self.MAX_LEDS, r, b, g)
            time.sleep(0.1)

    # Extend the LEDs from 1 LED to 16 LEDs per strip. Like the fading, but here the LEDs can be adjusted by the rotary poti.
    def set_leds(self, position):
        # The rotary poti can set the number of LEDs which should be used
        active_leds = (position / 300) * self.MAX_LEDS
        active_leds = int(math.ceil(active_leds))
        #print('Active LEDs: ' + str(active_leds))
        
        # Get the color values from the variables
        r = self.R[0]
        g = self.G[0]
        b = self.B[0]
        #print('R: ' + str(r),'G: ' + str(g),'B: ' + str(b))

        # Now build the list with the active leds
        r = [r]*active_leds
        g = [g]*active_leds
        b = [b]*active_leds
        #print('R: ' + str(r) + '\n','G: ' + str(g) + '\n','B: ' + str(b) + '\n')

        # Now add the remaining dark leds to the list
        dark_leds = 16 - active_leds
        #print('Dark LEDs: ' + str(dark_leds))
        r.extend([0]*dark_leds)
        g.extend([0]*dark_leds)
        b.extend([0]*dark_leds)          
        #print('R: ' + str(r) + '\n','G: ' + str(g) + '\n','B: ' + str(b) + '\n')

        # Now get it to the strips
        self.set_mode(self.MODE, 0, self.MAX_LEDS, r, b, g)           

        # Save the value in the variable
        self.ACTIVE_LEDS = active_leds

    # Helper function to generate the output for the LED strips
    def build_led_strip(self, r, g, b):
        r = int(r*255)
        g = int(g*255)
        b = int(b*255)
        #print('R: ' + str(r),'G: ' + str(g),'B: ' + str(b))

        # Get the actual number of LEDs which should be used
        active_leds = self.ACTIVE_LEDS
        r = [r]*active_leds
        g = [g]*active_leds
        b = [b]*active_leds
        
        # Now add the remaining dark leds to the list
        dark_leds = 16 - active_leds
        r.extend([0]*dark_leds)
        g.extend([0]*dark_leds)
        b.extend([0]*dark_leds)
        #print('R: ' + str(r) + '\n','G: ' + str(g) + '\n','B: ' + str(b) + '\n')
        
        # Now get it to the strips
        self.set_mode(self.MODE, 0, self.MAX_LEDS, r, b, g)
        # Save the values in the variables
        self.R = r
        self.G = g
        self.B = b

    # Callback function for position callback (parameter has range -150 to 150)
    def cb_position(self, position):
        # Print the position for debuging
        #print('Position: ' + str(position))
        # Always add +150 to the position value so that it will start on the left by 0 and to the right it will end by 300
        position = position + 150
        # Select in which MODE it is called
        if self.MODE == self.MODE_HUE:
            self.set_hue(position)
        elif self.MODE == self.MODE_SATURATION:
            self.set_saturation(position)
        elif self.MODE == self.MODE_VALUE:
            self.set_value(position)
        elif self.MODE == self.MODE_VELOCITY:
            self.set_velocity(position)
        elif self.MODE == self.MODE_COLOR_GRADIENT:
            self.set_color_gradient(position)
        elif self.MODE == self.MODE_COLOR_DOT:
            self.set_color_dot(position)
        elif self.MODE == self.MODE_COLOR_FADING:
            self.set_color_fading(position)
        elif self.MODE == self.MODE_COLOR_RANDOMLY:
            self.set_color_randomly(position)
        elif self.MODE == self.MODE_LEDS:
            self.set_leds(position)

    # Callback function for button callback
    def cb_buttons(self, button_state):
        for i in range(12):
            if button_state & (1 << i):
                if i == 0:
                    self.MODE_STRIPS = self.MODE_LEFT_STRIP
                elif i == 1:
                    self.MODE = self.MODE_HUE
                elif i == 2:
                    self.MODE = self.MODE_COLOR_GRADIENT
                elif i == 3:
                    self.MODE_STRIPS = self.MODE_BOTH_STRIPS
                elif i == 4:
                    self.MODE = self.MODE_SATURATION
                elif i == 5:
                    self.set_color_gradient_fading()
                elif i == 6:
                    self.MODE_STRIPS = self.MODE_RIGHT_STRIP
                elif i == 7:
                    self.MODE = self.MODE_VALUE
                elif i == 8:
                    self.MODE = self.MODE_COLOR_FADING
                elif i == 9:
                    #self.MODE = self.MODE_OFF
                    self.MODE = self.MODE_COLOR_RANDOMLY
                elif i == 10:
                    self.MODE = self.MODE_LEDS
                elif i == 11:
                    self.MODE = self.MODE_COLOR_DOT