def startUp(): log("Starting up ThexBerryClock...") global TBC, iterations, itime iterations = 0 itime = int(time.time()) TBC = {} TBC['epoch']=datetime.datetime.utcfromtimestamp(0) TBC['bhdisplay'] = 0 TBC['sleep'] = 0.01 TBC['clockmode'] = effect_startupSplash TBC['bitcoin'] = 0 TBC['btcopen'] = 0 TBC['rainbowBorderMode'] = 0 TBC['timers'] = {'bitcoin':0,'bhflipper':0}; TBC['timerFreqList'] = {'bitcoin':60,'bhflipper':10}; TBC['timerFuncList'] = {'bitcoin':getBitcoinPrice,'bhflipper':blockheight_flipDisplay}; TBC['matrix'] = RGBMatrix(32, 2) TBC['matrix'].pwmBits = 11 TBC['matrix'].brightness = 50 TBC['canvas'] = TBC['matrix'].CreateFrameCanvas() TBC['font'] = ImageFont.load(basePath + "/pilfonts/timR08.pil") TBC['blockheight'] = 0 thread.start_new_thread( startup_blockheight, () ) signal.signal(signal.SIGUSR1, interruptHandler)
class LedService: def __init__(self): print "Loading LED configurations" with open('led.json', 'r') as f: self.data = json.load(f) f.close() self.rows = self.data["settings"]["rows"] self.chain = self.data["settings"]["chain"] self.parallel = self.data["settings"]["parallel"] print (self.rows, self.chain, self.parallel) self.matrix = RGBMatrix(self.rows, self.chain, self.parallel) def dowork(self): print "Loading scene" def run(self): print "Starting LED service" self._thread = threading.Thread(target=self.dowork) self._thread.setDaemon(True) self._thread.start() def stop(self): self.matrix.clear()
def __init__(self): matrix = RGBMatrix(rows, chain, parallel) matrix.pwmBits = pwmbits matrix.brightness = brightness matrix.luminanceCorrect = luminance self.canvas = matrix self.font = graphics.Font() self.font.LoadFont(font_file) self.font_twitter = graphics.Font() self.font_twitter.LoadFont(font_file_twitter) self.color = graphics.Color(color_codeR, color_codeG, color_codeB) self.pos = self.canvas.width #self.tweet = "Cakam na tweet :D" #self.Twitter() self.offscreenCanvas = self.canvas.CreateFrameCanvas()
def __init__(self): print "Loading LED configurations" with open('led.json', 'r') as f: self.data = json.load(f) f.close() self.rows = self.data["settings"]["rows"] self.chain = self.data["settings"]["chain"] self.parallel = self.data["settings"]["parallel"] print (self.rows, self.chain, self.parallel) self.matrix = RGBMatrix(self.rows, self.chain, self.parallel)
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)
from rgbmatrix import RGBMatrix, RGBMatrixOptions from PIL import Image if len(sys.argv) < 2: sys.exit("Require an image argument") else: image_file = sys.argv[1] image = Image.open(image_file) # 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) # Make image fit our screen. image = image.resize((matrix.width, matrix.height), Image.ANTIALIAS) matrix.SetImage(image.convert('RGB')) try: print("Press CTRL-C to stop.") while True: time.sleep(100) except KeyboardInterrupt: sys.exit(0)
class Display(threading.Thread): def __init__(self, dimmer): #def __init__(self, weather, dimmer): threading.Thread.__init__(self) self.setDaemon(True) # Options options = RGBMatrixOptions() options.pwm_lsb_nanoseconds = 400 options.rows = 32 options.cols = 64 #self._weather = weather self._dimmer = dimmer # Configure LED matrix driver #self._matrix = RGBMatrix(32, 2, 1) self._matrix = RGBMatrix(options=options) self._matrix.pwmBits = 11 self._matrix.brightness = 20 # Load fonts self._font_large = graphics.Font() self._font_large.LoadFont("rpi-rgb-led-matrix/fonts/10x20.bdf") self._font_small = graphics.Font() self._font_small.LoadFont("rpi-rgb-led-matrix/fonts/6x10.bdf") self._font_tiny = graphics.Font() self._font_tiny.LoadFont("rpi-rgb-led-matrix/fonts/4x6.bdf") # Define colors self._white = graphics.Color(255, 255, 255) self._red = graphics.Color(255, 32, 32) self._blue = graphics.Color(64, 64, 255) rgbtupl = self.random_color() #rgbtupl = self.colorsX(3) self._randcolorH = graphics.Color(int(rgbtupl[0]), int(rgbtupl[1]), int(rgbtupl[2])) rgbtupl = self.random_color() self._randcolorCollon = graphics.Color(int(rgbtupl[0]), int(rgbtupl[1]), int(rgbtupl[2])) rgbtupl = self.random_color() self._randcolorM = graphics.Color(int(rgbtupl[0]), int(rgbtupl[1]), int(rgbtupl[2])) #self._randcolorH = graphics.Color(randint(100, 255), randint(100, 255), randint(100, 255)) #self._randcolorCollon = graphics.Color(randint(100, 255), randint(100, 255), randint(100, 255)) #self._randcolorM = graphics.Color(randint(100, 255), randint(100, 255), randint(100, 255)) def random_color(self): num1 = randint(100, 255) num2 = randint(10, 255) num3 = 250 % num1 rgbl = [num1, num2, num3] shuffle(rgbl) print rgbl return tuple(rgbl) def colorsX(n): ret = [] r = int(random.random() * 256) g = int(random.random() * 256) b = int(random.random() * 256) step = 256 / n for i in range(n): r += step g += step b += step r = int(r) % 256 g = int(g) % 256 b = int(b) % 256 ret.append((r, g, b)) return ret def _draw(self, canvas): # Remember this is a loop so dont generate colors here # otherwise they will be blinking and changing constantly # do it in above function instead canvas.Clear() locale.setlocale(locale.LC_TIME, "sv_SE.utf8") #graphics.DrawText(canvas, self._font_large, 1, 13, self._white, time.strftime("%-2I:%M")) graphics.DrawText(canvas, self._font_large, 5, 16, self._randcolorH, time.strftime("%H")) graphics.DrawText(canvas, self._font_large, 25, 16, self._randcolorCollon, time.strftime(":")) graphics.DrawText(canvas, self._font_large, 35, 16, self._randcolorM, time.strftime("%M")) #graphics.DrawText(canvas, self._font_small, 53, 13, self._white, time.strftime("%p")) # day of the month #graphics.DrawText(canvas, self._font_small, 2, 22, self._white, time.strftime("%a %-d %b")) # Remove these lines when temp is implemented hi_str = "Vilken dag idag?" #hi_str = "%3.0f" % self._weather.high_temp graphics.DrawText(canvas, self._font_tiny, 1, 30, self._red, hi_str) #graphics.DrawText(canvas, self._font_tiny, 40, 30, self._red, "F") ''' # For future use when temps added temp_str = "Tm" #temp_str = "%3.0f" % self._weather.cur_temp #graphics.DrawText(canvas, self._font_small, 0, 31, self._white, u'A good idea\u00AE') graphics.DrawText(canvas, self._font_tiny, 18, 30, self._white, "F") hi_str = "Hi" #hi_str = "%3.0f" % self._weather.high_temp graphics.DrawText(canvas, self._font_small, 22, 30, self._white, hi_str) graphics.DrawText(canvas, self._font_tiny, 40, 30, self._red, "F") low_str = "Lo" #low_str = "%3.0f" % self._weather.low_temp graphics.DrawText(canvas, self._font_small, 43, 30, self._white, low_str) graphics.DrawText(canvas, self._font_tiny, 61, 30, self._blue, "F") ''' def run(self): canvas = self._matrix.CreateFrameCanvas() while True: self._draw(canvas) time.sleep(0.05) canvas = self._matrix.SwapOnVSync(canvas) self._matrix.brightness = self._dimmer.brightness
def run(): # Kill the splash screen if active stop_splash_service() # Get supplied command line arguments commandArgs = args() if commandArgs.terminal_mode and sys.stdin.isatty(): height, width = os.popen('stty size', 'r').read().split() termMatrix = TermMatrix() termMatrix.width = int(width) termMatrix.height = int(height) matrix = Matrix(termMatrix) else: # Check for led configuration arguments matrixOptions = led_matrix_options(commandArgs) matrixOptions.drop_privileges = False # Initialize the matrix matrix = Matrix(RGBMatrix(options = matrixOptions)) #Riff to add loading screen here loading = Loading(matrix) loading.render() # Read scoreboard options from config.json if it exists config = ScoreboardConfig("config", commandArgs, (matrix.width, matrix.height)) data = Data(config) #If we pass the logging arguments on command line, override what's in the config.json, else use what's in config.json (color will always be false in config.json) if commandArgs.logcolor and commandArgs.loglevel != None: debug.set_debug_status(config,logcolor=commandArgs.logcolor,loglevel=commandArgs.loglevel) elif not commandArgs.logcolor and commandArgs.loglevel != None: debug.set_debug_status(config,loglevel=commandArgs.loglevel) elif commandArgs.logcolor and commandArgs.loglevel == None: debug.set_debug_status(config,logcolor=commandArgs.logcolor,loglevel=config.loglevel) else: debug.set_debug_status(config,loglevel=config.loglevel) # Print some basic info on startup debug.info("{} - v{} ({}x{})".format(SCRIPT_NAME, SCRIPT_VERSION, matrix.width, matrix.height)) if data.latlng is not None: debug.info(data.latlng_msg) else: debug.error("Unable to find your location.") # Event used to sleep when rendering # Allows Web API (coming in V2) and pushbutton to cancel the sleep # Will also allow for weather alert to interrupt display board if you want sleepEvent = threading.Event() # Start task scheduler, used for UpdateChecker and screensaver, forecast, dimmer and weather scheduler = BackgroundScheduler() scheduler.start() # Any tasks that are scheduled go below this line # Make sure we have a valid location for the data.latlng as the geocode can return a None # If there is no valid location, skip the weather boards #Create EC data feed handler if data.config.weather_enabled or data.config.wxalert_show_alerts: if data.config.weather_data_feed.lower() == "ec" or data.config.wxalert_alert_feed.lower() == "ec": try: data.ecData = ECData(coordinates=(data.latlng)) except Exception as e: debug.error("Unable to connect to EC, try running again in a few minutes") sys.exit(0) if data.config.weather_enabled: if data.config.weather_data_feed.lower() == "ec": ecWxWorker(data,scheduler) elif data.config.weather_data_feed.lower() == "owm": owmweather = owmWxWorker(data,scheduler) else: debug.error("No valid weather providers selected, skipping weather feed") data.config.weather_enabled = False if data.config.wxalert_show_alerts: if data.config.wxalert_alert_feed.lower() == "ec": ecalert = ecWxAlerts(data,scheduler,sleepEvent) elif data.config.wxalert_alert_feed.lower() == "nws": nwsalert = nwsWxAlerts(data,scheduler,sleepEvent) else: debug.error("No valid weather alerts providers selected, skipping alerts feed") data.config.weather_show_alerts = False if data.config.weather_forecast_enabled and data.config.weather_enabled: wxForecast(data,scheduler) # # Run check for updates against github on a background thread on a scheduler # if commandArgs.updatecheck: data.UpdateRepo = commandArgs.updaterepo checkupdate = UpdateChecker(data,scheduler,commandArgs.ghtoken) if data.config.dimmer_enabled: dimmer = Dimmer(data, matrix,scheduler) screensaver = None if data.config.screensaver_enabled: screensaver = screenSaver(data, matrix, sleepEvent, scheduler) if data.config.screensaver_motionsensor: motionsensor = Motion(data,matrix,sleepEvent,scheduler,screensaver) motionsensorThread = threading.Thread(target=motionsensor.run, args=()) motionsensorThread.daemon = True motionsensorThread.start() if data.config.pushbutton_enabled: pushbutton = PushButton(data,matrix,sleepEvent) pushbuttonThread = threading.Thread(target=pushbutton.run, args=()) pushbuttonThread.daemon = True pushbuttonThread.start() MainRenderer(matrix, data, sleepEvent).render()
# how many matrixes stacked horizontally and vertically matrix_horizontal = 5 matrix_vertical = 3 total_rows = matrix_rows * matrix_vertical total_columns = matrix_columns * matrix_horizontal options = RGBMatrixOptions() options.rows = matrix_rows options.cols = matrix_columns options.chain_length = matrix_horizontal options.parallel = matrix_vertical options.hardware_mapping = 'regular' # If you have an Adafruit HAT: 'adafruit-hat' options.gpio_slowdown = 2 matrix = RGBMatrix(options=options) ################################### # Main loop ################################### try: print("Press CTRL-C to stop") while True: try: image = Image.open("temp.jpg").convert('RGB') except: print "collision!" continue image = image.resize((total_columns, total_rows))
if today == "03-14": text = "Pi party! Wohooooooo!!" scrollaText(canvas, font, color, text) # Configuration for the matrix options = RGBMatrixOptions() options.rows = 32 options.cols = 64 options.chain_length = 1 options.parallel = 1 options.hardware_mapping = 'adafruit-hat' # If you have an Adafruit HAT: 'adafruit-hat' matrix = RGBMatrix(options=options) #Some variables to play with fontToUse = "../../../fonts/6x13.bdf" delayInSec = 5 color = graphics.Color(0, 0, 255) #just temporary color. Will change each loop canvas = matrix font = graphics.Font() font.LoadFont(fontToUse) #Loop FOREVER and EVER! try: print("Press CTRL-C to stop.") while True: hour = datetime.now().strftime('%H') minute = datetime.now().strftime('%M')
from PIL import Image options = RGBMatrixOptions() options.rows = 32 options.cols = 32 options.chain_length = 1 options.parallel = 1 options.hardware_mapping = 'adafruit-hat' options.disable_hardware_pulsing = False # default: False options.pwm_bits = 8 # default: 11 options.pwm_lsb_nanoseconds = 200 # default: 130 options.gpio_slowdown = 3 # default: 2 options.drop_privileges = False matrix = RGBMatrix(options=options) offscreen_canvas = matrix.CreateFrameCanvas() image_file = 'cache/temp2.gif' def panel_gif(filename, loop=1, delay=1): global matrix, offscreen_canvas image = Image.open(filename) for l in range(loop): for frame in range(0, image.n_frames): print(image.n_frames) image.seek(frame) offscreen_canvas.SetImage(image.convert('RGB'), unsafe=False) offscreen_canvas = matrix.SwapOnVSync(offscreen_canvas)
def __init__(self): ledOptions = LedOptions() options = ledOptions.getOptions() self.matrix = RGBMatrix(options=options)
class GoalLed(object): def __init__(self): ledOptions = LedOptions() options = ledOptions.getOptions() self.matrix = RGBMatrix(options=options) def goalScored(self, teamName): offscreen_canvas = self.matrix.CreateFrameCanvas() font = graphics.Font() font.LoadFont("../rgblibrary/fonts/9x15.bdf") textColor = graphics.Color(0, 0, 255) pos = offscreen_canvas.width max_brightness = self.matrix.brightness count = 0 while count < 3: self.matrix.Fill(255, 0, 0) time.sleep(.01) if self.matrix.brightness < 1: self.matrix.brightness = max_brightness count += 1 else: self.matrix.brightness -= 1 if teamName is not None: goalText = teamName + " Score!" else: goalText = "GOAL!" textCount = 0 while textCount < 2: offscreen_canvas.Clear() len = graphics.DrawText(offscreen_canvas, font, pos, 13, textColor, goalText) pos -= 1 if (pos + len < 0): pos = offscreen_canvas.width textCount += 1 time.sleep(0.02) offscreen_canvas = self.matrix.SwapOnVSync(offscreen_canvas) def writeScore(self, awayAbrv, awayScore, homeAbrv, homeScore, time, period): font = graphics.Font() font.LoadFont("../rgblibrary/fonts/4x6.bdf") canvas = self.matrix canvas.Clear() awayColour = graphics.Color(255, 0, 0) homeColour = graphics.Color(255, 128, 0) graphics.DrawText(canvas, font, 1, 5, awayColour, awayAbrv + " " + awayScore) graphics.DrawText(canvas, font, 1, 10, homeColour, homeAbrv + " " + homeScore) graphics.DrawText(canvas, font, 1, 16, awayColour, period + " " + time) def clearLed(self): canvas = self.matrix canvas.Clear() def writeText(self, text): offscreen_canvas = self.matrix.CreateFrameCanvas() font = graphics.Font() font.LoadFont("../rgblibrary/fonts/9x15.bdf") textColor = graphics.Color(0, 255, 0) pos = offscreen_canvas.width max_brightness = self.matrix.brightness count = 0 while count < 4: self.matrix.Fill(0, 255, 0) time.sleep(.01) if self.matrix.brightness < 1: self.matrix.brightness = max_brightness count += 1 else: self.matrix.brightness -= 1 textCount = 0 while textCount < 2: offscreen_canvas.Clear() len = graphics.DrawText(offscreen_canvas, font, pos, 13, textColor, text) pos -= 1 if (pos + len < 0): pos = offscreen_canvas.width textCount += 1 time.sleep(0.02) offscreen_canvas = self.matrix.SwapOnVSync(offscreen_canvas) count = 0 while count < 4: self.matrix.Fill(0, 255, 0) time.sleep(.01) if self.matrix.brightness < 1: self.matrix.brightness = max_brightness count += 1 else: self.matrix.brightness -= 1
class Murapix: """ Create a subclass to use Murapix The screen surface on which you need to blit the sprites is self.scratch. Murapix has the following properties: self.mapping: how the different LED panels are put in place self.demo: 0 if going to the LED panels, a positive int if it is going to the standart screen self.width: the total width of the rectangle enclosing all panels in pixel self.height: the total height of the rectangle enclosing all panels in pixel self.max_number_of_panels: the number of panels self.led_rows: the number of pixel for both height and width of the panels self.scratch: the total pygame surface which is going to be processed by the murapix draw methods to either go the LED panels or, in demo mode, to the standart screen. self.gamepad: None by default. If set to a path string pointing to an SVG, will start the virtual gamepad """ def __init__(self): configfile, demo = process_input_arg(sys.argv) (mapping, width, height, max_number_of_panels, led_rows, led_cols, parallel) = get_config(configfile) self.RUNNING = True self.mapping = mapping self.demo = demo self.width = width self.height = height self.max_number_of_panels = max_number_of_panels self.led_rows = led_rows self.led_cols = led_cols self.parallel = parallel self.scratch = pygame.Surface((width, height)) self.gamepad = None #signal handlers to quite gracefully signal.signal(signal.SIGINT, self.quit_gracefully) signal.signal(signal.SIGTERM, self.quit_gracefully) print(""" murapix Copyright (C) 2019 [email protected] This program comes with ABSOLUTELY NO WARRANTY. This is free software, and you are welcome to redistribute it under certain conditions.""") #LICENSE if not demo: #must be a raspberry pi configured for murapix, hence nodename #must be "rpi-murapix" if os.uname().nodename not in ("rpi-murapix", "raspberrypi"): raise EnvironmentError( "Not a murapix, please select demo mode with --demo=X") print('Going on the Murapix!') print('{0} channel(s) of [{1}*{2}={3} LED] X [{4} LED]'.format( parallel, max_number_of_panels // parallel, led_rows, max_number_of_panels * led_rows // parallel, led_cols)) #the screen is just a single line of panels options = RGBMatrixOptions() options.rows = options.cols = led_rows options.parallel = parallel options.chain_length = max_number_of_panels // parallel options.hardware_mapping = 'regular' options.drop_privileges = 0 self.matrix = RGBMatrix(options=options) self.double_buffer = self.matrix.CreateFrameCanvas() self._screen = init_pygame_display( (max_number_of_panels // parallel) * led_rows, led_cols * parallel) else: print('Going on the standart screen...') pygame.init() self._screen = pygame.display.set_mode( (width * demo, height * demo), 0, 32) self.clock = pygame.time.Clock() self.fps = 15 def setup(self): pass def logic_loop(self): pass def graphics_loop(self): pass def run(self): if self.gamepad: try: self.start_gamepad() except Exception as e: print("Error starting gamepad") print(e) self.close() raise e self.setup() if self.demo: draw = self.draw_demo else: draw = self.draw_murapix while self.RUNNING: self.logic_loop() self.graphics_loop() draw() self.clock.tick(self.fps) self.close() def draw_demo(self): demo = self.demo width = self.width height = self.height pygame.transform.scale(self.scratch, (width * demo, height * demo), self._screen) pygame.display.flip() def draw_murapix(self): scratch = self.scratch screen = self._screen mapping = self.mapping led_rows = self.led_rows led_cols = self.led_cols parallel = self.parallel curr_chain_row = 0 NoP_per_chain = int(self.max_number_of_panels / parallel) #now blit each simulated panel in a row onto screen in the order #indicated by the mapping in the config file. #TODO: may be more efficient by vectorizing & using blits() instead of blit() for i, n in enumerate(mapping): #x, rows for j, m in enumerate(n): #y, panel number if m is None: continue #find in which chain "m" is curr_chain_row = int((m - 1) / NoP_per_chain) #print into a square that fits hzeller doc led addressing #see https://github.com/hzeller/rpi-rgb-led-matrix/blob/master/wiring.md#chains screen.blit( scratch, #surface to take from #LED (row,col) on the lined up panels (led_rows * ((m - (NoP_per_chain * curr_chain_row)) - 1), curr_chain_row * led_cols), #rectangle to extract from the width*height scratch surface area=pygame.Rect((led_rows * j, led_rows * i), (led_rows, led_rows))) py_im = pygame.image.tostring(screen, "RGB", False) pil_im = Image.frombytes("RGB", screen.get_size(), py_im) self.double_buffer.SetImage(pil_im) self.matrix.SwapOnVSync(self.double_buffer) def start_gamepad(self): assert os.path.isfile( self.gamepad), "self.gamepad must be a path to an SVG file" self.p = set_up_gamepad(self.gamepad) self.draw_select_gamepads() pygame.joystick.quit() pygame.joystick.init() def draw_select_gamepads(self): rect_area = get_largest_rect_add(self.led_rows, self.mapping) ((left, top), (width, height)) = rect_area not_selected = True no_gamepad = True active_joystick = False fontsize = 3 * width // 18 - 1 top = top + (height - fontsize * 4) // 2 font = pygame.font.Font(None, fontsize) text = font.render("Players connected:", False, (255, 255, 255), (0, 0, 0)) text_end0 = font.render("Press any key", False, (255, 255, 255), (0, 0, 0)) text_end1 = font.render(" to start", False, (255, 255, 255), (0, 0, 0)) if self.demo: draw = self.draw_demo else: draw = self.draw_murapix while not_selected: self.clock.tick(self.fps) NoJS = [x.startswith('js') for x in os.listdir("/dev/input")].count(True) text_NoP = font.render(str(NoJS), False, (255, 255, 255), (0, 0, 0)) if NoJS > 0 and no_gamepad: no_gamepad = False pygame.joystick.quit() pygame.joystick.init() active_joystick = pygame.joystick.Joystick(0) active_joystick.init() for event in pygame.event.get(): if (active_joystick and event.type == pgl.JOYBUTTONDOWN): not_selected = False print('{} players selected'.format(NoJS)) tw, th = font.size("Players connected:") self.scratch.blit(text, (left + (width - tw) // 2, top)) self.scratch.blit(text_NoP, (left + width // 2, top + 1 * fontsize)) tw, th = font.size("Press any key") self.scratch.blit(text_end0, (left + (width - tw) // 2, top + 2 * fontsize)) tw, th = font.size(" to start") self.scratch.blit(text_end1, (left + (width - tw) // 2, top + 3 * fontsize)) draw() def close(self): #https://stackoverflow.com/questions/2638909/killing-a-subprocess-including-its-children-from-python if self.gamepad: try: os.killpg(os.getpgid(self.p.pid), signal.SIGTERM) except Exception as e: print("Error trying to kill gamepad node and its children") print(e) pygame.quit() sys.exit() def quit_gracefully(self, sig, frame): print('\n### {} was catched, terminating ###'.format( signal.Signals(sig).name)) self.RUNNING = False self.close()
i2c.write_word_data(mcp, mcp_gpio, 0x0000) leds.begin() options = RGBMatrixOptions() options.rows = 32 options.cols = 64 options.disable_hardware_pulsing = True options.pixel_mapper_config = "Rotate:180" #nfcRdr = NFCReader.NFCReader() #nfcRdr.run() paddles = Paddles.Paddles() matrix = RGBMatrix(options=options) acmefont = graphics.Font() acmefont.LoadFont('/home/pi/src/rpi-rgb-led-matrix/fonts/6x13.bdf') ipfont = graphics.Font() ipfont.LoadFont('/home/pi/src/rpi-rgb-led-matrix/fonts/5x8.bdf') def show_ipaddress(matrix, font): ipaddress = ((([ ip for ip in socket.gethostbyname_ex(socket.gethostname())[2] if not ip.startswith("127.") ] or [[(s.connect(("8.8.8.8", 53)), s.getsockname()[0], s.close()) for s in [socket.socket(socket.AF_INET, socket.SOCK_DGRAM)]][0][1]]) + ["no IP found"])[0]) ypos = 64 - 5 * len(ipaddress) graphics.DrawText(matrix, font, ypos, 30, graphics.Color(255, 0, 255),
options.cols = 64 options.chain_length = 2 options.parallel = 1 options.hardware_mapping = 'adafruit-hat-pwm' options.pixel_mapper_config = 'U-mapper;Rotate:90' dimension = 4 maxExposure = 256 # maximum exposures totalExposure = 0 # counter for exposures grid = [[0 for x in range(dimension)] for y in range(dimension) ] # 2D array of int values representing total exposure of each panel rowIndex = 0 # row index of currently exposed panel colIndex = 0 # column index of currently exposed panel eTime = 0 # countdown of remaining exposure; matrix = RGBMatrix(options=options) while totalExposure < maxExposure: if eTime <= 0: # randomly generate panel index and exposure time rowIndex = int(random.random() * dimension) colIndex = int(random.random() * dimension) eTime = int(random.random() * 6) + 2 else: if grid[rowIndex][colIndex] >= 255: grid[rowIndex][colIndex] = 255 # set upper bound else: grid[rowIndex][colIndex] += 1 # add to grid value totalExposure += 1 # add to counter eTime -= 1 # subtract from remaining exposure time
pass if event.is_set(): break print('Rendering Stop') options = RGBMatrixOptions() options.rows = 16 options.cols = 32 options.chain_length = 1 options.parallel = 1 options.hardware_mapping = 'adafruit-hat' matrix = RGBMatrix(options=options) offscreen_canvas = matrix.CreateFrameCanvas() font = graphics.Font() font.LoadFont("../../../fonts/6x13.bdf") pos = offscreen_canvas.width color = "green" stockValue = 0 shared_data = {"driver": driver, "stockValue": stockValue, "color": color} t = Thread(target=get_values, args=(shared_data, )) t.start() while True: try:
if int(resp) == risultato: sound1.play() return True else: sound2.play() return False # 1.a impostazioni per il ledmatrix # opzioni options = RGBMatrixOptions() options.hardware_mapping = 'adafruit-hat' options.rows = 32 options.chain_length = 2 # impostazione matrice matrix = RGBMatrix(options=options) offline_matrix = matrix.CreateFrameCanvas() #caricamento font font1 = graphics.Font() font2 = graphics.Font() font3 = graphics.Font() font4 = graphics.Font() font5 = graphics.Font() font1.LoadFont("./fonts/6x10.bdf") # per nomi dei colori font2.LoadFont("./fonts/5x7.bdf") # per messaggio di esito font3.LoadFont("./fonts/4x6.bdf") # per i tempi font4.LoadFont("./fonts/9x18.bdf") # per punteggi font5.LoadFont("./fonts/9x18B.bdf") # per punteggi #COLORI GENERICI RGBColor = [ graphics.Color(255, 0, 0),
def initiate(self): self.matrix = RGBMatrix(options=self.options) self.offscreen_canvas = self.matrix.CreateFrameCanvas()
class guerillaClockDisplay(object): def __init__(self): self.options = RGBMatrixOptions() self.options.rows = 16 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 nobus(self): self.msg = "BUSES AT TERMINAL - STANDBY FOR NEXT BUS." self.scroll() def announce(self, m): self.msg = m self.scroll() def set(self, m): self.msg = m def show(self, b, t): self.bus = b + ":" self.btime = t #self.msg = "test" pos = 3 #align left btlen = graphics.DrawText(self.offscreen_canvas, self.font, pos, 7, self.textColor, self.btime) #width of bus time hold = 1 while (pos + btlen > 0): self.offscreen_canvas.Clear() blen = graphics.DrawText(self.offscreen_canvas, self.font, pos, 7, self.textColor, self.bus) #width of bus btlen = graphics.DrawText(self.offscreen_canvas, self.font, pos, 15, self.textColor, self.btime) #width of bus time pos -= 1 if (pos + btlen < 0): pos = self.offscreen_canvas.width time.sleep(0.05) self.offscreen_canvas = self.matrix.SwapOnVSync( self.offscreen_canvas) if hold: time.sleep(10) hold = 0 def scroll(self): pos = self.offscreen_canvas.width loops = 0 while (loops < 2): self.offscreen_canvas.Clear() blen = graphics.DrawText(self.offscreen_canvas, self.font, pos, 10, self.textColor, self.msg) pos -= 1 if (pos + blen < 0): pos = self.offscreen_canvas.width loops += 1 time.sleep(0.05) self.offscreen_canvas = self.matrix.SwapOnVSync( self.offscreen_canvas) def off(self): self.offscreen_canvas.Clear()
class RGBBase: def __init__(self): # RGB Matrix Configuration self.__options__ = RGBMatrixOptions() self.__options__.rows = 16 self.__options__.cols = 32 self.__options__.chain_length = 3 self.__options__.parallel = 3 self.__options__.brightness = 100 self.__options__.pwm_bits = 1 self.__board_info__ = self._getBoardInfo() if self.__board_info__['panelType'] == 1: # options for first-batch boards self.__options__.multiplexing = 8 self.__options__.row_address_type = 0 self.__options__.pwm_lsb_nanoseconds = 90 elif self.__board_info__['panelType'] == 2: # options for second-batch boards self.__options__.multiplexing = 3 self.__options__.row_address_type = 2 self.__options__.gpio_slowdown = 2 # (ssid, password) = GetWifiConnectionInfo() # ssid = ssid.upper() # if ssid in legacy_panel_ssids: # # if ssid == "Lederbord103": # # options for production board # self.__options__.multiplexing = 8 # self.__options__.row_address_type = 0 # self.__options__.pwm_lsb_nanoseconds = 90 # # self.__options__.brightness = 100 # else: # # options for dev board # self.__options__.multiplexing = 3 # self.__options__.row_address_type = 2 # Create the matrix stuff self.__matrix__ = RGBMatrix(options=self.__options__) self.__offscreen_canvas__ = self.__matrix__.CreateFrameCanvas() self.__offscreen_canvas__.Clear() # Create arrays to hold the child views self.__children__ = [] def _getBoardInfo(self): board_info = {} if (os.path.exists("/home/pi/info.json")): with open("/home/pi/info.json", "r") as in_json: board_info = json.load(in_json) return board_info else: generateInfo() #create file if nonexistent return self._getBoardInfo() def redraw(self): self.__offscreen_canvas__.Clear() for child in self.__children__: child.render(self.__matrix__, self.__offscreen_canvas__) self.__offscreen_canvas__ = self.__matrix__.SwapOnVSync( self.__offscreen_canvas__) for child in self.__children__: if type(child) != RGBLabel: child.render(self.__matrix__, self.__offscreen_canvas__) elif (child.__textStyle__ == TextStyle.IMAGE or child.__textStyle__ == TextStyle.IMAGE_RED): child.render(self.__matrix__, self.__offscreen_canvas__) def addView(self, view): self.__children__.append(view) self.redraw() def removeAllViews(self): self.__offscreen_canvas__.Clear() self.__children__ = [] self.redraw() print('Removed All View') def setBrightness(self, dataStr): self.__matrix__.brightness = int(dataStr) self.redraw()
# Set up the matrix options log.info("In app main") options = RGBMatrixOptions() options.brightness = 100 options.rows = 32 options.cols = 64 options.hardware_mapping = "adafruit-hat-pwm" options.gpio_slowdown = 4 with data_lock: common_data[ACTIVE_SCREEN_KEY] = ActiveScreen.REFRESH common_data[SCREENS_KEY] = { ActiveScreen.REFRESH: InfoScreen("Loading...") } common_data[SCREENS_KEY][ActiveScreen.REBOOT] = InfoScreen( "Rebooting...") common_data[MATRIX_KEY] = RGBMatrix(options=options) common_data[SCREENS_KEY][ActiveScreen.SYNC] = SyncScreen() common_data[SCREENS_KEY][ActiveScreen.HOTSPOT] = WifiHotspot() common_data[SCREENS_KEY][ ActiveScreen.WIFI_DETAILS] = ConnectionScreen() common_data[SCREENS_KEY][ActiveScreen.ERROR] = ErrorScreen( "Dummy Error Message", ["Error"]) if not config.testing: run_webserver() else: # This is a terrible hack but it helps keep things running in test mode web_thread = threading.Thread(target=run_webserver) web_thread.start() common_data[MATRIX_KEY].master.mainloop()
image_file = sys.argv[1] image_file2 = sys.argv[2] image_file3 = sys.argv[3] image = Image.open(image_file) image2 = Image.open(image_file2) image3 = Image.open(image_file3) # 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) image2.thumbnail((matrix.width, matrix.height), Image.ANTIALIAS) matrix.SetImage(image.convert('RGB')) try: print("Press CTRL-C to stop.") while True: matrix.Clear() matrix.SetImage(image.convert('RGB')) time.sleep(1) matrix.Clear() matrix.SetImage(image2.convert('RGB'))
options.hardware_mapping = 'regular' options.inverse_colors = False options.led_rgb_sequence = "BGR" options.gpio_slowdown = 1 options.pwm_lsb_nanoseconds = 150 options.show_refresh_rate = 0 options.disable_hardware_pulsing = True options.scan_mode = 0 options.pwm_bits = 11 options.daemon = 0 options.drop_privileges = 0 return options options = rgbmatrix_options() display = RGBMatrix(options=options) class ArtNet(DatagramProtocol): def addToFrameBufferArray(self, sequence, universe, rgb_length, data): global frameArray if (sequence > 0): # Die Sequence Nummer wird aus dem Array gelesen frameSequenceInt = int(float(str(frameArray[0][0]))) # Ist die Sequence Nummer 0, so wurde der Initial Array String erkannt # nach dem befuellen muss der Initail Array entfernt werden if (frameSequenceInt == 0): frameArray.append([sequence, universe, rgb_length, data]) frameArray.pop(0) else: frameArray.append([sequence, universe, rgb_length, data])
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()
def __init__(self, canvas): if canvas is not None: self.matrix = canvas else: self.matrix = RGBMatrix(options=options)
import cv2 import os, time import numpy as np import random from PIL import Image from rgbmatrix import RGBMatrix, RGBMatrixOptions # 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' options.gpio_slowdown = 4 matrix = RGBMatrix(options = options) def overlay_transparent(background_img, img_to_overlay_t, x, y, overlay_size=None): """ @brief Overlays a transparant PNG onto another image using CV2 @param background_img The background image @param img_to_overlay_t The transparent image to overlay (has alpha channel) @param x x location to place the top-left corner of our overlay @param y y location to place the top-left corner of our overlay @param overlay_size The size to scale our overlay to (tuple), no scaling if None @return Background image with overlay on top """
total_rows = matrix_rows * matrix_vertical total_columns = matrix_columns * matrix_horizontal options = RGBMatrixOptions() options.rows = matrix_rows options.cols = matrix_columns options.chain_length = matrix_horizontal options.parallel = matrix_vertical #options.hardware_mapping = 'adafruit-hat-pwm' # If you have an Adafruit HAT: 'adafruit-hat' #options.hardware_mapping = 'adafruit-hat' # If you have an Adafruit HAT: 'adafruit-hat' options.hardware_mapping = 'regular' #options.gpio_slowdown = 2 matrix = RGBMatrix(options=options) ################################### # Main code ################################### icon_size = 40 fnt = ImageFont.truetype("Arial_Bold.ttf", 14) background = Image.open("andr_small.jpeg") background.convert("RGBA") background = background.resize((total_columns, total_rows)) icon_image = Image.open("tie-fighter-01.jpg") icon_image = icon_image.convert("RGBA") icon_image = icon_image.resize((icon_size, icon_size))
# http://effbot.org/imagingbook/imagedraw.htm from PIL import Image from PIL import ImageDraw import time from rgbmatrix import RGBMatrix, RGBMatrixOptions # Configuration for the matrix options = RGBMatrixOptions() options.rows = 16 options.chain_length = 1 options.parallel = 1 options.disable_hardware_pulsing = True 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", (16, 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, 15, 31), fill=(255, 0, 0)) draw.line((0, 15, 31, 0), fill=(0, 255, 0)) m = 0 # Then scroll image across matrix... for n in range(-15, 15): # Start off top-left, move off bottom-right m = n * 2 matrix.Clear()
image2 = Image.open("2.png") image3 = Image.open("3.png") image4 = Image.open("4.png") image5 = Image.open("5.png") image6 = Image.open("6.png") image7 = Image.open("7.png") image8 = Image.open("8.png") # Configuration for the matrix options = RGBMatrixOptions() options.rows = 32 options.chain_length = 5 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. image1.thumbnail((matrix.width, matrix.height), Image.ANTIALIAS) image2.thumbnail((matrix.width, matrix.height), Image.ANTIALIAS) image3.thumbnail((matrix.width, matrix.height), Image.ANTIALIAS) image4.thumbnail((matrix.width, matrix.height), Image.ANTIALIAS) image5.thumbnail((matrix.width, matrix.height), Image.ANTIALIAS) image6.thumbnail((matrix.width, matrix.height), Image.ANTIALIAS) image7.thumbnail((matrix.width, matrix.height), Image.ANTIALIAS) image8.thumbnail((matrix.width, matrix.height), Image.ANTIALIAS) print("Press CTRL-C to stop.") double_buffer = matrix.CreateFrameCanvas() img_width, img_height = image1.size xpos = 0
""" Mock-up to optimize image parsing in similar situation than actual one """ #Import module to handle led matrix display from rgbmatrix import RGBMatrix import time import itertools import random #Init matrix display rows = 16 chains = 3 parallel = 1 myMatrix = RGBMatrix(rows, chains, parallel) myMatrix.pwmBits = 1 myMatrix.luminanceCorrect = False #Create a buffer of the matrix display to hold new image before displaying offscreen = myMatrix.CreateFrameCanvas() #Speed test loop for i in xrange(10): #Init random image image = [(random.randint(0, 255),random.randint(0, 255),random.randint(0, 255)) for i in xrange(myMatrix.width*myMatrix.height)] start = time.time() screen_width = offscreen.width screen_height = offscreen.height
class Tank(): ############################################ # Init method ############################################### def __init__(self, panel_rows, panel_columns, num_horiz_panels, num_vert_panels): self.total_rows = panel_rows * num_vert_panels self.total_columns = panel_columns * num_horiz_panels options = RGBMatrixOptions() options.rows = matrix_rows options.cols = matrix_columns options.chain_length = num_horiz_panels options.parallel = num_vert_panels options.hardware_mapping = 'regular' #options.gpio_slowdown = 2 self.matrix = RGBMatrix(options=options) self.background = None self.icons = [] self.screen = Image.new("RGBA", (self.total_columns, self.total_rows)) ############################################ # set_background ############################################ def set_background(self, filename): self.background = Image.open(filename) self.background.convert("RGBA") self.background = self.background.resize( (self.total_columns, self.total_rows)) ############################################ # add_icon ############################################### def add_icon(self, icon): self.icons.append(icon) ############################################ # show # Displays the whole tank, and then moves any icon elements. ############################################### def show(self): #restore background self.screen.paste(self.background, (0, 0)) # move and paste in our icons for icon in self.icons: icon.move() icon.show(self.screen) self.screen = self.screen.convert("RGB") screen_draw = ImageDraw.Draw(self.screen) # draw text on top currentDT = datetime.datetime.now() time_string = currentDT.strftime("%H:%M:%S") # do some math to center our time string fnt = ImageFont.truetype("Arial_Bold.ttf", 14) time_size = fnt.getsize(time_string) time_x = (self.total_columns - time_size[0]) / 2 time_y = (self.total_rows - time_size[1]) / 2 screen_draw.text((time_x, time_y), time_string, fill=( 255, 0, 0, ), font=fnt) self.matrix.SetImage(self.screen, 0, 0)
total_rows = matrix_rows * matrix_vertical total_columns = matrix_columns * matrix_horizontal options = RGBMatrixOptions() options.rows = matrix_rows options.cols = matrix_columns options.chain_length = matrix_horizontal options.parallel = matrix_vertical #options.hardware_mapping = 'adafruit-hat-pwm' #options.hardware_mapping = 'adafruit-hat' # If you have an Adafruit HAT: 'adafruit-hat' options.hardware_mapping = 'regular' options.gpio_slowdown = 2 matrix = RGBMatrix(options=options) imageSize = 80 image = Image.open("./logos/flyingpig.jpg").convert('RGB') #image = image.rotate(180) image = image.resize((imageSize, imageSize)) xMaxRange = total_columns - imageSize yMaxRange = total_rows - imageSize imageX = random.randint(0, xMaxRange) imageY = random.randint(0, yMaxRange) dirX = random.randint(1, 3) dirY = random.randint(1, 3) start = time.time() elapsed_time = 0 last_reset = 0
def regenTropfen(topic, msg): global esRegnet v = int(msg.decode()) if v >= 1: esRegnet.on() if __name__ == "__main__": options = RGBMatrixOptions() options.rows = 64 options.cols = 64 options.hardware_mapping = "adafruit-hat-pwm" options.pwm_bits = 7 options.drop_privileges = False matrix = RGBMatrix(options=options) ch5 = House() ch5.addFloor("2.OG", 2) ch5.addFloor("1.OG", 1) ch5.addFloor("EG", 0) ch5.addFloor("Keller", -1) ch5.addFloor("Aussen", -2) ch5.addRoom("Arbeitszimmer", "2.OG") ch5.addRoom("Bad2", "2.OG") ch5.addRoom("Loggia", "2.OG") ch5.addRoom("RaspiBox", "2.OG") ch5.addRoom("3DPrinter", "2.OG") ch5.addRoom("2OG-Loggia", "2.OG") ch5.addRoom("2OG-Flur", "2.OG")
# how many matrixes stacked horizontally and vertically matrix_horizontal = 1 matrix_vertical = 1 total_rows = matrix_rows * matrix_vertical total_columns = matrix_columns * matrix_horizontal options = RGBMatrixOptions() options.rows = matrix_rows options.cols = matrix_columns options.chain_length = matrix_horizontal options.parallel = matrix_vertical options.hardware_mapping = 'regular' options.gpio_slowdown = 3 matrix = RGBMatrix(options=options) ################################### # Main code ################################### icon_size = 40 icon_image = Image.open("ghost.jpg") icon_image = icon_image.resize((icon_size, icon_size)) blank_image = Image.new("RGB", (icon_size, icon_size)) icon_x = total_columns icon_y = random.randint(0, total_columns - icon_size) try:
from rgbmatrix import RGBMatrix from rgbmatrix import graphics from field import Field from color import Color from ant import Ant import time Matrix = RGBMatrix(32, 2, 1) Matrix.pwmBits = 5 Matrix.brightness = 100 def colorize(foods, base, ants): for food in foods: Matrix.SetPixel(food[1], food[0], 0, 200, 0) for ant in ants: Matrix.SetPixel(ant.coordinates[1], ant.coordinates[0], 200, 0, 0) #base Matrix.SetPixel(base[1], base[0], 100, 255, 100) field = Field("field.txt", (30, 40)) field.food.append((10, 10)) field.food.append((20, 20)) for i in range(1, 21): field.units.append(Ant(Color(0, 0, 100), 30, 40, i)) field.add_occupied((30, 40)) offscreenCanvas = Matrix.CreateFrameCanvas()
# horizontal_position = 0 # offscreen.Fill(0,0,0) r, g, b = pixl[(horizontal_position + x) % im_width + y * im_width] #r, g, b = (0, 255, 0) offscreen.SetPixel(x, y, r, g, b) print "Parse Image rate: ? Hz", 1/(time.time()-start) #print "Update screen" offscreen = self.myMatrix.SwapOnVSync(offscreen) horizontal_position += scroll_jumps if horizontal_position < 0: horizontal_position = im_width #time.sleep(scroll_ms / 1000) def stop(self): self.Terminated = 1 def load(self, image): self.pix = list(image.getdata()) #pp.pprint(list(image.getdata())) self.image_width, self.image_height = image.size self.new_image = True if __name__ == '__main__': #Initiate led matrix screen size rows = 16 chains = 3 parallel = 1 myMatrix = RGBMatrix(rows, chains, parallel) myMatrix.pwmBits = 11 tweety_pi(myMatrix, sys.argv[1:])