Ejemplo n.º 1
0
def imageDraw():
# Configuration for the matrix
    options = RGBMatrixOptions()
    options.rows = 32
    options.chain_length = 1
    options.parallel = 1
    options.hardware_mapping = 'regular'  # If you have an Adafruit HAT: 'adafruit-hat'

    matrix = RGBMatrix(options = options)

# RGB example w/graphics prims.
# Note, only "RGB" mode is supported currently.
    image = Image.new("RGB", (32, 32))  # Can be larger than matrix if wanted!!
    draw = ImageDraw.Draw(image)  # Declare Draw instance before prims
# Draw some shapes into image (no immediate effect on matrix)...
    draw.rectangle((0, 0, 31, 31), fill=(0, 0, 0), outline=(0, 0, 255))
    draw.line((0, 0, 31, 31), fill=(255, 0, 0))
    draw.line((0, 31, 31, 0), fill=(0, 255, 0))

# Then scroll image across matrix...
    for n in range(-32, 33):  # Start off top-left, move off bottom-right
        matrix.Clear()
        matrix.SetImage(image, n, n)
        time.sleep(0.05)

    matrix.Clear()
Ejemplo n.º 2
0
def display(image, timeLeft):
    # Configuration for the matrix
    options = RGBMatrixOptions()
    options.rows = 32
    options.chain_length = 1
    options.parallel = 1
    options.hardware_mapping = 'adafruit-hat'  # If you have an Adafruit HAT: 'adafruit-hat'

    matrix = RGBMatrix(options=options)

    # Make image fit our screen.
    image.thumbnail((matrix.width, matrix.height), Image.ANTIALIAS)

    for n in range(-32, 0):  # Start off top-left, move off bottom-right
        matrix.SetImage(image.convert('RGB'), n, 0)
        time.sleep(0.10)
        matrix.Clear()

    matrix.SetImage(image.convert('RGB'))
    time.sleep(10)

    for n in range(0, 33):  # Start off top-left, move off bottom-right
        matrix.SetImage(image.convert('RGB'), n, 0)
        time.sleep(0.15)
        matrix.Clear()
Ejemplo n.º 3
0
class guerillaDisplay(object):
    def __init__(self):
        self.options = RGBMatrixOptions()
        self.options.rows = 16
        self.options.pwm_bits = 6
        self.options.pwm_lsb_nanoseconds = 300
        self.options.chain_length = 1
        self.options.parallel = 1
        self.options.hardware_mapping = 'regular'  # If you have an Adafruit HAT: 'adafruit-hat'
        self.font = graphics.Font()
        self.font.LoadFont("rpi-rgb-led-matrix/fonts/5x8.bdf")
        self.textColor = graphics.Color(255, 0, 0)

    def initiate(self):
        self.matrix = RGBMatrix(options=self.options)
        self.offscreen_canvas = self.matrix.CreateFrameCanvas()

    def set(self, m):
        self.msg = m

    def cellOn(self, x, y, r, g, b):
        self.r = int(r)
        self.g = int(g)
        self.b = int(b)
        self.matrix.SetPixel(x, y, self.r, self.g, self.b)

    def cellOff(self, x, y):
        self.matrix.SetPixel(x, y, 0, 0, 0)

    def clear(self):
        self.matrix.Clear()
Ejemplo n.º 4
0
def image_show_API(image_file,stop):
    
    image = Image.open(image_file)

    # Configuration for the matrix
    options = RGBMatrixOptions()
    options.rows = 32
    options.chain_length = 1
    options.parallel = 1
    options.hardware_mapping = 'adafruit-hat'  # If you have an Adafruit HAT: 'adafruit-hat'

    matrix = RGBMatrix(options = options)
    matrix.Clear()
    # Make image fit our screen.
    image.thumbnail((matrix.width, matrix.height), Image.ANTIALIAS)

    matrix.SetImage(image.convert('RGB'))

    try:
        while True:
            pass
            if stop():
                break

    except KeyboardInterrupt:
        sys.exit(0)
Ejemplo n.º 5
0
class MatrixBase:
    def __init__(self, rows, cols, refresh_rate=20):
        self.rows = rows
        self.cols = cols
        self.refresh_rate = refresh_rate

        options = RGBMatrixOptions()
        options.rows = rows
        options.cols = cols
        options.hardware_mapping = 'adafruit-hat'

        self.options = options
        self.matrix = RGBMatrix(options=options)
        self.font = create_font()
        self.widths = widths(
            self.font,
            '$!@#%^*()[]0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-=+_. '
        )

        self.frame = self.matrix.CreateFrameCanvas()

    def flush(self):
        self.frame = self.matrix.SwapOnVSync(self.frame)

    def clear(self):
        self.frame.Clear()

    def stop(self):
        self.matrix.Clear()
Ejemplo n.º 6
0
class RpiRgbDmdDevice(DmdPlatformInterface):
    """A RpiRgbDmd device."""
    def __init__(self, config):
        """Initialise RpiRgbDmd device."""
        self.config = config
        xs = config["cols"]
        ys = config["rows"]
        self.img = Image.frombytes("RGB", (xs, ys), b'\x11' * xs * ys * 3)
        self.rgbOpts = RGBMatrixOptions()
        self.rgbOpts.drop_privileges = 1
        # Rudeboy way of setting the RGBMatrixOptions
        for k, v in config.items():
            try:
                setattr(self.rgbOpts, k, v)
            except Exception:
                print("RpiRgbDmdDevice: couldn't set", k, v)
        self.matrix = RGBMatrix(options=self.rgbOpts)
        self.matrix.SetImage(self.img)

    def update(self, data):
        """Update DMD data."""
        self.img.frombytes(data)
        self.matrix.SetImage(self.img)

    def set_brightness(self, brightness: float):
        """ brightness [0.0 ... 1.0] """
        self.matrix.brightness = brightness * 100

    def stop(self):
        self.matrix.Clear()
Ejemplo n.º 7
0
class RpiRgbDmdDevice(DmdPlatformInterface):
    """A RpiRgbDmd device."""
    def __init__(self, config):
        """Initialise RpiRgbDmd device."""
        self.config = config
        xs = config["cols"]
        ys = config["rows"]
        self.img = Image.frombytes("RGB", (xs, ys), b'\x11' * xs * ys * 3)
        self.rgb_opts = RGBMatrixOptions()
        # Rudeboy way of setting the RGBMatrixOptions
        for k, v in config.items():
            try:
                setattr(self.rgb_opts, k, v)
            except Exception:  # pylint: disable-msg=broad-except
                raise AssertionError("RpiRgbDmdDevice: couldn't set", k, v)
        self.matrix = RGBMatrix(options=self.rgb_opts)
        self.matrix.SetImage(self.img)

    def update(self, data):
        """Update DMD data."""
        self.img.frombytes(data)
        self.matrix.SetImage(self.img)

    def set_brightness(self, brightness: float):
        """Set brightness.

        Range is [0.0 ... 1.0].
        """
        self.matrix.brightness = brightness * 100

    def stop(self):
        """Stop device."""
        self.matrix.Clear()
Ejemplo n.º 8
0
class EzMatrix(object):
    """Responsible for handling communication with matrix"""
    def __init__(self, rows=32, cols=32, chain_length=1):
        options = RGBMatrixOptions()
        options.rows = rows
        options.chain_length = chain_length
        options.parallel = 1
        options.hardware_mapping = 'adafruit-hat'
        options.cols = cols

        self.matrix = RGBMatrix(options=options)

    def draw_canvas(self, canvas):
        for y in range(len(canvas)):
            for x in range(len(canvas[y])):
                pixel = canvas[y][x]
                self.matrix.SetPixel(x, y, pixel.r, pixel.g, pixel.b)

    def run_anim(self, anim):
        sleep = 0.07

        for canvas in anim:
            self.draw_canvas(canvas)
            time.sleep(sleep)
            self.matrix.Clear()
Ejemplo n.º 9
0
class controller(threading.Thread):
    """A Class to show a image to a LED matrix.

    Attributes:
        img: An image to show in the LED matrix.
        stop_event: A flag to terminate the control loop.
        update_event: A flag to update an image to show.
    """
    def setRGBData(self, rgb_im):
        """Set Imge data to the LED matrix.

        Args:
            rgb_im: a PIL RGB image
        """
        self.matrix.SetImage(rgb_im)

    def __init__(self, rows, chain_length, brightness):
        """Initialize a LED matrix.

        Args:
            rows: The numberof matrix rows (usually 32 or 64).
            chain_length: The number of daisy-chained panels.
            brightness: LED brightness (0-100).
        """
        # LED control options
        options = RGBMatrixOptions()
        options.rows = rows
        options.chain_length = chain_length
        options.parallel = 1
        options.hardware_mapping = 'adafruit-hat'
        options.brightness = brightness

        self.matrix = RGBMatrix(options=options)
        self.img = Image.new('RGB', (rows * chain_length, rows), (0, 0, 0))

        self.stop_event = threading.Event()
        self.update_event = threading.Event()

        threading.Thread.__init__(self)

    def run(self):
        """Run a control loop."""
        while not self.stop_event.is_set():
            self.update_event.wait(3)
            if (self.update_event.is_set()):
                self.update_event.clear()
                self.setRGBData(self.img)

        self.matrix.Clear()
Ejemplo n.º 10
0
class LedServiceMode:
    MODE_NAME = None
    BACKGROUND_POLL_TIME = None

    def __init__(self):
        self.matrix = None
        self.setup()
        self.last_bg_poll = None

    def setup(self):
        pass

    def handle_command(self, cmd):
        return True

    def iterate(self):
        pass

    def activate(self):
        '''Called when this mode is foregrounded.'''
        self.matrix = RGBMatrix(options=options.matrix_options())
        self.do_activate()

    def deactivate(self):
        '''Called when this mode is removed from the foreground.'''
        self.do_deactivate()
        self.matrix.Clear()
        self.matrix = None

    def do_activate(self):
        pass

    def do_deactivate(self):
        pass

    def background_poll(self):
        if self.BACKGROUND_POLL_TIME is None:
            return

        now = time.time()
        if (not self.last_bg_poll
                or now - self.last_bg_poll >= self.BACKGROUND_POLL_TIME):
            self.last_bg_poll = now
            self.background_job()

    def background_job(self):
        pass
Ejemplo n.º 11
0
class DriverRgbMatrix(DriverBase):
    def __init__(self, clear_screen=True):
        options = RGBMatrixOptions()
        options.rows = Config.get_or_throw('leds.display_height')
        options.cols = Config.get_or_throw('leds.display_width')
        options.chain_length = 1
        options.parallel = 1
        options.hardware_mapping = 'adafruit-hat'
        options.drop_privileges = False

        self.__matrix = RGBMatrix(options=options)
        self.__pixels = self.__matrix.CreateFrameCanvas()
        if clear_screen:
            self.clear_screen()

    def display_frame(self, frame):
        img = Image.fromarray(frame, mode='RGB')
        self.__pixels.SetImage(img)
        self.__pixels = self.__matrix.SwapOnVSync(self.__pixels)

    def clear_screen(self):
        self.__pixels.Clear()
        self.__matrix.Clear()

    # For some drivers, only one instance of the driver can exist at a time because all of them
    # would send competing signals to the LEDs. The screensaver, video playback, etc processes
    # that the Queue launches might have their own instance of the driver as well as the
    # Queue process itself, which could cause problems.
    #
    # Thus, for some drivers (like the RGB Matrix driver), when the Queue needs to perform
    # operations like clearing the screen, it creates a short lived instance to avoid the
    # problems with multiple long lived driver instances. This approach does not work for other
    # drivers (like the APA102 driver).
    #
    # See: https://github.com/hzeller/rpi-rgb-led-matrix/issues/640
    #      https://github.com/dasl-/pifi/pull/32
    #      https://github.com/dasl-/pifi/issues/33
    def can_multiple_driver_instances_coexist(self):
        return False
Ejemplo n.º 12
0
class LedMatrixRGB(object):
    """ Gives interface for the 3D.
    """
    def __init__(self, nx=None, ny=None, color=None, power=0):
        self.matrix_opts = RGBMatrixOptions()
        self.set_power(0)
        self.nx = nx
        self.ny = ny
        self.set_options()

    def set_options(self):
        self.matrix_opts.rows = 32
        self.matrix_opts.chain_length = 1
        # self.matrix_opts.parallel = 1
        self.matrix_opts.pwm_bits = 4
        self.matrix_opts.pwm_lsb_nanoseconds = 900
        self.matrix_opts.drop_privileges = True
        self.matrix_opts.hardware_mapping = 'regular'
        # self.matrix_opts.gpio_slowdown=1
        self.matrix = RGBMatrix(options=self.matrix_opts)

    def set_power(self, power):
        """ Adjusts power manually between 0-255.
        """
        print('doit')

    def set_pixel(self, x, y, power, color):
        self.matrix.Clear()
        nx, ny, power = int(x), int(y), int(power)
        if color == 'R':
            self.matrix.SetPixel(nx, ny, power, 0, 0)
        if color == 'G':
            self.matrix.SetPixel(nx, ny, 0, power, 0)
        if color == 'B':
            self.matrix.SetPixel(nx, ny, 0, 0, power)

    def __del__(self):
        print('Goodbye')
            draw_beat()
            beat_count += 1

        if beat_queue.full(
        ):  # if history is full, then replace last element from queue, and perform beat detection
            beat_ave = pop_freq(beat_ave, beat_queue)
            beat_ave = push_freq(beat_ave, beat, beat_queue)
            # compute variance of beat vs average
            variance = 0.0
            for elem in list(beat_queue.queue):
                variance += abs(elem - beat_ave)
            variance = variance / 43
            c = 1.6 - (variance * 0.000003)  # sensitivity factor
            if beat >= beat_ave * c and beat_ave > beat_threshold:
                # beat detected
                draw_beat()
                beat_count = 0
        else:
            beat_ave = push_freq(beat_ave, beat, beat_queue)

        matrix.Clear()  # erase the image currently on matrix
        matrix.SetImage(image, 0, 0)  # add new image to matrix

except KeyboardInterrupt:
    matrix.Clear()
    print('Program Exiting')
    # close the stream gracefully
    stream.stop_stream()
    stream.close()
    p.terminate()
Ejemplo n.º 14
0
def to_matrix(_minutes):
	# matrix options set here
	options = RGBMatrixOptions()	
	options.rows = 32
	options.chain_length = 2
	options.hardware_mapping = 'adafruit-hat'
	options.parallel = 1

	# orient_image arguments here
	mat_x = options.chain_length * options.rows
	mat_y = options.rows
	char_w = 8
	char_h = 13
	num_chars = 8
	lines= 1
	O = orient_image(mat_x, mat_y, char_w ,char_h, num_chars,lines)
	
	matrix = RGBMatrix(options = options)
	image = Image.new("RGB", (64, 32))
	draw = ImageDraw.Draw(image)
	matrix.Clear()
	
	# image files found in respective directories
	png = PNG_8x13
	# create the countdown timer here
	
# First for loop takes the initial list of lists and starts itering through
	#print(T)
        #timer_flag = True
	while True:		
	    T = test_timer(_minutes)
	    for i in T:
                #print('here')
# Second for loop takes each individual list itme and iters through, printing to the matrix
                #print(i)
                # this updates later according to the offset
                x_matrix_pos = O[0]
                # with a single row of chars this wont change
                y_matrix_pos = O[1]
                # this is how far away the next char will print from the previous
                x_matrix_offset = O[2]
                #print(i)
                minutes = (i[0],i[1])
                seconds = (i[2],i[3])
                hundreths = (i[4],i[5])
                
                for i in minutes:
                    #sleep(.01)
                        #x_matrix_pos = x_matrix_offset
                    image = Image.open("%s" % png[int(minutes[0])])
                    image.load()
                    matrix.SetImage(image.convert('RGB'),x_matrix_pos, y_matrix_pos)
                    
                    x_matrix_pos += x_matrix_offset
                    #print x_matrix_pos
                    image = Image.open("%s" % png[int(minutes[1])])
                    image.load()
                    matrix.SetImage(image.convert('RGB'),x_matrix_pos, y_matrix_pos)

                    #colon
                    x_matrix_pos += x_matrix_offset
                    image = Image.open("%s" % png[10])
                    image.load()
                    matrix.SetImage(image.convert('RGB'),x_matrix_pos, y_matrix_pos)
                    #for secs in seconds:

                    x_matrix_pos += x_matrix_offset
                    image = Image.open("%s" % png[int(seconds[0])])
                    image.load()
                    matrix.SetImage(image.convert('RGB'),x_matrix_pos, y_matrix_pos)

                    x_matrix_pos += x_matrix_offset
                    #image = Image.open("%s" % png[int(seconds[1])])
                    image = Image.open("%s" % png[int(seconds[1])])
                    image.load()
                    matrix.SetImage(image.convert('RGB'),x_matrix_pos, y_matrix_pos)
                    #period
                    x_matrix_pos += x_matrix_offset
                    image = Image.open("./8x13/period.png")
                    image.load()
                    matrix.SetImage(image.convert('RGB'),x_matrix_pos, y_matrix_pos)
                    #for hunds in hundreths:

                    x_matrix_pos += x_matrix_offset
                    image = Image.open("%s" % png[int(hundreths[0])])
                    image.load()
                    matrix.SetImage(image.convert('RGB'),x_matrix_pos, y_matrix_pos)

                    x_matrix_pos += x_matrix_offset
                    image = Image.open("%s" % png[int(hundreths[1])])
                    image.load()
                    matrix.SetImage(image.convert('RGB'),x_matrix_pos, y_matrix_pos)
                    #print(minutes[0],minutes[1],seconds[0],seconds[1],hundreths[0],hundreths[1])
                    sleep(.0001693405867)
	        #timer_flag == False
            print(datetime.now())
	while 1:
			# last list item in timer
		zero_status = T[-1]

		x_matrix_pos = O[0]
		y_matrix_pos = O[1]
		x_matrix_offset = O[2]
			
		for i in zero_status:
		    image = Image.open("%s" % png[i])
		    image.load()
		    matrix.SetImage(image.convert('RGB'),x_matrix_pos, y_matrix_pos)
		    x_matrix_pos += x_matrix_offset
def main(win):

    # 32 Rows, 2 panel, 1 chain
    MyMatrix = RGBMatrix(32, 2, 1)

    # Bits used for PWM. Something between 1..11. Default: 11
    MyMatrix.pwmBits = 11

    # Sets brightness level. Default: 100. Range: 1..100"
    MyMatrix.brightness = 100

    # Buffer canvas.
    MyOffsetCanvas = MyMatrix.CreateFrameCanvas()

    # setup colours for border, paddles and ball
    red = graphics.Color(255, 0, 0)
    green = graphics.Color(0, 255, 0)
    blue = graphics.Color(0, 0, 255)
    white = graphics.Color(255, 255, 255)
    black = graphics.Color(0, 0, 0)
    grey = graphics.Color(128, 128, 128)

    # set player1 paddle start
    p1x = 2
    p1y = 12

    # set player2 paddle start
    p2x = 61
    p2y = 12

    # set the ball start
    ballx = 32
    bally = 16

    # Set the ball movement
    xballmovement = +1
    yballmovement = -1

    # start the main loop
    going = True

    win.nodelay(True)  # make getkey() not wait

    while going:

        try:
            key = win.getkey()
        except:  # in no delay mode getkey raise and exeption if no key is press
            key = None
        #endtry

        if key == "x":
            going = False
            break
        #endif

        # player1 paddle down
        if key == "q":
            p1y = p1y - 1
        #endif

        # player1 paddle down
        if key == "a":
            p1y = p1y + 1
        #endif

        # player2 paddle up
        if key == "p":
            p2y = p2y - 1
        #endif

        # player2 paddle down
        if key == "l":
            p2y = p2y + 1
        #endif

        ballx = ballx + xballmovement
        bally = bally + yballmovement

        p1y = bally - 4
        p2y = bally - 4

        MyMatrix.Clear()

        # draw the border
        graphics.DrawLine(MyOffsetCanvas, 0, 0, 63, 0, white)
        graphics.DrawLine(MyOffsetCanvas, 0, 0, 0, 31, white)

        graphics.DrawLine(MyOffsetCanvas, 63, 0, 63, 31, white)
        graphics.DrawLine(MyOffsetCanvas, 0, 31, 63, 31, white)

        # draw player1 paddle
        graphics.DrawLine(MyOffsetCanvas, p1x, p1y, p1x, p1y + 8, red)

        # draw player2 paddle
        graphics.DrawLine(MyOffsetCanvas, p2x, p2y, p2x, p2y + 8, green)

        # draw the ball
        graphics.DrawCircle(MyOffsetCanvas, ballx, bally, 1, blue)

        # Collision Detect
        collision_type = fnDetectCollision(p1x, p1y, p2x, p2y, ballx, bally)

        if collision_type == PADDLE1:
            xballmovement = +1
        #endif

        if collision_type == PADDLE2:
            xballmovement = -1
        #endif

        if collision_type == TOP:
            yballmovement = +1
        #endif

        if collision_type == BOTTOM:
            yballmovement = -1
        #endif

        if collision_type == LEFT_EDGE:
            xballmovement = +1
        #endif

        if collision_type == RIGHT_EDGE:
            xballmovement = -1
        #endif

        # flip on vsync
        MyOffsetCanvas = MyMatrix.SwapOnVSync(MyOffsetCanvas)

        # Wait a bit
        time.sleep(0.005)

    #endwhile

    return
Ejemplo n.º 16
0
# get the interface name from the command line (will throw an exception if one is not given)
myifname = sys.argv[1]

# init the RGB matrix as 32 Rows, 2 panels (represents 32 x 64 panel), 1 chain
MyMatrix = RGBMatrix(32, 2, 1)

# Bits used for PWM. Something between 1..11. Default: 11
MyMatrix.pwmBits = 11

# Sets brightness level. Default: 100. Range: 1..100"
MyMatrix.brightness = 100

# Flood fill with white as a POST
MyMatrix.Fill(255, 255, 255)
time.sleep(2)
MyMatrix.Clear()

# Setup colours for text display
ColorRED = graphics.Color(255, 0, 0)
ColorGRN = graphics.Color(0, 255, 0)
ColorBLU = graphics.Color(0, 0, 255)
ColorWHI = graphics.Color(255, 255, 255)

# Create the buffer canvas
MyOffsetCanvas = MyMatrix.CreateFrameCanvas()

# Load up the font (use absolute paths so script can be invoked from /etc/rc.local correctly)
font = graphics.Font()
font.LoadFont("/home/pi/rpi-rgb-led-matrix/fonts/5x8.bdf")

# get the IP address of the interface specified on the command line (e.g. wlan0)
Ejemplo n.º 17
0
class AlarmClock(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)

        # Setup GPIO buttons
        GPIO.setwarnings(False)
        GPIO.setmode(GPIO.BCM)
        GPIO.setup(SENSOR, GPIO.IN, pull_up_down=GPIO.PUD_UP)
        GPIO.setup(UP, GPIO.IN, pull_up_down=GPIO.PUD_UP)
        GPIO.setup(DOWN, GPIO.IN, pull_up_down=GPIO.PUD_UP)
        GPIO.setup(SOUND, GPIO.IN, pull_up_down=GPIO.PUD_UP)

        self.font_day = graphics.Font()
        self.font_day.LoadFont(BASE_DIR + "fonts/4x6.bdf")
        self.font_time = graphics.Font()
        self.font_time.LoadFont(BASE_DIR + "fonts/5x8.bdf")
        self.color_day = graphics.Color(255, 179, 0)
        self.color_time = graphics.Color(154, 240, 0)
        self.color_pixel = graphics.Color(0, 149, 67)
        self.font_alarm = graphics.Font()
        self.font_alarm.LoadFont(BASE_DIR + "fonts/7x13.bdf")
        self.color_alarm = graphics.Color(234, 0, 52)
        self.color_alarm_colon = graphics.Color(255, 130, 42)

        self.player = Player()
        self.alarm = Alarm(7, 30, self.player)

        self.done = False
        return

    def set_pixel(self, x, y, color):
        self.matrix.SetPixel(x, y, color[0], color[1], color[2])
        return

    def shutdown(self):
        logger.info("AlarmClock is shutting down")
        self.done = True
        time.sleep(2)
        pass

    def setup(self):
        logger.info("setting up the matrix: %s", getpass.getuser())
        options = RGBMatrixOptions()
        options.rows = 16
        options.chain_length = 1
        options.brightness = BRIGHTNESS
        options.daemon = 0
        options.drop_privileges = 0
        self.matrix = RGBMatrix(options=options)
        logger.info("matrix setup is done: %s", getpass.getuser())
        return

    def run(self):
        self.setup()
        logger.info("AlarmClock is running")
        self.color_black = graphics.Color(0, 0, 0)
        while not self.done:
            # handle sound play
            if GPIO.input(SOUND) == 0:
                self.player.play(SOUND_FILE)
            elif GPIO.input(SOUND) == 1:
                self.player.stop()
                pass

            # handle buttons
            self.matrix.Clear()
            if GPIO.input(SENSOR) == 0:
                if GPIO.input(UP) == 0:
                    self.alarm.change_up()
                    pass
                if GPIO.input(DOWN) == 0:
                    self.alarm.change_down()
                    pass
                alarm_hour = "%2d" % (self.alarm.hour)
                alarm_minute = "%02d" % (self.alarm.minute)
                self.alarm_dot(0, 12, alarm_hour, alarm_minute)
            else:
                local_time = time.localtime()
                local_hour = "%2d" % (local_time.tm_hour)
                local_minute = "%02d" % (local_time.tm_min)
                local_sec = "%02d" % (local_time.tm_sec)
                self.time_dot(0, 15, local_hour, local_minute, local_sec)
                local_day = time.strftime("%a%d%b%y", local_time)
                self.day_text(0, 6, local_day)
                pass
            time.sleep(1)
            pass
        GPIO.cleanup()
        logger.info("GPIO cleanup is done")
        self.player.shutdown()
        return

    def pixel(self, x, y, color):
        self.matrix.SetPixel(x, y - 1, color.red, color.green, color.blue)
        self.matrix.SetPixel(x - 1, y - 1, color.red, color.green, color.blue)
        self.matrix.SetPixel(x, y - 2, color.red, color.green, color.blue)
        self.matrix.SetPixel(x - 1, y - 2, color.red, color.green, color.blue)
        return 1

    def colon(self, x, y, color):
        self.pixel(x, y, color)
        self.pixel(x, y - 4, color)
        return 1

    def alarm_colon(self, x, y, color):
        self.pixel(x, y - 1, color)
        self.pixel(x, y - 6, color)
        return 1

    def time_dot(self, x, y, hour, minute, sec):
        cx = x
        l = graphics.DrawText(self.matrix, self.font_time, cx, y,
                              self.color_time, hour)
        cx = cx + l
        self.colon(cx, y, self.color_pixel)
        cx = cx + 1
        l = graphics.DrawText(self.matrix, self.font_time, cx, y,
                              self.color_time, minute)
        cx = cx + l
        self.pixel(cx, y, self.color_pixel)
        cx = cx + 1
        l = graphics.DrawText(self.matrix, self.font_time, cx, y,
                              self.color_time, sec)
        return

    def time_text(self, x, y, text):
        graphics.DrawText(self.matrix, self.font_time, x, y, self.color_time,
                          text)
        return

    def day_text(self, x, y, text):
        graphics.DrawText(self.matrix, self.font_day, x, y, self.color_day,
                          text)
        return

    def alarm_dot(self, x, y, hour, minute):
        cx = x
        l = graphics.DrawText(self.matrix, self.font_alarm, cx, y,
                              self.color_alarm, hour)
        cx = cx + l
        self.alarm_colon(cx, y, self.color_alarm_colon)
        cx = cx + 1
        #cx = cx + l - 2
        #l = graphics.DrawText(self.matrix, self.font_alarm, cx, y-1, self.color_alarm_pixel, ":")
        #cx = cx + l - 1
        l = graphics.DrawText(self.matrix, self.font_alarm, cx, y,
                              self.color_alarm, minute)
        return
Ejemplo n.º 18
0
class Game:
    SWITCHES = None

    BLOCK_SIZE = 16

    COLUMNS = None
    ROWS = None

    SHAPES_NEXT_COUNT = None

    FPS = None

    COLORS = [
        # 0 - Black
        (0, 0, 0),
        # 1 - Purple
        (128, 0, 128),
        # 2 - Green
        (0, 255, 0),
        # 3 - Red
        (255, 0, 0),
        # 4 - Blue
        (0, 0, 255),
        # 5 - Orange
        (255, 165, 0),
        # 6 - Cyan
        (0, 255, 255),
        # 7 - Yellow
        (255, 255, 0),
        # 8 - Dark Grey
        (35, 35, 35),
        # 9 - White
        (255, 255, 255)
    ]

    SHAPES = [
        # T
        [
            [1, 1, 1],
            [0, 1, 0],
        ],

        # S
        [
            [0, 2, 2],
            [2, 2, 0]
        ],

        # Z
        [
            [3, 3, 0],
            [0, 3, 3]
        ],

        # J
        [
            [4, 0, 0],
            [4, 4, 4]
        ],

        # L
        [
            [0, 0, 5],
            [5, 5, 5],
        ],

        # I
        [
            [6, 6, 6, 6],
        ],

        # O
        [
            [7, 7],
            [7, 7],
        ]
    ]

    WIDTH = None
    HEIGHT = None

    COUNTDOWN = None

    SCORE_INCREMENTS = None

    LINES = 0
    SCORE = 0

    LEVEL = 1
    LEVEL_INCREMENT = None

    INTERVAL = None
    INTERVAL_INCREMENT = None

    PAUSED = False

    GAMEOVER = False

    BACKGROUND_GRID = None
    BACKGROUND_BOX = None

    RGB_MATRIX_HARDWARE = None
    RGB_MATRIX_ROWS = None
    RGB_MATRIX_CHAIN_LENGTH = None
    RGB_MATRIX_PARALLEL = None
    RGB_MATRIX_PWM_BITS = None
    RGB_MATRIX_BRIGHTNESS = None
    RGB_MATRIX_LSB_NANOSECONDS = None
    RGB_MATRIX_GPIO_SLOWDOWN = None

    pygame = None
    pygame_font = None
    pygame_screen = None
    pygame_clock = None

    rgbmatrix = None
    rgbmatrix_options = None
    rgbmatrix_font = None

    gpio = None
    db = None

    board = None
    shape = None
    shapes_next = None

    def __init__(self, switches, columns, rows, shapes_next_count, fps, countdown, interval, score_increments, level_increment, interval_increment, rgb_matrix_hardware, rgb_matrix_rows, rgb_matrix_chain_length, rgb_matrix_parallel, rgb_matrix_pwm_bits, rgb_matrix_brightness, rgb_matrix_lsb_nanoseconds, rgb_matrix_gpio_slowdown, rgb_matrix_disable_hardware_pulsing, rgb_matrix_rgb_sequence, pygame_instance=None):
        self.SWITCHES = switches
        self.COLUMNS = columns
        self.ROWS = rows
        self.SHAPES_NEXT_COUNT = shapes_next_count
        self.FPS = fps
        self.COUNTDOWN = countdown
        self.INTERVAL = interval
        self.SCORE_INCREMENTS = score_increments
        self.LEVEL_INCREMENT = level_increment
        self.INTERVAL_INCREMENT = interval_increment
        self.RGB_MATRIX_HARDWARE = rgb_matrix_hardware
        self.RGB_MATRIX_ROWS = rgb_matrix_rows
        self.RGB_MATRIX_CHAIN_LENGTH = rgb_matrix_chain_length
        self.RGB_MATRIX_PARALLEL = rgb_matrix_parallel
        self.RGB_MATRIX_PWM_BITS = rgb_matrix_pwm_bits
        self.RGB_MATRIX_BRIGHTNESS = rgb_matrix_brightness
        self.RGB_MATRIX_LSB_NANOSECONDS = rgb_matrix_lsb_nanoseconds
        self.RGB_MATRIX_GPIO_SLOWDOWN = rgb_matrix_gpio_slowdown
        self.RGB_MATRIX_DISABLE_HARDWARE_PULSING = rgb_matrix_disable_hardware_pulsing
        self.RGB_MATRIX_RGB_SEQUENCE = rgb_matrix_rgb_sequence

        self.gpio = Gpio

        self.rgbmatrix_options = RgbMatrixOptions()
        self.rgbmatrix_options.hardware_mapping = self.RGB_MATRIX_HARDWARE
        self.rgbmatrix_options.rows = self.RGB_MATRIX_ROWS
        self.rgbmatrix_options.chain_length = self.RGB_MATRIX_CHAIN_LENGTH
        self.rgbmatrix_options.parallel = self.RGB_MATRIX_PARALLEL
        self.rgbmatrix_options.pwm_bits = self.RGB_MATRIX_PWM_BITS
        self.rgbmatrix_options.brightness = self.RGB_MATRIX_BRIGHTNESS
        self.rgbmatrix_options.pwm_lsb_nanoseconds = self.RGB_MATRIX_LSB_NANOSECONDS
        self.rgbmatrix_options.gpio_slowdown = self.RGB_MATRIX_GPIO_SLOWDOWN
        self.rgbmatrix_options.disable_hardware_pulsing = self.RGB_MATRIX_DISABLE_HARDWARE_PULSING
        self.rgbmatrix_options.led_rgb_sequence = self.RGB_MATRIX_RGB_SEQUENCE

        if pygame_instance is None:
            self.pygame = pygame
        else:
            self.pygame = pygame_instance

        self.db = TinyDB('data/database.json')

        try:
            self.gpio.setmode(self.gpio.BCM)

            for switch in self.SWITCHES.keys():
                self.gpio.setup(switch, self.gpio.IN)

            self.WIDTH = self.BLOCK_SIZE * (self.COLUMNS + 12)
            self.HEIGHT = self.BLOCK_SIZE * (self.ROWS + 24)

            self.BACKGROUND_GRID = [
                [8 if x % 2 == y % 2 else 0 for x in xrange(self.COLUMNS)]
                for y in xrange(self.ROWS)
            ]
            self.BACKGROUND_BOX = [
                [9 if (x == 0 or x == self.COLUMNS + 1 or y == 0 or y == self.ROWS + 1) else 0 for x in xrange(self.COLUMNS + 2)]
                for y in xrange(self.ROWS + 2)
            ]

            self.pygame.init()
            self.pygame.key.set_repeat(150, 50)
            self.pygame_font = self.pygame.font.Font(self.pygame.font.get_default_font(), 12)
            self.pygame_screen = self.pygame.display.set_mode((self.WIDTH, self.HEIGHT), 0, 24)
            self.pygame.display.set_caption('RGB Matrix Tetris')
            self.pygame.event.set_blocked(self.pygame.MOUSEMOTION)
            self.pygame.mouse.set_visible(0)
            self.pygame_clock = self.pygame.time.Clock()

            self.rgbmatrix = RgbMatrix(options=self.rgbmatrix_options)
            self.rgbmatrix_graphics = Graphics
            self.rgbmatrix_font = self.rgbmatrix_graphics.Font()
            self.rgbmatrix_font.LoadFont('./rgbmatrixtetris/fonts/4x6.bdf')

            self.board = Board(self.COLUMNS, self.ROWS)
            self.__generate_shapes()
        except AttributeError:
            print("[Game][error] An error occurred initialising game")

    def start(self, run_once=False):
        print("[Game][info] Starting game")

        try:
            self.rgbmatrix.Clear()
            self.pygame_screen.fill((0, 0, 0))
            self.__display_message("Press\n\nenter\n\nto\n\nstart")
            self.pygame.display.update()
            pygame_wait = True

            while pygame_wait:
                try:
                    for event in self.pygame.event.get():
                        if event.type == self.pygame.KEYDOWN:
                            if event.key == self.pygame.K_RETURN:
                                pygame_wait = False
                            elif event.key == self.pygame.K_ESCAPE:
                                self.quit()
                        elif event.type == self.pygame.QUIT:
                            self.quit()
                except KeyboardInterrupt:
                    self.quit()
        except AttributeError:
            print("[Game][error] An error occurred starting game")

        self.__countdown()
        self.__loop()
        self.finish()

        if run_once is not True:
            self.start()

    def __countdown(self):
        print("[Game][info] Starting game countdown")
        try:
            start_ticks = self.pygame.time.get_ticks()

            while True:
                seconds = (self.pygame.time.get_ticks() - start_ticks) / 1000
                self.rgbmatrix.Clear()
                self.pygame_screen.fill((0, 0, 0))
                remaining = (self.COUNTDOWN - seconds)

                if seconds > self.COUNTDOWN:
                    break

                if seconds == self.COUNTDOWN:
                    self.__display_message("Go!")
                elif seconds == 0:
                    self.__display_message("Starting\n\nin %d!" % remaining)
                else:
                    self.__display_message("%d!" % remaining)

                self.pygame.display.update()
                self.pygame.time.wait(1000)
        except AttributeError:
            print("[Game][error] An error occurred starting game countdown")

    def __loop(self):
        print("[Game][info] Starting game loop")

        try:
            self.pygame.time.set_timer(pygame.USEREVENT + 1, self.INTERVAL)

            key_actions = {
                'ESCAPE': lambda: self.quit(),
                'LEFT': lambda: self.__move(-1),
                'RIGHT': lambda: self.__move(+1),
                'DOWN': lambda: self.__drop(True),
                'UP': lambda: self.__rotate_shape(),
                'p': lambda: self.toggle_pause(),
                'RETURN': lambda: self.__instant_drop()
            }

            start_ticks = self.pygame.time.get_ticks()

            while not self.GAMEOVER:
                self.pygame_clock.tick(self.FPS)
                rgbmatrix_canvas = self.rgbmatrix.CreateFrameCanvas()
                self.pygame_screen.fill((0, 0, 0))

                if self.PAUSED:
                    self.__display_message("Paused", None, self.COLORS[9], self.COLORS[0], None)
                else:
                    self.__display_message("Next:", ((self.COLUMNS + 3), 1), self.COLORS[9], self.COLORS[0], None, False)
                    self.__display_message("Time: \n\n\n\n\nScore: \n\n\n\n\nLines: \n\n\n\n\nLevel:", (1, (self.ROWS + 3)), self.COLORS[9], self.COLORS[0], None, False)

                    self.__display_message("%s" % (str(datetime.timedelta(seconds=((self.pygame.time.get_ticks() - start_ticks) / 1000)))), (1, (self.ROWS + 8)), self.COLORS[3], self.COLORS[0], (60, './rgbmatrixtetris/fonts/4x6.bdf'), rgbmatrix_canvas)
                    self.__display_message("%d" % (self.SCORE), (1, (self.ROWS + 14)), self.COLORS[2], self.COLORS[0], (60, './rgbmatrixtetris/fonts/4x6.bdf'), rgbmatrix_canvas)
                    self.__display_message("%d" % (self.LINES), (1, (self.ROWS + 20)), self.COLORS[5], self.COLORS[0], (60, './rgbmatrixtetris/fonts/4x6.bdf'), rgbmatrix_canvas)
                    self.__display_message("%d" % (self.LEVEL), (1, (self.ROWS + 26)), self.COLORS[6], self.COLORS[0], (60, './rgbmatrixtetris/fonts/4x6.bdf'), rgbmatrix_canvas)

                    self.__draw_matrix(self.BACKGROUND_GRID, (1, 1), None, False)
                    self.__draw_matrix(self.board.coordinates(), (1, 1), None, rgbmatrix_canvas)
                    self.__draw_matrix(self.shape.coordinates(), self.shape.position((1, 1)), None, rgbmatrix_canvas)
                    self.__draw_matrix(self.BACKGROUND_BOX, (0, 0), None, rgbmatrix_canvas)

                    for i in range(0, (self.SHAPES_NEXT_COUNT - 1)):
                        self.__draw_matrix(self.shapes_next[i].coordinates(), ((self.COLUMNS + 3), (((i + 1) * 5) - 2)), None, rgbmatrix_canvas)

                rgbmatrix_canvas = self.rgbmatrix.SwapOnVSync(rgbmatrix_canvas)
                self.pygame.display.update()

                try:
                    for event in self.pygame.event.get():
                        if event.type == self.pygame.USEREVENT + 1 and not self.PAUSED:
                            self.__drop(False)
                        elif event.type == self.pygame.QUIT:
                            self.quit()
                        elif event.type == self.pygame.KEYDOWN:
                            for key in key_actions:
                                if event.key == eval("self.pygame.K_" + key):
                                    key_actions[key]()
                except KeyboardInterrupt:
                    self.quit()
        except AttributeError:
            print("[Game][error] An error occurred during game loop")

    def __button_press(self, channel):
        print("[Game][info] Button pressed: %d" % channel)

        event = self.pygame.event.Event(self.pygame.KEYDOWN, key=eval("self.pygame.K_" + self.SWITCHES[channel]), trigger='gpio')
        self.pygame.event.post(event)

    def __generate_shapes(self):
        print("[Game][info] Generating next shapes")

        self.shapes_next = [Shape(self.SHAPES[rand(len(self.SHAPES))]) for x in xrange(self.SHAPES_NEXT_COUNT)]
        self.__next_shape()

    def __next_shape(self):
        print("[Game][info] Getting next shape")

        self.shape = self.shapes_next.pop(0)
        self.shapes_next.append(Shape(self.SHAPES[rand(len(self.SHAPES))]))

        self.shape.set_x(int(self.COLUMNS / 2 - len(self.shape.coordinates()[0]) / 2))
        self.shape.set_y(0)

        if self.board.check_collision(self.shape, self.shape.position()):
            self.GAMEOVER = True

    def __display_message(self, message, coordinates=None, color=COLORS[9], background_color=COLORS[0], message_size=None, rgbmatrix=None):
        print("[Game][info] Displaying message")

        for i, line in enumerate(message.splitlines()):
            pygame_message_font = self.pygame_font
            rgbmatrix_message_font = self.rgbmatrix_font

            if message_size is not None:
                pygame_message_size, rgbmatrix_message_size = message_size
                pygame_message_font = self.pygame.font.Font(self.pygame.font.get_default_font(), pygame_message_size)
                rgbmatrix_message_font = self.rgbmatrix_graphics.Font()
                rgbmatrix_message_font.LoadFont(rgbmatrix_message_size)

            pygame_message_image = pygame_message_font.render(line, False, color, background_color)

            if coordinates is not None:
                pygame_position_x, pygame_position_y = coordinates
                pygame_position_x = (pygame_position_x * self.BLOCK_SIZE)
                pygame_position_y = (pygame_position_y * self.BLOCK_SIZE)
                rgbmatrix_position_x, rgbmatrix_position_y = coordinates
            else:
                pygame_message_image_center_x, pygame_message_image_center_y = pygame_message_image.get_size()
                pygame_message_image_center_x //= 2
                pygame_message_image_center_y //= 2
                pygame_position_x = (self.WIDTH // 2 - pygame_message_image_center_x)
                pygame_position_y = (self.HEIGHT // 2 - pygame_message_image_center_y + i)
                rgbmatrix_position_x = (self.WIDTH / self.BLOCK_SIZE - (4 * len(line))) // 2
                rgbmatrix_position_y = (((self.HEIGHT / self.BLOCK_SIZE - rgbmatrix_message_font.height) // 2) + (i * 3))

            if rgbmatrix is not False:
                if rgbmatrix is None:
                    rgbmatrix = self.rgbmatrix

                r, g, b = color
                self.rgbmatrix_graphics.DrawText(rgbmatrix, rgbmatrix_message_font, rgbmatrix_position_x, rgbmatrix_position_y, self.rgbmatrix_graphics.Color(r, g, b), line)

            self.pygame_screen.blit(
                pygame_message_image,
                (pygame_position_x, pygame_position_y)
            )

    def __draw_line(self, start_position, end_position, color=COLORS[9], rgbmatrix=True):
        print("[Game][info] Drawing line")

        if rgbmatrix:
            r, g, b = color
            start_x, start_y = start_position
            end_x, end_y = end_position
            self.rgbmatrix_graphics.DrawLine(self.rgbmatrix, start_x, start_y, end_x, end_y, self.rgbmatrix_graphics.Color(r, g, b))

        self.pygame.draw.line(self.pygame_screen, color, start_position, end_position)

    def __draw_matrix(self, matrix, offset, color=None, rgbmatrix=None):
        print("[Game][info] Drawing matrix")

        off_x, off_y = offset

        for y, row in enumerate(matrix):
            for x, val in enumerate(row):
                if val:
                    if color is None:
                        shape_color = self.COLORS[val]
                    else:
                        shape_color = color

                    if rgbmatrix is not False:
                        if rgbmatrix is None:
                            rgbmatrix = self.rgbmatrix

                        r, g, b = shape_color
                        rgbmatrix.SetPixel((off_x + x), (off_y + y), r, g, b)

                    self.pygame.draw.rect(
                        self.pygame_screen,
                        shape_color,
                        self.pygame.Rect((off_x + x) * self.BLOCK_SIZE, (off_y + y) * self.BLOCK_SIZE, self.BLOCK_SIZE, self.BLOCK_SIZE),
                        0
                    )

    def __count_clear_rows(self, rows):
        print("[Game][info] Counting cleared rows")

        self.LINES += rows
        self.SCORE += self.SCORE_INCREMENTS[rows] * self.LEVEL

        if self.LINES >= self.LEVEL * self.LEVEL_INCREMENT:
            self.LEVEL += 1
            delay = self.INTERVAL - self.INTERVAL_INCREMENT * (self.LEVEL - 1)
            delay = 100 if delay < 100 else delay
            self.pygame.time.set_timer(self.pygame.USEREVENT + 1, delay)

    def __move(self, delta_x):
        print("[Game][info] Moving shape")

        if not self.GAMEOVER and not self.PAUSED:
            new_x = self.shape.x() + delta_x

            if new_x < 0:
                new_x = 0

            if new_x > self.COLUMNS - len(self.shape.coordinates()[0]):
                new_x = self.COLUMNS - len(self.shape.coordinates()[0])

            if not self.board.check_collision(self.shape, (new_x, self.shape.y())):
                self.shape.set_x(new_x)

    def __drop(self, manual):
        print("[Game][info] Drop shape")

        if not self.GAMEOVER and not self.PAUSED:
            self.SCORE += 1 if manual else 0
            self.shape.set_y(self.shape.y() + 1)

            if self.board.check_collision(self.shape, self.shape.position()):
                self.board.join_matrixes(self.shape, self.shape.position())
                self.__next_shape()
                cleared_rows = 0

                while True:
                    for i, row in enumerate(self.board.coordinates()[:-1]):
                        if 0 not in row:
                            self.board.clear_row(i)
                            cleared_rows += 1
                            break
                    else:
                        break

                self.__count_clear_rows(cleared_rows)

                return True

        return False

    def __instant_drop(self):
        print("[Game][info] Instant drop shape")

        if not self.GAMEOVER and not self.PAUSED:
            while not self.__drop(True):
                pass

    def __rotate_shape(self, direction='clockwise'):
        print("[Game][info] Rotating shape %s" % (direction))

        if not self.GAMEOVER and not self.PAUSED:
            new_coordinates = (0, 0)

            if direction == 'clockwise':
                new_coordinates = self.shape.rotate_clockwise()
            elif direction == 'anti-clockwise':
                new_coordinates = self.shape.rotate_anti_clockwise()

            if not self.board.check_collision(Shape(new_coordinates), self.shape.position()):
                self.shape.set_coordinates(new_coordinates)

    def toggle_pause(self):
        print("[Game][info] Toggling paused state")

        self.PAUSED = not self.PAUSED

    def get_score(self):
        print("[Game][info] Calculating score")

        return self.SCORE

    def print_score(self):
        print("[Game][info] Printing score")

        score = self.get_score()

        try:
            self.__display_message("Game\n\nOver!\n\nYour\n\nscore:\n\n%d" % score)
            self.pygame.display.update()
            self.pygame.time.wait(3000)
        except AttributeError:
            print("[Game][error] An error occurred printing score")

    def print_high_score(self):
        print("[Game][info] Printing high score: %d" % self.get_score())

        try:
            self.__display_message("Game\n\nOver!\n\nHigh\n\nscore:\n\n%d!" % self.get_score())
            self.pygame.display.update()
            self.pygame.time.wait(3000)
        except AttributeError:
            print("[Game][error] An error occurred printing high score")

    def finish(self):
        print("[Game][info] Finishing game")

        score = self.get_score()

        self.rgbmatrix.Clear()
        self.pygame_screen.fill((0, 0, 0))

        if self.db.contains(Query().score >= score):
            self.print_score()
        else:
            self.print_high_score()

        self.db.insert({'score': score})
        self.reset()

    def quit(self):
        print("[Game][info] Quitting game")

        self.rgbmatrix.Clear()
        self.pygame_screen.fill((0, 0, 0))
        self.__display_message("Quit...")
        self.pygame.display.update()
        self.pygame.quit()
        sys.exit()

    def reset(self):
        print("[Game][info] Resetting game")

        self.PAUSED = False
        self.GAMEOVER = False
        self.SCORE = 0
        self.LINES = 0
        self.LEVEL = 1

        self.board = Board(self.COLUMNS, self.ROWS)
        self.shape = None
        self.shapes_next = None
        self.__generate_shapes()

        self.pygame.time.set_timer(pygame.USEREVENT + 1, 0)
        self.pygame.display.update()

    def cleanup(self):
        print("[Game][info] Game clean up")

        try:
            self.rgbmatrix.Clear()
        except AttributeError:
            print("[Game][error] An error occurred cleaning up")

    def __exit__(self):
        print("[Game][info] Game exit")

        self.cleanup()
Ejemplo n.º 19
0
#!/usr/bin/env python3
import datetime
import time
from rgbmatrix import RGBMatrix, RGBMatrixOptions, graphics
import init

options = init.get_options()
canvas = RGBMatrix(options=options)

clockFont = graphics.Font()
clockFont.LoadFont("fonts/tom-thumb.bdf")

msgFont = graphics.Font()
msgFont.LoadFont("fonts/clR6x12.bdf")

blue = graphics.Color(0, 0, 255)
red = graphics.Color(255, 0, 0)

while True:
    graphics.DrawText(canvas, clockFont, 4, 5, blue,
                      str(datetime.datetime.now().strftime("%H:%M:%S")))
    graphics.DrawText(canvas, msgFont, 4, 20, red, "Line 2")
    time.sleep(0.1)
    canvas.Clear()
def main(myifname):

    # init the RGB matrix as 32 Rows, 2 panels (represents 32 x 64 panel), 1 chain
    MyMatrix = RGBMatrix(32, 2, 1)

    # Bits used for PWM. Something between 1..11. Default: 11
    MyMatrix.pwmBits = 11

    # Sets brightness level. Default: 100. Range: 1..100"
    MyMatrix.brightness = 100

    # Flood fill with white as a POST
    MyMatrix.Fill(255, 255, 255)
    time.sleep(2)
    MyMatrix.Clear()

    # Setup colours for text display
    ColorRED = graphics.Color(255, 0, 0)
    ColorGRN = graphics.Color(0, 255, 0)
    ColorBLU = graphics.Color(0, 0, 255)
    ColorWHI = graphics.Color(255, 255, 255)

    # Create the buffer canvas
    MyOffsetCanvas = MyMatrix.CreateFrameCanvas()

    # Load up the font (use absolute paths so script can be invoked from /etc/rc.local correctly)
    font = graphics.Font()
    font.LoadFont("/home/pi/rpi-rgb-led-matrix/fonts/5x8.bdf")

    # get the IP address of the interface specified on the command line (e.g. wlan0)
    ni.ifaddresses(myifname)
    myip = ni.ifaddresses(myifname)[2][0]['addr']

    # Show the interface, IP address and current time on the RGB led matrix for roughly 30 seconds (loop runs for 60 cycles with a 500ms delays, so roughly 30 seconds)
    for i in range(60):
        # grab current time and format
        thetime = time.strftime("%H:%M:%S")

        # run the "iwconfig" command passing in the ifname and capturing the output
        cmd = subprocess.Popen('iwconfig %s' % myifname, shell=True, stdout=subprocess.PIPE)

        # example output from "iwconfig wlp2s0" from Asus Eee PC R101 running lubuntu 16.04
        #
        # wlp2s0    IEEE 802.11bg  ESSID:"wapifoh"  
        # Mode:Managed  Frequency:2.437 GHz  Access Point: E8:FC:AF:2B:09:60   
        # Bit Rate=54 Mb/s   Tx-Power=20 dBm   
        # Retry short limit:7   RTS thr:off   Fragment thr:off
        # Power Management:off
        # Link Quality=30/70  Signal level=-80 dBm  
        # Rx invalid nwid:0  Rx invalid crypt:0  Rx invalid frag:0
        # Tx excessive retries:0  Invalid misc:2280   Missed beacon:0
        #

        # scan the output looking for key tokens of "Link Quality" "Level" and "ESSID"
        for line in cmd.stdout:
            if 'Link Quality' in line:
                pos = line.find('Quality=')
                quality = str_mid(line, pos+8, 5)

                pos = line.find('level=')
                level = str_mid(line, pos+6, 7)
            #endif
            
            if 'ESSID' in line:
                pos = line.find('ESSID:')
                essid = str_mid(line, pos+7, len(line)-pos-11)
            #endif
        #endfor

        # format the interface attributes into four lines
        line1 = str("%s %s" % (myifname, essid))
        line2 = str("%s %s" % (quality, level))
        line3 = str("%s" % myip)
        line4 = str("%s %s" % (thetime, str(i)))

        # clear matrix and print the four lines        
        MyOffsetCanvas.Clear()
        graphics.DrawText(MyOffsetCanvas, font, 0,  7, ColorRED, line1)
        graphics.DrawText(MyOffsetCanvas, font, 0, 15, ColorGRN, line2)
        graphics.DrawText(MyOffsetCanvas, font, 0, 23, ColorBLU, line3)
        graphics.DrawText(MyOffsetCanvas, font, 0, 31, ColorWHI, line4)

        # debug print
        print("line1=%s; line2=%s; line3=%s; line4=%s" % (line1,line2,line3,line4))
        
        time.sleep(0.5)
    
        MyOffsetCanvas = MyMatrix.SwapOnVSync(MyOffsetCanvas)
    #endwhile

    # tidy up and exit
    MyOffsetCanvas.Clear()

    # invoking autoexec.py	
    graphics.DrawText(MyOffsetCanvas, font, 0, 7, ColorWHI, "invoking:")
    graphics.DrawText(MyOffsetCanvas, font, 0, 15, ColorWHI, "autoexec.py")
    MyOffsetCanvas = MyMatrix.SwapOnVSync(MyOffsetCanvas)
    time.sleep(1.0)

    # invoke the autoeec.py python project in /projects with root permissions
    # Other python projects to run should replace autoexec.py with there own functionality
    # invoking with root allows these projects to do anything!
    cmd = subprocess.Popen('sudo python /home/pi/projects/autoexec.py', shell=True, stdout=subprocess.PIPE)
Ejemplo n.º 21
0
class scoreboard(object):
    def __init__(self):
        super(scoreboard, self).__init__()

    def sleep(self, sleep_period):
        """ Function to sleep if not in season or no game.
        Inputs sleep period depending if it's off season or no game."""

        # Get current time
        now = datetime.datetime.now()
        # Set sleep time for no game today
        if "day" in sleep_period:
            delta = datetime.timedelta(hours=12)
        # Set sleep time for not in season
        elif "season" in sleep_period:
            # If in August, 31 days else 30
            if now.month is 8:
                delta = datetime.timedelta(days=31)
            else:
                delta = datetime.timedelta(days=30)
        next_day = datetime.datetime.today() + delta
        next_day = next_day.replace(hour=12, minute=10)
        sleep = next_day - now
        sleep = sleep.total_seconds()
        time.sleep(sleep)

    def setup_nhl(self):
        """Function to setup the nhl_goal_light.py with team,
        team_id and delay"""
        """Try to find a settings.txt file in the folder to automaticly setup
        the goal light with pre-desired team and delay.
        settings.txt file should as such : Enter team_id and delay,
        each on a separate line in this order. LEAVE EMPTY if you want to
        manually input every time. If program can't find settings.txt file or if
        file is empty, it will ask for user input.
        """

        lines = ""
        team = ""
        team_id = ""
        settings_file = '/home/pi/nhlscoreboard/settings.txt'
        if os.path.exists(settings_file):
            # get settings from file
            f = open(settings_file, 'r')
            lines = f.readlines()

        # find team_id
        try:
            team_id = lines[1].strip('\n')
        except IndexError:
            team_id = ""
        if team_id == "":
            team = input(
                "Enter team you want to setup (without city) (Default: Canadiens) \n"
            )
            if team == "":
                team = "Canadiens"
            else:
                team = team.title()

            # query the api to get the ID
            team_id = nhl.get_team_id(team)

        # find delay
        try:
            delay = lines[2].strip('\n')
        except IndexError:
            delay = ""
        if delay is "":
            delay = input("Enter delay required to sync : \n")
            if delay is "":
                delay = 0
        delay = float(delay)
        delay = 0.0

        return (team_id, delay)

    def run(self):

        options = RGBMatrixOptions()
        options.rows = 32
        options.cols = 64
        options.chain_length = 4
        options.parallel = 1
        options.hardware_mapping = "adafruit-hat-pwm"
        options.pixel_mapper_config = "U-mapper"
        options.row_address_type = 0
        options.multiplexing = 0
        options.pwm_bits = 6
        options.brightness = 100
        options.pwm_lsb_nanoseconds = 130
        options.limit_refresh_rate_hz = 200
        options.led_rgb_sequence = "RBG"
        options.show_refresh_rate = 0
        options.gpio_slowdown = 1
        self.matrix = RGBMatrix(options=options)

        white = graphics.Color(255, 255, 255)
        gray = graphics.Color(127, 127, 127)
        green = graphics.Color(0, 150, 0)
        yellow = graphics.Color(127, 127, 0)
        red = graphics.Color(150, 0, 0)
        blue = graphics.Color(0, 0, 150)
        magenta = graphics.Color(127, 0, 127)
        cyan = graphics.Color(0, 127, 127)
        dim = graphics.Color(10, 10, 10)

        offscreen_canvas = self.matrix.CreateFrameCanvas()
        font = graphics.Font()

        #main_dir = os.getcwd()
        main_dir = "/home/pi/nhlscoreboard"

        width = 128
        height = 64
        font_medium = graphics.Font()
        font_medium.LoadFont("/home/pi/rpi-rgb-led-matrix/fonts/7x13.bdf")
        font_small = graphics.Font()
        font_small.LoadFont("/home/pi/rpi-rgb-led-matrix/fonts/6x10.bdf")
        font_big = graphics.Font()
        font_big.LoadFont("/home/pi/rpi-rgb-led-matrix/fonts/9x15.bdf")

        fontYoffset = 8
        fontYoffset2 = 8
        x_offset = -64

        gameday = False
        season = False
        home_roster = {}
        away_roster = {}
        home_score = 0
        home_score_old = 0
        away_score = 0
        away_score_old = 0
        home_team = ""
        away_team = ""
        live_stats_link = ""
        x = 0
        y = 10
        home_score_color = ""
        away_score_color = ""
        do_once = 1
        ignore_first_score_change = 1

        random.seed()
        choice = 1

        teams = {
            1: "NJD",
            2: "NYI",
            3: "NYR",
            4: "PHI",
            5: "PIT",
            6: "BOS",
            7: "BUF",
            8: "MTL",
            9: "OTT",
            10: "TOR",
            12: "CAR",
            13: "FLA",
            14: "TBL",
            15: "WSH",
            16: "CHI",
            17: "DET",
            18: "NSH",
            19: "STL",
            20: "CGY",
            21: "COL",
            22: "EDM",
            23: "VAN",
            24: "ANA",
            25: "DAL",
            26: "LAK",
            28: "SJS",
            29: "CBJ",
            30: "MIN",
            52: "WPG",
            53: "ARI",
            54: "VGK"
        }
        team_id, delay = self.setup_nhl()

        #image = Image.open("/home/pi/nhlscoreboard/images/goal.png")
        #self.matrix.SetImage(image.convert('RGB'))
        #time.sleep(5)

        try:

            while (True):

                time.sleep(2)

                # check if in season
                season = nhl.check_season()
                season = 1
                if season:

                    # check game
                    gameday = nhl.check_if_game(team_id)

                    if gameday:
                        # check end of game
                        game_end = nhl.check_game_end(team_id)

                        if not game_end:
                            try:
                                # get score, teams, and live stats link
                                home_score, home_team, away_score, away_team, live_stats_link = nhl.fetch_game(
                                    team_id)
                            except TypeError:
                                continue

                            # get stats from the game
                            current_period, home_sog, away_sog, home_powerplay, away_powerplay, time_remaining = nhl.fetch_live_stats(
                                live_stats_link)

                            if current_period > 0:

                                # get the rosters just once at the start
                                if do_once:
                                    while ((len(home_roster) < 5)
                                           or (len(away_roster) < 5)):
                                        home_roster, away_roster = nhl.fetch_rosters(
                                            live_stats_link)
                                    do_once = 0

                                # get the players on ice
                                home_on_ice, away_on_ice = nhl.players_on_ice(
                                    live_stats_link)
                                # build a list like so for each team
                                # jersey_number lastname
                                home_ice_list = []
                                away_ice_list = []
                                home_goalie_id, away_goalie_id = nhl.fetch_goalies(
                                    live_stats_link)
                                for the_id in home_on_ice:
                                    try:
                                        jersey_number = (
                                            home_roster['ID' + str(the_id)]
                                            ['jerseyNumber']).encode("ascii")
                                    except:
                                        jersey_number = "0"
                                    if int(jersey_number) < 10:
                                        try:
                                            jersey_number = jersey_number.decode(
                                                "utf-8") + ' '
                                        except:
                                            jersey_number = '00'
                                    else:
                                        try:
                                            jersey_number = jersey_number.decode(
                                                "utf-8")
                                        except:
                                            jersey_number = '00'

                                    try:
                                        last_name = ((
                                            (home_roster['ID' + str(the_id)]
                                             ['person']['fullName']).split(
                                                 ' ', 1))[1]
                                                     ).encode('utf-8').strip()
                                    except UnicodeEncodeError:
                                        last_name = ' '

                                    try:
                                        temp_thing = jersey_number + ' ' + (
                                            last_name[0:7].upper()
                                        ).decode("utf-8")
                                    except TypeError:
                                        temp_thing = ' '
                                    home_ice_list.append(temp_thing)
                                for the_id in away_on_ice:
                                    try:
                                        jersey_number = (
                                            away_roster['ID' + str(the_id)]
                                            ['jerseyNumber']).encode("ascii")
                                    except:
                                        jersey_number = '00'
                                    if int(jersey_number) < 10:
                                        try:
                                            jersey_number = jersey_number.decode(
                                                "ascii") + ' '
                                        except TypeError:
                                            jersey_number = 0
                                    else:
                                        jersey_number = jersey_number.decode(
                                            "utf-8")
                                    try:
                                        last_name = ((
                                            (away_roster['ID' + str(the_id)]
                                             ['person']['fullName']).split(
                                                 ' ', 1))[1]
                                                     ).encode('utf-8').strip()
                                    except TypeError:
                                        last_name = ' '
                                    try:
                                        temp_thing = jersey_number + ' ' + (
                                            last_name[0:7].upper()
                                        ).decode("utf-8")
                                    except TypeError:
                                        temp_thing = ' '
                                    away_ice_list.append(temp_thing)

                                # determine score colors
                                if home_score > away_score:
                                    home_score_color = red
                                    away_score_color = green
                                elif away_score > home_score:
                                    home_score_color = green
                                    away_score_color = red
                                else:
                                    home_score_color = green
                                    away_score_color = green

                                # determine team colors
                                if home_powerplay == 1:
                                    home_team_color = yellow
                                else:
                                    home_team_color = gray
                                if away_powerplay == 1:
                                    away_team_color = yellow
                                else:
                                    away_team_color = gray

                                # reset x and y
                                x = 0
                                y = 0

                                # clear the offscreen canvas
                                offscreen_canvas.Clear()

                                # teams
                                # away on left
                                # home on right
                                # 3-letter team, score, sog
                                graphics.DrawText(offscreen_canvas, font_small,
                                                  0, y + fontYoffset,
                                                  away_team_color,
                                                  teams[away_team])
                                graphics.DrawText(offscreen_canvas, font_small,
                                                  28, y + fontYoffset,
                                                  away_score_color,
                                                  str(away_score))
                                graphics.DrawText(offscreen_canvas, font_small,
                                                  49, y + fontYoffset, yellow,
                                                  str(away_sog))
                                y += 8
                                # players on ice
                                for line in away_ice_list:
                                    graphics.DrawText(offscreen_canvas,
                                                      font_small, 0,
                                                      y + fontYoffset, gray,
                                                      line)
                                    y += 8

                                # away on left
                                y = 0
                                # 3-letter team, score, sog
                                graphics.DrawText(offscreen_canvas, font_small,
                                                  64, y + fontYoffset,
                                                  home_team_color,
                                                  teams[home_team])
                                graphics.DrawText(offscreen_canvas, font_small,
                                                  92, y + fontYoffset,
                                                  home_score_color,
                                                  str(home_score))
                                graphics.DrawText(offscreen_canvas, font_small,
                                                  113, y + fontYoffset, yellow,
                                                  str(home_sog))
                                y += 8
                                # players on ice
                                for line in home_ice_list:
                                    graphics.DrawText(offscreen_canvas,
                                                      font_small, 64,
                                                      y + fontYoffset, gray,
                                                      line)
                                    y += 8

                                y = 64
                                status, time_remaining = nhl.intermission_status(
                                    live_stats_link)
                                if status == False:
                                    graphics.DrawText(
                                        offscreen_canvas, font_small, 35, y,
                                        cyan, "PERIOD " + str(current_period))
                                else:
                                    m, s = divmod(time_remaining, 60)
                                    graphics.DrawText(
                                        offscreen_canvas, font_small, 0, y,
                                        cyan, "INTERMISSION " +
                                        '{:02d}:{:02d}'.format(m, s))
                                # blit it to the screen
                                offscreen_canvas = self.matrix.SwapOnVSync(
                                    offscreen_canvas)

                                # If score change...
                                if home_score > home_score_old:
                                    home_score_old = home_score
                                    choice = random.randint(1, 3)
                                    if ignore_first_score_change == 0:
                                        if home_team == int(team_id):
                                            time.sleep(delay)
                                            image = Image.open(
                                                "/home/pi/nhlscoreboard/images/goal.png"
                                            )
                                            self.matrix.SetImage(
                                                image.convert('RGB'))
                                            time.sleep(5)
                                        else:
                                            time.sleep(delay)
                                            image = Image.open(
                                                "/home/pi/nhlscoreboard/images/sad-rod.gif"
                                            )
                                            self.matrix.SetImage(
                                                image.convert('RGB'))
                                            time.sleep(5)
                                    else:
                                        ignore_first_score_change = 0
                                else:
                                    home_score_old = home_score

                                # If score change...
                                if away_score > away_score_old:
                                    away_score_old = away_score
                                    choice = random.randint(1, 3)
                                    if ignore_first_score_change == 0:
                                        if away_team == int(team_id):
                                            time.sleep(delay)
                                            image = Image.open(
                                                "/home/pi/nhlscoreboard/images/goal.png"
                                            )
                                            self.matrix.SetImage(
                                                image.convert('RGB'))
                                            time.sleep(5)
                                        else:
                                            time.sleep(delay)
                                            image = Image.open(
                                                "/home/pi/nhlscoreboard/images/sad-rod.gif"
                                            )
                                            self.matrix.SetImage(
                                                image.convert('RGB'))
                                            time.sleep(5)
                                    else:
                                        ignore_first_score_change = 0

                                else:
                                    away_score_old = away_score

                                ignore_first_score_change = 0

                            if current_period == 0:
                                offscreen_canvas.Clear()
                                y = 7
                                x_offset = x_offset + 1
                                if x_offset > 128:
                                    x_offset = -128
                                graphics.DrawText(offscreen_canvas, font_small,
                                                  x + x_offset, y, blue,
                                                  "GAME TODAY!")
                                y += fontYoffset2
                                graphics.DrawText(offscreen_canvas, font_small,
                                                  x + 10 + x_offset, y, green,
                                                  "GAME TODAY!")
                                y += fontYoffset2
                                graphics.DrawText(offscreen_canvas, font_small,
                                                  x + 20 + x_offset, y, red,
                                                  "GAME TODAY!")
                                y += fontYoffset2
                                graphics.DrawText(offscreen_canvas, font_small,
                                                  x + 30 + x_offset, y, yellow,
                                                  "GAME TODAY!")
                                y += fontYoffset2
                                graphics.DrawText(offscreen_canvas, font_small,
                                                  x + 40 + x_offset, y,
                                                  magenta, "GAME TODAY!")
                                y += fontYoffset2
                                graphics.DrawText(offscreen_canvas, font_small,
                                                  x + 50 + x_offset, y, cyan,
                                                  "GAME TODAY!")
                                y += fontYoffset2
                                temptime = datetime.datetime.now()
                                graphics.DrawText(
                                    offscreen_canvas, font_small, 0, y, gray,
                                    temptime.strftime("%m/%d/%y %H:%M"))
                                y += fontYoffset2
                                game_start_time = nhl.fetch_game_start_time(
                                    live_stats_link)
                                graphics.DrawText(
                                    offscreen_canvas, font_small, 0, y, gray,
                                    "GAMETIME: " + game_start_time)
                                offscreen_canvas = self.matrix.SwapOnVSync(
                                    offscreen_canvas)

                        else:
                            home_roster.clear()
                            away_roster.clear()
                            old_score = 0  # Reset for new game
                            current_period = 0
                            self.matrix.Clear()
                            offscreen_canvas.Clear()
                            do_once = 1
                            self.sleep("day")  # sleep till tomorrow
                    else:
                        print("No Game Today!")
                        self.sleep("day")  # sleep till tomorrow
                else:
                    print("OFF SEASON!")
                    self.sleep("season")  # sleep till next season

        except KeyboardInterrupt:
            print("\nCtrl-C pressed")
Ejemplo n.º 22
0
class LedMatrixRGB(object):
    """ Gives interface for the 3D.
    """
    def __init__(self, nx=None, ny=None, color=None, power=0):
        self.matrix_opts = RGBMatrixOptions()
        self.set_power(0)
        self.nx = nx
        self.ny = ny
        self.set_options()

    def set_options(self):
        self.matrix_opts.rows = 32
        self.matrix_opts.chain_length = 1
        # self.matrix_opts.parallel = 1
        self.matrix_opts.pwm_bits = 1
        self.matrix_opts.pwm_lsb_nanoseconds = 200
        self.matrix_opts.drop_privileges = True
        self.matrix_opts.hardware_mapping = 'regular'
        # self.matrix_opts.gpio_slowdown=1
        self.matrix = RGBMatrix(options=self.matrix_opts)

    def set_power(self, power):
        """ Adjusts power manually between 0-255.
        """
        print('doit')

    def set_pixel(self, x, y, power, color):
        self.matrix.Clear()
        nx, ny, power = int(x), int(y), int(power)
        if color == 'R':
            self.matrix.SetPixel(nx, ny, power, 0, 0)
        if color == 'G':
            self.matrix.SetPixel(nx, ny, 0, power, 0)
        if color == 'B':
            self.matrix.SetPixel(nx, ny, 0, 0, power)

    def set_pattern(self, pattern, power, color):
        self.matrix.Clear()
        matrix = fpmm.hex_decode(pattern)
        offset_canvas = self.matrix.CreateFrameCanvas()
        xx , yy = np.where(matrix==1)
        for x, y in (zip(xx, yy)):
            nx = int(x)
            ny = int(y)
            power = int(power)
            if color == 'R':
                offset_canvas.SetPixel(nx, ny, power, 0, 0)
            if color == 'G':
                offset_canvas.SetPixel(nx, ny, 0, power, 0)
            if color == 'B':
                offset_canvas.SetPixel(nx, ny, 0, 0, power)
            # offset_canvas.SetPixel(nx, ny, power, color)
        offset_canvas = self.matrix.SwapOnVSync(offset_canvas)

        # nx, ny, power = int(x), int(y), int(power)
        # if color == 'R':
        #     self.matrix.SetPixel(nx, ny, power, 0, 0)
        # if color == 'G':
        #     self.matrix.SetPixel(nx, ny, 0, power, 0)
        # if color == 'B':
        #     self.matrix.SetPixel(nx, ny, 0, 0, power)

    def __del__(self):
        print('Goodbye')
Ejemplo n.º 23
0
class LedDisplay:
    def __init__(self):
        # Configuration for the matrix
        options = RGBMatrixOptions()
        options.rows = 32
        options.cols = 32
        options.chain_length = 1
        options.parallel = 1
        options.gpio_slowdown = 5
        options.hardware_mapping = 'adafruit-hat'

        # Enter in the hardware configurations
        self.matrix = RGBMatrix(options=options)

        # Specifications for Font style of text
        self.font = graphics.Font()
        self.font.LoadFont("rpi-rgb-led-matrix/fonts/4x6.bdf")
        self.textColor = graphics.Color(100, 100, 100)
        self.fontWidth = 4
        self.fontHeight = 6

        self.canvas = self.matrix.CreateFrameCanvas()

    def clear(self):
        self.matrix.Clear()
        self.canvas.Clear()

    def show(self, info):
        # first attempt at code that will print multiple lines, could be rerwitten to be easier
        if type(info) == tuple:
            self.fontHeight = 6  # random constant depending on which font is chosen
            index = self.fontHeight  # First line in which text can be placed on matrix

            for elem in info:
                graphics.DrawText(self.canvas, self.font, 0, index,
                                  self.textColor, elem)
                index += self.fontHeight  # move to next line on matrix

            self.canvas = self.matrix.SwapOnVSync(self.canvas)

        elif type(info) == str:
            if len(info) > 8:
                pos = self.canvas.width
                while True:
                    self.canvas.Clear()
                    length = graphics.DrawText(self.canvas, self.font, pos, 10,
                                               self.textColor, info)
                    pos -= 1
                    if (pos + length < 0):
                        pos = self.canvas.width

                    time.sleep(0.05)
                    self.canvas = self.matrix.SwapOnVSync(self.canvas)
            else:
                graphics.DrawText(self.canvas, self.font, 0, 10,
                                  self.textColor, info)
                self.canvas = self.matrix.SwapOnVSync(self.canvas)

        elif type(info) == list:
            for r in range(self.matrix.height):
                for c in range(self.matrix.width):
                    R, G, B = info[r][c]
                    self.canvas.SetPixel(r, c, R, G, B)
            self.canvas = self.matrix.SwapOnVSync(self.canvas)

        else:
            print("Invalid input: must be a tuple or a list")
            raise ValueError

    def getTextDimensions(self):
        return int(self.matrix.height / self.fontHeight), int(
            self.matrix.width / self.fontWidth)
Ejemplo n.º 24
0
class MatrixDisplay(object):
    matrix_w = 64
    matrix_h = 64
    options = RGBMatrixOptions()
    options.rows = matrix_h
    options.cols = matrix_w
    options.chain_length = 1
    options.parallel = 1
    options.hardware_mapping = 'adafruit-hat'
    chipSize = (6, 6)  # 6px by 6px chip

    def __init__(self,
                 player1Color=(200, 200, 0),
                 player2Color=(200, 0, 0),
                 boardColor=(0, 0, 210),
                 gridSize=(6, 8),
                 rotation=0):
        self.gridSize = gridSize  # rows x cols
        self.rotation = rotation
        self.matrix = RGBMatrix(options=MatrixDisplay.options)
        self.matrix.Clear()
        self.absoluteWidth = 64
        self.absoluteHeight = 64
        self.setRotation(rotation)
        self.width = MatrixDisplay.matrix_w
        self.height = MatrixDisplay.matrix_h
        self.colors = {
            "player1": player1Color,
            "player2": player2Color,
            "board": boardColor
        }

    # * draw the board upon each call. Output the board along with a possible selection if wanted
    def update(self, grid, hoveredCol=None, currentPlayer=None):
        #self.matrix.Clear()
        #self.drawBoard()
        for row in range(self.gridSize[0]):
            for col in range(self.gridSize[1]):
                gridVal = grid[row][col]
                chipColor = (0, 0, 0)
                if gridVal == 0:
                    chipColor = self.colors["player1"]
                elif gridVal == 1:
                    chipColor = self.colors["player2"]
                self.drawChip(5 - row, col, chipColor)
        if hoveredCol != None:
            chipColor = self.colors[
                "player1"] if currentPlayer == 0 else self.colors["player2"]
            self.drawHoverChip(hoveredCol, chipColor)

    def drawChip(self, y, x, color):
        # display a chip at (x,y) location with given color
        chipColor = color
        #print("Drawing chip at {}, {}".format(x, y))
        self.drawRect((x * 8) + 1, 18 + (y * 8), (x * 8) + 6, 23 + (y * 8),
                      chipColor)

    def drawBoard(self):
        #print("Drawing board")
        # draw the virtual grid to screen
        boardColor = self.colors["board"]
        self.drawRect(0, 16, 0, 63, boardColor)
        self.drawRect(63, 16, 63, 63, boardColor)
        # draw vertical lines
        for x in range(7):
            self.drawRect((x * 8) + 7, 16, (x * 8) + 8, 63, boardColor)
        # draw horizontal lines
        for y in range(6):
            self.drawRect(0, (y * 8) + 16, 63, (y * 8) + 17, boardColor)

    def drawHoverChip(self, col, color):
        # draw a chip over a column when user is making a choice
        chipColor = color
        self.drawRect(0, 0, 63, 16, (0, 0, 0))
        self.drawRect((col * 8) + 1, 4, (col * 8) + 6, 9, chipColor)

    def drawWinScreen(self, winningPlayer):
        self.matrix.Clear()
        # display the winning player or tie if there is one (winningPlayer = 2)
        font = graphics.Font()
        font.LoadFont("./fonts/6x12.bdf")
        if winningPlayer == 2:
            graphics.DrawText(self.matrix, font, 5, 25,
                              graphics.Color(200, 200, 200), "It's a tie!")
        else:
            graphics.DrawText(self.matrix, font, 5, 15,
                              graphics.Color(200, 200, 200), "Congrats")
            graphics.DrawText(self.matrix, font, 5, 30,
                              graphics.Color(200, 200, 200),
                              "player {},".format(winningPlayer + 1))
            graphics.DrawText(self.matrix, font, 5, 45,
                              graphics.Color(200, 200, 200), "nice job!")

    def drawStartScreen(self, startingPlayer):
        self.matrix.Clear()
        # show the start screen along with who is going first
        font = graphics.Font()
        font.LoadFont("./fonts/6x12.bdf")
        graphics.DrawText(self.matrix, font, 5, 25,
                          graphics.Color(200, 200, 200),
                          "Player {}".format(startingPlayer))
        graphics.DrawText(self.matrix, font, 5, 60,
                          graphics.Color(200, 200, 200), "starts")

    def playAgainAsk(self):
        font = graphics.Font()
        font.LoadFont("./fonts/6x12.bdf")
        graphics.DrawText(self.matrix, font, 2, 10,
                          graphics.Color(200, 200, 200), "Play again?")

    def drawPlayAgainScreen(self, choice):
        #self.matrix.Clear()
        # * choice is an int for the choice being hovered
        # show the play again selection screen
        font = graphics.Font()
        font.LoadFont("./fonts/6x12.bdf")
        graphics.DrawText(
            self.matrix, font, 2, 30,
            graphics.Color(0, 200, 0) if choice == 0 else graphics.Color(
                200, 200, 200), "Yes")
        graphics.DrawText(
            self.matrix, font, 48, 30,
            graphics.Color(0, 200, 0) if choice == 1 else graphics.Color(
                200, 200, 200), "No")

    def colorTupleToColor(self, color):
        return graphics.Color(color[0], color[1], color[2])

    def drawRect(self, x1, y1, x2, y2, color):
        for x in range(x1, x2 + 1):
            for y in range(y1, y2 + 1):
                newX, newY = self.mapPixelToRotation(x, y)
                #print(newX, newY, sep=',')
                self.matrix.SetPixel(newX, newY, color[0], color[1], color[2])

    def mapPixelToRotation(self, x, y):
        if (x < 0) or (y < 0) or (x >= self.width) or (y >= self.height):
            #print("x was {} and y was {}".format(x,y))
            return None, None
        t = 0
        if self.rotation == 1:
            t = x
            x = self.absoluteWidth - 1 - y
            y = t
        elif self.rotation == 2:
            x = self.absoluteWidth - 1 - x
            y = self.absoluteHeight - 1 - y
        elif self.rotation == 3:
            t = x
            x = y
            y = self.absoluteHeight - 1 - t
        return x, y

    def setRotation(self, r):
        self.rotation = (r & 3)
        if self.rotation == 0:
            pass
        elif self.rotation == 2:
            self.width = self.absoluteWidth
            self.height = self.absoluteHeight
        elif self.rotation == 1:
            pass
        elif self.rotation == 3:
            self.width = self.absoluteHeight
            self.height = self.absoluteWidth
Ejemplo n.º 25
0
class PulseLedView(object):
    def __init__(self, *args, **kwargs):
        self.parser = argparse.ArgumentParser()

        self.parser.add_argument("-r", "--led-rows", action="store", help="Display rows. 16 for 16x32, 32 for 32x32. Default: 32", default=32, type=int)
        self.parser.add_argument("-c", "--led-chain", action="store", help="Daisy-chained boards. Default: 2.", default=2, type=int)
        self.parser.add_argument("-P", "--led-parallel", action="store", help="For Plus-models or RPi2: parallel chains. 1..3. Default: 1", default=1, type=int)
        self.parser.add_argument("-p", "--led-pwm-bits", action="store", help="Bits used for PWM. Something between 1..11. Default: 11", default=11, type=int)
        self.parser.add_argument("-b", "--led-brightness", action="store", help="Sets brightness level. Default: 100. Range: 1..100", default=100, type=int)
        self.parser.add_argument("-m", "--led-gpio-mapping", help="Hardware Mapping: regular, adafruit-hat, adafruit-hat-pwm Default: adafruit-hat" , choices=['regular', 'adafruit-hat', 'adafruit-hat-pwm'], default="adafruit-hat", type=str)
        self.parser.add_argument("--led-scan-mode", action="store", help="Progressive or interlaced scan. 0 Progressive, 1 Interlaced (default)", default=1, choices=range(2), type=int)
        self.parser.add_argument("--led-pwm-lsb-nanoseconds", action="store", help="Base time-unit for the on-time in the lowest significant bit in nanoseconds. Default: 130", default=130, type=int)
        self.parser.add_argument("--led-show-refresh", action="store_true", help="Shows the current refresh rate of the LED panel")
        self.parser.add_argument("--led-slowdown-gpio", action="store", help="Slow down writing to GPIO. Range: 1..100. Default: 1", choices=range(3), type=int)
        self.parser.add_argument("--led-no-hardware-pulse", action="store", help="Don't use hardware pin-pulse generation")
        self.parser.add_argument("--led-rgb-sequence", action="store", help="Switch if your matrix has led colors swapped. Default: RGB", default="RGB", type=str)
        self.parser.add_argument("--cache-location", action="store", help="Location of the cache folder Default: ./pulse-cache", default="./pulse-cache", type=str)
        self.parser.add_argument("--log-level", action="store", help="Log level Default: DEBUG", default="DEBUG", type=str)

    def initialize_and_run(self):
        self.args = self.parser.parse_args()

        logging_level = logging.getLevelName(self.args.log_level)
        self.logging = logging.basicConfig(level=logging_level, format='%(asctime)-15s [%(levelname)s] (%(threadName)-10s) %(message)s', )

        logging.info("Initializing LED matrix...")
        options = RGBMatrixOptions()

        if self.args.led_gpio_mapping != None:
          options.hardware_mapping = self.args.led_gpio_mapping

        options.rows = self.args.led_rows
        options.chain_length = self.args.led_chain
        options.parallel = self.args.led_parallel
        options.pwm_bits = self.args.led_pwm_bits
        options.brightness = self.args.led_brightness
        options.pwm_lsb_nanoseconds = self.args.led_pwm_lsb_nanoseconds
        options.led_rgb_sequence = self.args.led_rgb_sequence

        if self.args.led_show_refresh:
          options.show_refresh_rate = 1

        if self.args.led_slowdown_gpio != None:
            options.gpio_slowdown = self.args.led_slowdown_gpio

        if self.args.led_no_hardware_pulse:
          options.disable_hardware_pulsing = True

        self.matrix = RGBMatrix(options = options)

        #self.led_pulse_cache = FanoutCache(self.args.cache_location, shards=20, timeout=1)
        self.columns = self.args.led_rows * self.args.led_chain
        self.rows = 32

        # TODO: configure me
        self.pulse_events_url = "http://192.168.1.7:9201/events"

        # TODO: configure me
        self.target_fps = 24.
        self.time_per_frame_ms = (1 / self.target_fps) * 1000.

        self.draw_state = DrawState()
        self.stop_event = threading.Event()

        try:
            # Start loop
            print("Press CTRL-C to stop sample")
            self.run()
        except KeyboardInterrupt:
            print("Exiting\n")
            self.stop_event.set()
            sys.exit(0)

        return True

    def draw_text(self, matrix, x, y, text, size = 20):
        font = ImageFont.truetype('fonts/FiraCode-Regular.ttf', size)
        image = Image.new("RGB", (self.columns, self.rows))
        draw = ImageDraw.Draw(image)

        text_width, text_height = font.getsize(text)

        draw.text((x - text_width/2 ,y - text_height/2), text, font=font, fill=(41,161,228,0))

        self.matrix.SetImage(image.convert('RGB'))

    def draw_logo(self):
        logging.info("Display TS logo...")
        logo_image = Image.open("images/tradeshift.jpg")
        logo_image.thumbnail((self.columns, self.rows), Image.ANTIALIAS)
        logo_image_width, logo_image_height = logo_image.size

        x = (self.columns - logo_image_width) / 2
        y = (self.rows - logo_image_height) / 2

        self.matrix.SetImage(logo_image.convert('RGB'), x, y)

    def countdown(self):
        for value in reversed(range(0, 10)):
            self.draw_text(self.matrix, (self.columns / 2), (self.rows / 2), str(value), 20)
            sleep(0.125)

        self.matrix.Clear()

    def run(self):
        self.draw_logo()
        sleep(2)
        self.countdown()

        pulse_data_producer = PulseDataProducer(self.draw_state,
                                                self.stop_event,
                                                self.pulse_events_url,
                                                self.target_fps,
                                                self.columns,
                                                self.rows
                                               )

        pulse_led_panel_output = PulseLedPanelOutput( self.draw_state,
                                                self.stop_event,
                                                self.matrix,
                                                self.target_fps,
                                                self.columns,
                                                self.rows
                                               )

        producer_thread = threading.Thread(name='data-producer-thread',
                                   target=pulse_data_producer.run)
        producer_thread.setDaemon(True)
        producer_thread.start()

        draw_thread = threading.Thread(name='data-draw-thread',
                                       target=pulse_led_panel_output.run,)
        draw_thread.setDaemon(True)
        draw_thread.start()

        producer_thread.join()
        draw_thread.join()
Ejemplo n.º 26
0
def to_matrix(minutes):
	# How fast for testing
	sleep_i = 1
	
	# matrix options set here
	options = RGBMatrixOptions()	
	options.rows = 32
	options.chain_length = 2
	options.hardware_mapping = 'adafruit-hat'
	options.parallel = 1

	# orient_image arguments here
	mat_x = options.chain_length * options.rows
	mat_y = options.rows
	char_w = 8
	char_h = 13
	num_chars = 8
	lines= 1
	O = orient_image(mat_x, mat_y, char_w ,char_h, num_chars,lines)
	
	matrix = RGBMatrix(options = options)
	image = Image.new("RGB", (64, 32))
	draw = ImageDraw.Draw(image)
	matrix.Clear()
	
	# image files found in respective directories
	png = PNG_8x13
	# create the countdown timer here
	T = timer(minutes)

	try:
# First for loop takes the initial list of lists and starts itering through
		print 'countdown timer started'
		while 1:		
			for i in T:
# Second for loop takes each individual list itme and iters through, printing to the matrix
				# this updates later according to the offset
				x_matrix_pos = O[0]
				# with a single row of chars this wont change
				y_matrix_pos = O[1]
				# this is how far away the next char will print from the previous
				x_matrix_offset = O[2]
				print i
				for j in i:
					#print "i ", i,"\nj ", j
					image = Image.open("%s" % png[j])
					image.load()
					matrix.SetImage(image.convert('RGB'),x_matrix_pos, y_matrix_pos)
					x_matrix_pos += x_matrix_offset
				
				sleep(sleep_i)

			# display zero status at the end of the timer
			print "countdown timer finished"
			while 1:
				# last list item in timer
				zero_status = T[-1]

				x_matrix_pos = O[0]
				y_matrix_pos = O[1]
				x_matrix_offset = O[2]
				
				for i in zero_status:
					image = Image.open("%s" % png[i])
					image.load()
					matrix.SetImage(image.convert('RGB'),x_matrix_pos, y_matrix_pos)
					x_matrix_pos += x_matrix_offset

	except Exception as e:
		matrix.Clear()
		print e

	except KeyboardInterrupt:
		matrix.Clear()
		print 'sorry to see you go'
Ejemplo n.º 27
0

client = MQTTClient(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY)  #initialize MQTT
client.on_connect = connected  #setup connect action
client.on_disconnect = disconnected  #setup disconnect action
client.on_message = message  #setup message action
client.connect()  #connect to MQTT
client.loop_background()  #continue a loop in background

while True:  #forever loop
    mean = mn * 4  #set variable mean to the actual mean times 4
    if mn > 7:  #if actual mean is greater than seven, set colour to green
        r = 0
        g = 255
        b = 0
    else:  #if not greater than seven, set colour to red
        r = 255
        g = 0
        b = 0
    image = Image.new("RGB", (64, 64))  #create new RGB image
    draw = ImageDraw.Draw(image)  #draw on image
    draw.text((0, 50), "Average:" + str(mn),
              (0, 0, 255))  #create text showing average
    draw.rectangle(
        (0, 0, mean, mean),
        fill=(r, g, b))  #create rectangle from 0,0 to mean,mean (mn*4,mn*4)
    matrix.Clear()  #clear the matrix if value has decreased
    matrix.SetImage(image, 0,
                    0)  #set the image on the matrix to the one just drawn
    time.sleep(60)  #wait a minute
Ejemplo n.º 28
0
        matrix.SetImage(downscaled, 0, 0)

        time.sleep(1)
        time_is += step


def testMoonColors():
    img = Image.new('RGB', (dimen, dimen), 'black')
    draw = ImageDraw.Draw(img)
    for i in range(0, len(moonColors)):
        fullColor = moonColors[i]
        draw.pieslice((start, start, diameter + start, diameter + start),
                      -180,
                      180,
                      fill=fullColor)

        downscaled = getDownscaledImg(img)
        matrix.Clear()
        matrix.SetImage(downscaled, 0, 0)

        time.sleep(2)


#testMoonColors()
runStart()
matrix.Clear()
runMoonClockQuick()
#runMoonClock()

matrix.Clear()
Ejemplo n.º 29
0
def main(args):
    device_lat = args.device_lat
    device_long = args.device_long
    feeder_url = args.fr24_feeder_host
    fonts_home = args.fonts_home

    # Configuration for the LED matrix
    options = RGBMatrixOptions()
    options.cols = 64
    options.rows = 32
    options.chain_length = 1
    options.brightness = 40
    options.pwm_dither_bits = 1
    options.pwm_lsb_nanoseconds = 50
    options.parallel = 1
    options.gpio_slowdown = 2  # reduces flicker
    #options.hardware_mapping = 'regular'  # If you have an Adafruit HAT: 'adafruit-hat'

    matrix = RGBMatrix(options=options)
    font = graphics.Font()
    font.LoadFont(f'{fonts_home}/5x7.bdf')
    font2 = graphics.Font()
    font2.LoadFont(f'{fonts_home}/6x10.bdf')

    green = graphics.Color(0, 255, 0)
    graphics.DrawText(matrix, font, 0, 7, green, 'No aircraft')
    graphics.DrawText(matrix, font, 0, 14, green, 'found')

    try:
        print('Press CTRL-C to stop.')
        while True:
            t = threading.Thread(target=get_aircraft(feeder_url))
            t.run()
            if aircraft_change:
                logger.info('Refreshing aircraft list')
                matrix.Clear()
                index = 1
                if len(aircraft_map.keys()) > 0:
                    for aircraft in aircraft_map.keys():
                        matrix.Clear()
                        aircraft_mode_s_transponder = aircraft_map.get(aircraft)[0]
                        aircraft_lat = aircraft_map.get(aircraft)[1]
                        aircraft_long = aircraft_map.get(aircraft)[2]
                        aircraft_ground_speed = aircraft_map.get(aircraft)[5]
                        aircraft_squawk = aircraft_map.get(aircraft)[6]
                        aircraft_callsign = aircraft_map.get(aircraft)[-1]

                        # Draw ADS-B Mode S transponder code
                        graphics.DrawText(matrix, font, 0, index * 7, green, f'ModeS: {aircraft_mode_s_transponder}')

                        # Draw aircraft callsign
                        if aircraft_callsign:
                            graphics.DrawText(matrix, font, 0, (index + 1) * 7, green, f'Sign:  {aircraft_callsign}')
                        else:
                            graphics.DrawText(matrix, font, 0, (index + 1) * 7, green, f'Sign: unknown')

                        if aircraft_lat and aircraft_long:
                            geodesic_dict = Geodesic.WGS84.Inverse(float(device_lat), float(device_long), aircraft_lat,
                                                                   aircraft_long)
                            azimuth = geodesic_dict['azi1']
                            distance_meters = geodesic_dict['s12']
                            distance_miles = 0.000621371 * distance_meters
                            heading = float(azimuth)
                            logger.info(f'heading: {heading:.3f}')

                            # Correct for negative headings
                            if heading < 0:
                                heading = heading + 360
                                logger.info(f'corrected heading: {heading:.3f}')

                            cardinal_direction = get_direction_from_heading(heading)
                            logger.info(f'cardinal direction: {cardinal_direction}')

                            # adjust heading from display orientation
                            display_heading = 240.0
                            adjusted_heading = 360 - display_heading + heading
                            logger.info(f'adjusted heading: {adjusted_heading:.3f}°')
                            # correct for heading over 360°
                            if adjusted_heading > 360:
                                adjusted_heading = adjusted_heading - 360
                                logger.info(f'adjusted heading (corrected): {adjusted_heading:.3f}°')
                            arrow_direction = get_direction_from_heading(adjusted_heading)

                            # Draw cardinal direction and arrow
                            graphics.DrawText(matrix, font2, 0, ((index + 2) * 7) + 1, green, cardinal_direction)
                            graphics.DrawText(matrix, font2, 0, ((index + 3) * 7) + 2, green, cardinal_arrows_map[
                                arrow_direction])
                            graphics.DrawText(matrix, font2, 22, ((index + 3) * 7) + 2, green, f'{distance_miles:.2f} mi')
                        else:
                            graphics.DrawText(matrix, font2, 0, ((index + 2) * 7) + 1, green, '?')
                            graphics.DrawText(matrix, font2, 0, ((index + 3) * 7) + 2, green, '?')
                        if aircraft_ground_speed:
                            graphics.DrawText(matrix, font2, 22, ((index + 2) * 7) + 1, green, f'{aircraft_ground_speed} kts')
                        time.sleep(10)
                else:
                    graphics.DrawText(matrix, font, 0, 7, green, "No aircraft")
                    graphics.DrawText(matrix, font, 0, 14, green, "found")

            time.sleep(60)
    except KeyboardInterrupt:
        sys.exit(0)