class InfoMatrix(object): def __init__(self): self._matrix = Adafruit_RGBmatrix(32, 1) self._font = ImageFont.truetype("/usr/share/fonts/truetype/freefont/FreeSans.ttf", 12) @staticmethod def _image_draw(): image = Image.new('RGB', (32, 32), 'black') draw = ImageDraw.Draw(image) return image, draw def update_weather(self, temp, percip): image, draw = self._image_draw() draw.text( (1, 0), '{0} f'.format(int(round(temp))), (255, 0, 0), font=self._font) draw.text( (1, 13), percip, (255, 0, 0), font=self._font) self._matrix.Clear() self._matrix.SetImage(image.im.id, 0, 0) def write_bus(self, route, prediction): image, draw = self._image_draw() draw.text((0, 0), '{0}:'.format(route), (255, 0, 0), font=self._font) draw.text((0, 13), prediction, (255, 0, 0), font=self._font) self._matrix.Clear() self._matrix.SetImage(image.im.id, 0, 0)
class drawing_app_matrix: def __init__(self): # Initialize LED Matrix self.matrix = Adafruit_RGBmatrix(32, 1) def main(self, arg1, arg2): self.matrix.Clear() # INPUT pix = arg1 rainbow = arg2 # end INPUT #print_to_matrix_default(canvas_pix) if rainbow: for x in range(0, 32): for y in range(0, 32): if pix[x][y] == 1: self.matrix.SetPixel(x, y, randint(0, 255), randint(0, 255), randint(0, 255)) else: for x in range(0, 32): for y in range(0, 32): if pix[x][y] == 1: self.matrix.SetPixel(x, y, 255, 0, 0) def clear_matrix(self): self.matrix.Clear() if __name__ == "__main__": main(sys.argv[1], sys.argv[2])
def main(argv): # init led matrix matrix = Adafruit_RGBmatrix(32, 1) matrix.Clear() # file name inputfile = '' try: opts, args = getopt.getopt(argv, "hi:o:", ["ifile="]) except getopt.GetoptError: print 'test.py -i <inputfile>' sys.exit(2) for opt, arg in opts: if opt == '-h': print 'test.py -i <inputfile>' sys.exit() elif opt in ("-i", "--ifile"): inputfile = arg # play print 'Input file is ', inputfile image = Image.open(inputfile) image.load() matrix.SetImage(image.im.id, 0, 1) time.sleep(10.0) matrix.Clear()
def loop(): from rgbmatrix import Adafruit_RGBmatrix matrix = Adafruit_RGBmatrix(MATRIX_SIZE,1) while(True): run(matrix) time.sleep(REFRESH_INTERVAL) matrix.Clear()
class input_triggered_matrix: def __init__(self): # Initialize LED Matrix self.matrix = Adafruit_RGBmatrix(32, 1) def main(self, arg1, arg2): # INPUT word = arg1 score = arg2 # end INPUT # Initialize canvas canvas_pix = numpy.zeros((32, 32)) # Word input -> canvas canvas_pix = overlayAt(1, 4, stringtopix(word), canvas_pix, 1) # Scoreboard -> canvas canvas_pix = overlayAt(1, 16, stringtopix("Score:"), canvas_pix, 1) # Score input -> canvas canvas_pix = overlayAt(1, 24, stringtopix(str(score)), canvas_pix, 1) # print_to_matrix_default(canvas_pix) for x in range(0,32): for y in range(0,32): if canvas_pix[x][y] == 1: self.matrix.SetPixel(x,y,255,0,0) # time.sleep(1.0) # matrix.Clear() def clear_matrix(self): self.matrix.Clear() def clear_word(self,score): # Initialize canvas canvas_pix = numpy.zeros((32, 32)) # Word input -> canvas #canvas_pix = overlayAt(1, 4, stringtopix(word), canvas_pix, 1) # Scoreboard -> canvas canvas_pix = overlayAt(1, 16, stringtopix("Score:"), canvas_pix, 1) # Score input -> canvas canvas_pix = overlayAt(1, 24, stringtopix(str(score)), canvas_pix, 1) # print_to_matrix_default(canvas_pix) for x in range(0,32): for y in range(0,32): if canvas_pix[x][y] == 1: self.matrix.SetPixel(x,y,255,0,0) if __name__ == "__main__": main(sys.argv[1], sys.argv[2])
class Matrix: def __init__(self, height, chains): self.matrix = Adafruit_RGBmatrix(height, chains) self.MAX_Y = height self.MAX_X = height * chains self.obj_list = [] self.setBG(0x000000) def setBG(self, hex_color): self.BG = hex_color self.drawBG() def setBoard(self, board_num, rgb): self.fillRect(board_num*self.MAX_Y, 0, board_num*self.MAX_Y + self.MAX_Y, self.MAX_Y, rgb) def drawBG(self): self.matrix.Fill(self.BG) def clear(self): self.matrix.Clear() def setPixel(self, x, y, rgb): self.matrix.SetPixel(x, y, *rgb) def fillRect(self, x1, y1, x2, y2, rgb): for x in range(x1, x2): for y in range(y1, y2): self.setPixel(x, y, rgb) def drawPointList(self, plist, rgb): for point in plist: self.setPixel(point[0],point[1], rgb) def drawImage(self, file_name): image = Image.open(file_name) raw = image.load() for x in range(0,30): for y in range(0,63): rgb = raw[y, x] if rgb == (0,0,0): #If you wanted to make the background another color self.setPixel(y,x, (0,0,0)) else: self.setPixel(y, x, (rgb[0], rgb[1], rgb[2])) def refresh(self): self.drawBG() for obj in self.obj_list: obj.draw() def getMatrix(self): return self.matrix
class RGB_Matrix(Device): """ Handles output to the Adafruit RGB Matrix """ def __init__(self): self.capabilities(MATRIX_WIDTH, MATRIX_HEIGHT, mode="RGB") # Use Adafruit's RGB Matrix class from rgbmatrix import Adafruit_RGBmatrix self._matrix = Adafruit_RGBmatrix(32, 1) def display(self): self._matrix.SetImage(self.image.im.id) def clear(self): self._matrix.Clear() self.image = Image.new(self.mode, self.size)
def main(): if len(sys.argv) != 2: sys.exit('usage: {} <src_dir>'.format(sys.argv[0])) if not os.path.isdir(sys.argv[1]): sys.exit('{} is not a directory'.format(sys.argv[1])) dir_src = os.path.normpath(sys.argv[1]) images = sorted(list_files_with_ext(dir_src, JPEG)) matrix = Adafruit_RGBmatrix(MATRIX_SIZE, MATRIX_CHAIN) try: while True: for image in images: im = Image.open(image) im.load() matrix.SetImage(im.im.id, 0, 0) time.sleep(SLEEP) except KeyboardInterrupt: pass matrix.Clear()
class Printer: def __init__(self): self.font_width = 6 self.font_height = 10 self.max_char_width = 9 self.max_char_height = 2 self.matrix = Adafruit_RGBmatrix(32, 2) self.fontfile = os.path.join( os.path.dirname(os.path.abspath(__file__)), "fonts/{0}x{1}.bdf".format(self.font_width, self.font_height)) self.offset = [0, 0] def offset_x(self): return self.offset[0] * self.font_width def offset_y(self): return self.offset[1] * self.font_height def draw_char(self, char): # If return, set offset to new line try: test = ord(char) == 10 except TypeError: test = False if test: self.offset[0] = 0 self.offset[1] += 1 else: self.matrix.DrawText(self.fontfile, self.offset_x(), self.offset_y(), 0xFF, 0xFF, 0xFF, char) self.offset[0] += 1 if self.offset[0] > self.max_char_width: self.offset[0] = 0 self.offset[1] += 1 if self.offset[1] > self.max_char_height: self.offset[1] = 0 self.matrix.Clear()
class Skeeball: buttons = 0 score = 0 highscore = 0 balls = 0 BUTTON = { 'B1000L': int("0001",16), 'B1000R': int("0002",16), 'B500': int("0004",16), 'B400': int("0008",16), 'B300': int("0010",16), 'B200': int("0020",16), 'B100': int("0040",16), 'BRET': int("0080",16), 'SELECT': int("0100",16), 'START': int("0200",16), 'SCORED': int("003F",16), 'ANY': int("FFFF",16) } MODE = { 'ATTRACT': 0, 'POST': 1, 'GAME': 2 } FONTS = { 'Score': ImageFont.truetype("fonts/GameCube.ttf", 20), 'GameOver': ImageFont.truetype("fonts/GameCube.ttf", 16), 'Balls': ImageFont.truetype("fonts/GameCube.ttf", 16), } def __init__(self): #self.__initSerial() self.game_mode = self.MODE['ATTRACT'] self.matrix = Adafruit_RGBmatrix(32,2,3) self.image = Image.new("RGB", (96, 64)) self.draw = ImageDraw.Draw(self.image) image = Image.open("imgs/penis.png") image.load() # Must do this before SetImage() calls self.matrix.SetImage(image.im.id,0,0) time.sleep(5) self.__start() def __initSerial(self): if True: self.serial = serial.Serial( port='/dev/arduino', baudrate=9600, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, bytesize=serial.EIGHTBITS, timeout=.1, rtscts=False, dsrdtr=False ) #self.serial=None def __drawScore(self): font = self.FONTS['Score'] self.draw.rectangle([(0, 0), (96, 64)],fill=(0,0,0)) self.draw.text((34, 05), "%02d" % self.balls,font=self.FONTS['Balls'],fill=(0,255,50)) self.draw.text((12, 25), "%04d" % self.score ,font=font,fill=(100,0,255)) self.matrix.Clear() self.matrix.SetImage(self.image.im.id,0,0) def __updateButtons(self): self.serial.write("B") buttons = self.serial.read(2) if buttons != None and buttons != '': print buttons.encode('hex') self.buttons = int(buttons.encode('hex'), 16) def __releaseBalls(self): self.serial.write("R\n") def __isPressed(self,button): return self.buttons & button def __start(self): self.score = 0 self.balls = 6 self.game_mode = self.MODE['GAME'] #self.__releaseBalls() def __update(self): #self.__updateButtons() if self.game_mode == self.MODE['ATTRACT']: if self.__isPressed(self.BUTTON['START']): self.__start() return if self.game_mode == self.MODE['POST']: self.__doPost() if self.game_mode == self.MODE['GAME']: self.__doGame() def __doGame(self): self.score += 150 self.balls-=1 self.__drawScore() if self.balls > 0: if self.__isPressed(self.BUTTON['B1000L']) or self.__isPressed(self.BUTTON['B1000R']): self.score += 1000 if self.__isPressed(self.BUTTON['B500']): self.score += 500 if self.__isPressed(self.BUTTON['B400']): self.score += 400 if self.__isPressed(self.BUTTON['B300']): self.score += 300 if self.__isPressed(self.BUTTON['B200']): self.score += 200 if self.__isPressed(self.BUTTON['B100']): self.score += 100 if self.__isPressed(self.BUTTON['BRET']): self.balls-=1 if self.__isPressed(self.BUTTON['SCORED']): self.__drawScore() else: self.game_mode = self.MODE['POST'] self.__startPost() def __startPost(self): font=self.FONTS['GameOver'] self.draw.rectangle([(0, 0), (96, 64)],fill=(0,0,0)) self.draw.text((8, 2), "GAME",font=font,fill=(255,0,0)) self.draw.text((14, 16), "OVER",font=font,fill=(255,0,0)) self.draw.text((10,32), "%04d" % self.score,font=self.FONTS['Score'],fill=(255,200,10)) self.matrix.Clear() self.matrix.SetImage(self.image.im.id,0,0) time.sleep(5) return def __doPost(self): return def loop(self): while 1: self.__update() #time.sleep(.2) time.sleep(1)
class AmpView(object): """ This is the Amp View, which displays reciever details on the Adafruit RGB matrix. It's set up for a 32x64 RGB display. """ RED = (255, 0, 0) DIM_RED = (128, 0, 0) GREEN = (0, 255, 0) DIM_GREEN = (0, 128, 0) BLUE = (155, 48, 255) DIM_BLUE = (77, 24, 128) FONT1 = '/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf' FONT2 = '/home/pi/rpi-rgb-led-matrix-master/fonts/5x7.pil' FONT3 = '/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf' PANEL_HEIGHT = 32 PANELS = 2 PANEL_WIDTH = 64 def __init__(self): """ Initialise a new twitter display """ self.logger = logging.getLogger(self.__class__.__name__) self.logger.info("Initialising the Amp View") self.matrix = Adafruit_RGBmatrix(AmpView.PANEL_HEIGHT, AmpView.PANELS) self.__load_fonts() self.volume = "" self.source = "" self.timer = None self.model = None def callback(self, model): """ This is the only public method, the entry point to updating the display.""" self.model = model self.__refresh_display_vol(model.volumne) self.__refresh_display_front_line(model.display) self.__refresh_display_source(model.source) self.__refresh_display_input_res(model.input_resolution) self.__refresh_display_speakers( self.model.input_left_channel, self.model.input_center_channel, self.model.input_right_channel, self.model.input_left_back_channel, self.model.input_right_back_channel, self.model.input_lfe_channel, self.model.output_left_channel, self.model.output_center_channel, self.model.output_right_channel, self.model.output_left_back_channel, self.model.output_right_back_channel, self.model.output_sub_channel) self.timer = Timer(5, self.__dim) self.timer.start() def clear(self): """ Clear the matrix display and reset the timer """ self.logger.debug('Clear called') self.matrix.Clear() self.model = None self.timer = None self.matrix = None def __load_fonts(self): """ Load the fonts that will be used by the display """ self.font1 = ImageFont.truetype(AmpView.FONT1, 10) self.font2 = ImageFont.load(AmpView.FONT2) self.font3 = ImageFont.truetype(AmpView.FONT3, 8) def __refresh_display_vol(self, msg): self.logger.debug("refresh vol: " + msg) self.__clear_region(0) self.__show_text(self.font3, msg, 0, AmpView.BLUE) def __refresh_display_front_line(self, msg): self.logger.debug("refresh front line: " + msg) self.__clear_region(9) self.__show_text(self.font1, msg, 9, AmpView.RED) def __refresh_display_source(self, msg): self.logger.debug("refresh source: " + msg) self.__clear_region(20) self.__show_text(self.font1, msg, 20, AmpView.GREEN) def __refresh_display_input_res(self, msg): self.logger.debug("refresh input resolution: " + msg) self.__clear_region(0, 25, 32, 8) self.__show_text(self.font3, msg, 0, AmpView.BLUE, 25) def __refresh_display_speakers( self, input_left_channel, input_center_channel, input_right_channel, input_left_back_channel, input_right_back_channel, input_lfe_channel, output_left_channel, output_center_channel, output_right_channel, output_left_back_channel, output_right_back_channel, output_sub_channel): """ The 5.1 channel speaker display """ self.__draw_speakers(8, 1, input_left_channel, input_center_channel, input_right_channel, input_left_back_channel, input_right_back_channel, input_lfe_channel, output_left_channel, output_center_channel, output_right_channel, output_left_back_channel, output_right_back_channel, output_sub_channel) def __refresh_display_vol_dim(self, msg): """ The db volume display """ self.logger.debug("dim vol: " + msg) self.__clear_region(0) self.__show_text(self.font3, msg, 0, AmpView.DIM_BLUE) def __refresh_display_frontline_dim(self, msg): self.logger.debug("dim front line: " + msg) self.__clear_region(9) self.__show_text(self.font1, msg, 9, AmpView.DIM_RED) def __refresh_display_source_dim(self, msg): self.logger.debug("dim source: " + msg) self.__clear_region(20) self.__show_text(self.font1, msg, 20, AmpView.DIM_GREEN) def __refresh_display_input_res_dim(self, msg): self.logger.debug("dim input resolution: " + msg) self.__clear_region(0, 25, 32, 8) self.__show_text(self.font3, msg, 0, AmpView.DIM_BLUE, 25) def __refresh_display_inputfreq_dim(self, msg): self.logger.debug("dim input frequency: " + msg) #self.clear_region(0,25,32,8) #self.show_text(self.font3, msg, 0, AmpView.DIM_BLUE, 25) def __refresh_display_speakers_dim( self, input_left_channel, input_center_channel, input_right_channel, input_left_back_channel, input_right_back_channel, input_lfe_channel, output_left_channel, output_center_channel, output_right_channel, output_left_back_channel, output_right_back_channel, output_sub_channel): self.__draw_speakers(8, 1, input_left_channel, input_center_channel, input_right_channel, input_left_back_channel, input_right_back_channel, input_lfe_channel, output_left_channel, output_center_channel, output_right_channel, output_left_back_channel, output_right_back_channel, output_sub_channel) def __clear_region(self, row, col=0, width=64, height=12): image = Image.new("RGB", (width, height), "black") ImageDraw.Draw(image) self.matrix.SetImage(image.im.id, col, row) def __show_text(self, font, msg, row, colour, col=0): msg = msg.strip() image = ImageText(font, msg, colour) self.matrix.SetImage(image.image.im.id, col, row) if len(msg) > 2: if ord(msg[0]) == 5 and ord(msg[1]) == 6: self.__draw_dolby_image(11, 0, colour) if len(msg) > 5: if ord(msg[4]) == 8: self.__draw_prologic_image(11, 26, colour) def __dim(self): self.__refresh_display_vol_dim(self.model.volumne) self.__refresh_display_frontline_dim(self.model.display) self.__refresh_display_source_dim(self.model.source) self.__refresh_display_input_res_dim(self.model.input_resolution) self.__refresh_display_inputfreq_dim(self.model.input_frequency) self.__refresh_display_speakers_dim( self.model.input_left_channel, self.model.input_center_channel, self.model.input_right_channel, self.model.input_left_back_channel, self.model.input_right_back_channel, self.model.input_lfe_channel, self.model.output_left_channel, self.model.output_center_channel, self.model.output_right_channel, self.model.output_left_back_channel, self.model.output_right_back_channel, self.model.output_sub_channel) self.timer.cancel() def __draw_dolby_image(self, row, column, colour): """ draw the dolby double DD image """ image = Image.new("RGB", (12, 10), "black") draw = ImageDraw.Draw(image) draw.line([0, 0, 4, 0], fill=colour) draw.line([0, 0, 0, 6], fill=colour) draw.line([0, 6, 4, 6], fill=colour) draw.line([4, 6, 4, 0], fill=colour) draw.point([3, 1], fill=colour) draw.point([3, 5], fill=colour) draw.line([6, 0, 10, 0], fill=colour) draw.line([6, 0, 6, 6], fill=colour) draw.line([6, 6, 10, 6], fill=colour) draw.line([10, 6, 10, 0], fill=colour) draw.point([7, 1], fill=colour) draw.point([7, 5], fill=colour) self.matrix.SetImage(image.im.id, column, row) def __draw_prologic_image(self, row, column, colour): image = Image.new("RGB", (5, 10), "black") draw = ImageDraw.Draw(image) draw.line([0, 0, 4, 0], fill=colour) draw.line([1, 0, 1, 6], fill=colour) draw.line([0, 6, 4, 6], fill=colour) draw.line([3, 6, 3, 0], fill=colour) self.matrix.SetImage(image.im.id, column, row) def __draw_speakers(self, row, column, l, c, r, lb, rb, lfe, output_l, output_c, output_r, output_lb, output_rb, output_sub): """ Draw the speakers using on pixel each. It's configured for 5.1 layout """ image = Image.new("RGB", (14, 3), "black") draw = ImageDraw.Draw(image) if l: draw.point([0, 0], fill=(25, 25, 112)) if c: draw.point([1, 0], fill=(25, 25, 112)) if r: draw.point([2, 0], fill=(25, 25, 112)) if lb: draw.point([0, 1], fill=(25, 25, 112)) if rb: draw.point([2, 1], fill=(25, 25, 112)) if lfe: draw.point([3, 1], fill=(25, 25, 112)) if output_l: draw.point([6, 0], fill=(25, 25, 112)) if output_c: draw.point([7, 0], fill=(25, 25, 112)) if output_r: draw.point([8, 0], fill=(25, 25, 112)) if output_lb: draw.point([6, 1], fill=(25, 25, 112)) if output_rb: draw.point([8, 1], fill=(25, 25, 112)) if output_sub: draw.point([9, 1], fill=(25, 25, 112)) self.matrix.SetImage(image.im.id, column, row)
class Skeeball: buttons = 0 score = 0 highscore = 0 balls = 0 BUTTON = { 'B1000L': int("0001", 16), 'B1000R': int("0002", 16), 'B500': int("0004", 16), 'B400': int("0008", 16), 'B300': int("0010", 16), 'B200': int("0020", 16), 'B100': int("0040", 16), 'BRET': int("0080", 16), 'SELECT': int("0100", 16), 'START': int("0200", 16), 'SCORED': int("003F", 16), 'ANY': int("FFFF", 16) } MODE = {'ATTRACT': 0, 'POST': 1, 'GAME': 2} def __init__(self): self.__initSerial() self.game_mode = self.MODE['ATTRACT'] self.matrix = Adafruit_RGBmatrix(32, 2, 3) self.image = Image.new("RGB", (96, 64)) self.draw = ImageDraw.Draw(self.image) font = ImageFont.truetype( "/usr/share/fonts/truetype/freefont/FreeSerif.ttf", 14) self.draw.text((20, 10), "LOADING", font=font, fill=(255, 60, 5)) self.draw.text((18, 30), "SKEEBALL", font=font, fill=(255, 60, 5)) self.matrix.Clear() self.matrix.SetImage(self.image.im.id, 0, 0) time.sleep(1) def __initSerial(self): if True: self.serial = serial.Serial(port='/dev/arduino', baudrate=9600, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, bytesize=serial.EIGHTBITS, timeout=.1, rtscts=False, dsrdtr=False) #self.serial=None def __drawScore(self): font = ImageFont.truetype( "/usr/share/fonts/truetype/freefont/FreeSerif.ttf", 14) self.draw.rectangle([(0, 0), (96, 64)], fill=(0, 0, 0)) self.draw.text((20, 10), "Score", font=font, fill=(255, 60, 5)) self.draw.text((18, 30), str(self.score), font=font, fill=(255, 60, 5)) self.matrix.Clear() self.matrix.SetImage(self.image.im.id, 0, 0) def __updateButtons(self): self.serial.write("B") buttons = self.serial.read(2) if buttons != None and buttons != '': print buttons.encode('hex') self.buttons = int(buttons.encode('hex'), 16) def __releaseBalls(self): self.serial.write("R\n") def __isPressed(self, button): return self.buttons & button def __start(self): self.score = 0 self.balls = 6 self.game_mode = self.MODE['GAME'] self.__releaseBalls() def __update(self): self.__updateButtons() if self.game_mode == self.MODE['ATTRACT']: if self.__isPressed(self.BUTTON['START']): self.__start() return if self.game_mode == self.MODE['POST']: self.__doPost() if self.game_mode == self.MODE['GAME']: self.__doGame() def __doGame(self): if self.balls > 0: if self.__isPressed(self.BUTTON['B1000L']) or self.__isPressed( self.BUTTON['B1000R']): self.score += 1000 if self.__isPressed(self.BUTTON['B500']): self.score += 500 if self.__isPressed(self.BUTTON['B400']): self.score += 400 if self.__isPressed(self.BUTTON['B300']): self.score += 300 if self.__isPressed(self.BUTTON['B200']): self.score += 200 if self.__isPressed(self.BUTTON['B100']): self.score += 100 if self.__isPressed(self.BUTTON['BRET']): self.balls -= 1 if self.__isPressed(self.BUTTON['SCORED']): self.__drawScore() else: self.game_mode = self.MODE['POST'] self.__startPost() def __startPost(self): return def loop(self): while 1: self.__update() time.sleep(.2)
class ThreadingExample(object): """ Threading example class The run() method will be started and it will run in the background until the application exits. """ def __init__(self, interval=3): """ Constructor :type interval: int :param interval: Check interval, in seconds """ self.interval = interval self.channel_data = dict() self.histogram_data = list() self.showlight = False for i in chanlookup: self.channel_data[i] = dict() # Rows and chain length are both required parameters: if args.nolights is False: self.matrix = Adafruit_RGBmatrix(16, 1) # use a bitmap font if args.nolights is False: self.font = ImageFont.load("rpi-rgb-led-matrix/fonts/4x6.pil") if args.nolights is False: self.font2 = ImageFont.load("rpi-rgb-led-matrix/fonts/5x7.pil") thread = threading.Thread(target=self.run, args=()) thread.daemon = True # Daemonize thread thread.start() # Start the execution def run(self): """ Method that runs forever """ counter = 0 switchval = 1 while True: if self.showlight is True: if args.ratio is False: self.flash_state_summary() else: if switchval == 1: self.ratio_summary() elif switchval == 2: self.histogram_summary() else: self.flash_state_summary() #if args.verbose is True: if args.verbose is True: print self.get_state_summary() if args.verbose is True: print time.time() time.sleep(0.5) counter += 1 if (counter / switchval) >= 20: if switchval == 1: switchval = 2 elif switchval == 2: switchval = 3 else: switchval = 1 counter = 0 pass def histogram_summary(self): if args.nolights is False: scaled_hist = scale16(proc_hist_3(self.histogram_data)) self.matrix.Clear() for idx, val in enumerate(scaled_hist): #print(idx, val) for i in range(15): if i + 1 <= val: self.point(idx, 16 - (i + 1), 50, 50, 200) else: self.point(idx, 16 - (i + 1), 0, 0, 0) def ratio_summary(self): summary = self.get_state_summary() strand = 0 single = 0 if "strand" in summary.keys(): strand = int(summary["strand"]) if "good_single" in summary.keys(): single = int(summary["good_single"]) print "Seen Good Single", single total = strand + single if strand == 0: percentage = 0 else: percentage = (strand / total) * 100 perc = "%.1f" % percentage texttowrite1 = str(strand) + "/" + str(total) texttowrite2 = str(perc) + "%" color1 = "blue" color2 = "blue" if perc <= 90.0: color2 = "red" if strand <= 256: color1 = "red" self.write_text_inst_two(str(texttowrite1), color1, str(texttowrite2), color2) def write_text_inst_two(self, message1, color1, message2, color2): if args.nolights is False: image = Image.new("1", (320, 200)) image = image.convert("RGBA") draw = ImageDraw.Draw(image) draw.text((0, 0), message1, font=self.font, fill=color1) draw.text((0, 9), message2, font=self.font2, fill=color2) self.matrix.Clear() self.matrix.SetImage(image.im.id, 1, 0) def flash_state_summary(self): for key, value in self.channel_data.items(): #print key,value (r, g, b) = (0, 0, 0) try: (r, g, b) = colourlookup[value["state"]] except: pass (x, y) = chanlookup[int(key)] self.point(x, y, r, g, b) def get_state_summary(self): state_dict = dict() for key, value in self.channel_data.items(): #print value,type(value) try: if value["state"] in state_dict: state_dict[value["state"]] += 1 else: state_dict[value["state"]] = 1 except: pass #print(key, len([item for item in value if item])) return state_dict def logitem(self, channel, state): self.channel_data[channel]["state"] = state def point(self, x, y, r, g, b): if args.nolights is False: if args.brightness is True: self.matrix.SetPixel(x, y, int(r / 3), int(g / 3), int(b / 3)) else: self.matrix.SetPixel(x, y, r, g, b) else: if args.verbose is True: print "would do:", x, y, r, g, b def write_text_inst(self, message, color): if args.nolights is False: image = Image.new("1", (320, 200)) image = image.convert("RGBA") draw = ImageDraw.Draw(image) draw.text((0, 0), message, font=self.font, fill=color) self.matrix.Clear() self.matrix.SetImage(image.im.id, 1, 0) def write_text(self, message, color, showtime): if args.nolights is False: image = Image.new("1", (320, 200)) image = image.convert("RGBA") draw = ImageDraw.Draw(image) draw.text((0, 0), message, font=self.font, fill=color) self.matrix.Clear() self.matrix.SetImage(image.im.id, 1, 0) time.sleep(showtime) self.matrix.Clear() def write_time(self, color): if args.nolights is False: timestring = time.strftime("%H:%M:%S", time.gmtime()) image = Image.new("1", (320, 200)) image = image.convert("RGBA") draw = ImageDraw.Draw(image) draw.text((0, 0), timestring, font=self.font, fill=color) #self.matrix.Clear() self.matrix.SetImage(image.im.id, 0, 0)
class Transmitter: def __init__(self, version, qrECC, linkID,duration): self.linkID = linkID self.matrix = Adafruit_RGBmatrix(32,1) self.currentID = 0 self.version = version self.qrECC = qrECC self.qrSize = int(QR_DICTIONARIES.VERSION_SIZE[version]) self.dict = self.__selectDict__(qrECC) self.startTime = time() self.duration = duration ## self.__startTransmitter__() def __startTransmitter__(self, queue): print("Transmitter Started") self.homeScreen(3) self.__transmit__(queue) sleep(.2) self.homeScreen(3) def __transmit__(self, queue): self.homeScreen(0) cont = self.checkTime() while cont == True: cont = self.checkTime() try: packet = queue.pop(0) print("Transmitting: ",packet) self.matrix.Clear() prep = EncodeFrame.EncodeFrame(packet, self.version, self.qrECC, self.qrSize, self.currentID, self.linkID, self.matrix) prep.sendPacket() self.__incrementID__() self.homeScreen(0) except: pass def checkTime(self): now = time() if self.duration > (now - self.startTime): return True else: return False def __incrementID__(self): if self.currentID >= 255: self.currentID = 0 else: self.currentID += 1 def __selectDict__(self, qrECC): """Determines capacity dictionary to use for error correction level.""" if qrECC == "L": self.dict = QR_DICTIONARIES.QR_DICT_L elif qrECC == "M": self.dict = QR_DICTIONARIES.QR_DICT_M elif qrECC == "Q": self.dict = QR_DICTIONARIES.QR_DICT_Q elif qrECC == "H": self.dict = QR_DICTIONARIES.QR_DICT_H else: print("Error: Invalid Error Correction Level selected.") pass return self.dict def homeScreen(self, duration): for i in range(32): if i%2 == 1: for j in range(32): if j%2 == 1: self.matrix.SetPixel(i, j,0, 0, 200) else: self.matrix.SetPixel(i, j, 0, 0, 0) else: for j in range(32): if j%2 == 0: self.matrix.SetPixel(i, j,0, 0, 200) else: self.matrix.SetPixel(i, j, 0, 0, 0) if duration != 0: sleep(duration) self.matrix.Clear()
#!/usr/bin/python import time from rgbmatrix import Adafruit_RGBmatrix matrix = Adafruit_RGBmatrix(32, 1) matrix.Clear() def spiral(n): center = (n - 1) / 2 position = center * (1 + 1j) direction = 1 arm_length = 1 count = 0 while True: for _ in range(2): for _ in range(2): for _ in range(arm_length): coords = int(position.real), int(position.imag) yield coords position += direction count += 1 if count == n * n: return direction *= 1j arm_length += 1
class RGBMatrixDisplay: def __init__(self): self.curFileName = "" self.matrix = None self.alloc_matrix() self.font = Font() self.font.setColor(1,255,1) self.num = 0 thread.start_new_thread(self.keythread,()) def alloc_matrix(self): self.matrix = Adafruit_RGBmatrix(32, 2) def free_matrix(self): self.matrix.Clear() self.matrix = None def checkExtension(self, filename, extension): file_len = len(filename) ext_len = len(extension) + 1 if str.upper(filename[file_len - ext_len:]) == "." + str.upper(extension): return True else: return False def keythread(self): serv = MSGserver("localhost", 5000) serv.listen() self.num = 0 while True: data = serv.recv() if data == "start": self.num = 1 elif data == "key": self.num +=1 elif data == "end": self.num = 0 elif data == "err": sys.exit() def show(self): global playFileName self.curFileName = playFileName while True: if self.checkExtension(self.curFileName,"mp4") or self.checkExtension(self.curFileName,"avi"): cap = cv2.VideoCapture(self.curFileName) total_frame = cap.get(cv2.cv.CV_CAP_PROP_FRAME_COUNT) count = 1 while (True): if self.curFileName != playFileName: self.curFileName = str(playFileName) break _, frame = cap.read() cv2.waitKey(24) pil_im = Image.fromarray(frame) self.matrix.SetImage(pil_im.im.id, 0, 0) # draw combo combo = self.num if combo >0: s = str(combo) sl = len(s) x_start_pos =32-int((sl*6)/2.0) for index,n in enumerate(s): self.font.drawNumber(self.matrix,x_start_pos+(index*6),13,int(n)) else: pass count += 1 if count >= total_frame - 1: cap.set(1, 1) count = 1 cap.release()
class drawing_app_matrix: def __init__(self): # Initialize LED Matrix self.matrix = Adafruit_RGBmatrix(32, 1) def main(self, arg1, arg2): # global random, randint self.matrix.Clear() # INPUT pix = arg1 rainbow = arg2 # end INPUT # Initialize canvas # canvas_pix = numpy.zeros((32, 32)) # Word input -> canvas # canvas_pix = overlayAt(0, 4, stringtopix(word), canvas_pix, 1) # Scoreboard -> canvas # canvas_pix = overlayAt(1, 16, stringtopix("Score:"), canvas_pix, 1) # Score input -> canvas # canvas_pix = overlayAt(1, 24, stringtopix(str(score)), canvas_pix, 1) # print_to_matrix_default(canvas_pix) if rainbow: for x in range(0, 32): for y in range(0, 32): if pix[x][y] == 1: self.matrix.SetPixel(x, y, randint(0, 255), randint(0, 255), randint(0, 255)) else: for x in range(0, 32): for y in range(0, 32): if pix[x][y] == 1: self.matrix.SetPixel(x, y, 255, 0, 0) def clear_matrix(self): self.matrix.Clear() def clear_word(self, score): # Initialize canvas canvas_pix = numpy.zeros((32, 32)) # Word input -> canvas #canvas_pix = overlayAt(1, 4, stringtopix(word), canvas_pix, 1) # Scoreboard -> canvas canvas_pix = overlayAt(1, 16, stringtopix("Score:"), canvas_pix, 1) # Score input -> canvas canvas_pix = overlayAt(1, 24, stringtopix(str(score)), canvas_pix, 1) # print_to_matrix_default(canvas_pix) for x in range(0, 32): for y in range(0, 32): if canvas_pix[x][y] == 1: self.matrix.SetPixel(x, y, 255, 0, 0) if __name__ == "__main__": main(sys.argv[1], sys.argv[2])