Esempio n. 1
0
def show_text_input(win, work, rest):
    round_rect(win, MINS_RECT, (255, 255, 255), 3)
    round_rect(win, SECS_RECT, (255, 255, 255), 3)

    show_text_rect('-', 12, DASH_RECT, (255, 255, 255), win)
    show_text_rect(str(work), 15, MINS_RECT, BG_COLOR, win)
    show_text_rect(str(rest), 15, SECS_RECT, BG_COLOR, win)
Esempio n. 2
0
def lookleft(surface):
    state = LOOKLEFT
    roundrects.round_rect(surface, [LEYPOS - 20, EYPOS, EW, EH], TUR, rad=30)
    #right
    roundrects.round_rect(surface, [REYPOS - 20, EYPOS, EW, EH - 20],
                          TUR,
                          rad=30)
Esempio n. 3
0
def lookright(surface):
    state = LOOKRIGHT
    roundrects.round_rect(surface, [LEYPOS + 20, EYPOS, EW, EH - 20],
                          TUR,
                          rad=30)
    #right
    roundrects.round_rect(surface, [REYPOS + 20, EYPOS, EW, EH], TUR, rad=30)
    pygame.display.update()
Esempio n. 4
0
def neutral(surface):
    #rect: (x1, y1, width, height)
    state = NEUTRAL
    #left
    roundrects.round_rect(surface, [LEYPOS, EYPOS + 10, EW, EH - 20],
                          TUR,
                          rad=30)
    #right
    roundrects.round_rect(surface, [REYPOS, EYPOS, EW, EH], TUR, rad=30)
Esempio n. 5
0
def happy(surface):
    state = HAPPY
    #left
    roundrects.round_rect(surface, [LEYPOS, EYPOS, EW, EH], TUR, rad=30)
    #right
    roundrects.round_rect(surface, [REYPOS, EYPOS, EW, EH], TUR, rad=30)
    #draw blak box
    #rect: (x1, y1, width, height)
    pygame.draw.rect(surface, BLACK,
                     [LEYPOS - 10, EYPOS + 20, (EW * 2) + 35, EH + 15])
Esempio n. 6
0
def sleep(surface):
    #left
    roundrects.round_rect(surface, [LEYPOS, EYPOS, EW, EH], TUR, rad=30)
    #right
    roundrects.round_rect(surface, [REYPOS, EYPOS, EW, EH], TUR, rad=30)
    #draw blak box
    #rect: (x1, y1, width, height)
    pygame.draw.rect(surface, BLACK,
                     [LEYPOS - 10, SIZEH / 2, (EW * 2) + 35, EH / 1.4])
    pygame.draw.rect(
        surface, BLACK,
        [LEYPOS - 10, (SIZEH / 2) - SIZEH / 4, (EW * 2) + 35, EH / 1.4])
Esempio n. 7
0
def loadpics():
    global piclist, bgcolor, myfont, screen, qty
    screen.fill((bgcolor))
    myfont = pygame.font.Font(pygame.font.match_font('mono'), 25)
    screen.blit((myfont.render("Loading Images", 1, fontcolor)), (20, 100))
    pygame.display.flip()
    i = 0
    piclist = []
    list2 = range(50)
    #while i<qty2:
    #print "Attemting to import "+str(qty2)+" pictures"
    print "Importing all pictures downloaded..."
    success = True
    while success:
        try:
            #i=i+1
            print "Importing pic " + str(i) + ".jpg"
            img = pygame.image.load('pics/' + str(i) + '.jpg')
            piclist.append(img)
            i = i + 1
            round_rect(screen, (10, 210, 300, 20), (190, 190, 190), 10, 0)
            round_rect(screen, (10, 210, 250 / qty * i + 14, 20),
                       (255, 75, 75), 10, 0)
            pygame.display.flip()
        except:
            success = False
            print "Done Importing"
            round_rect(screen, (10, 210, 300, 20), (190, 190, 190), 10, 0)
            round_rect(screen, (10, 210, 300, 20), (255, 75, 75), 10, 0)
            pygame.display.flip()
            time.sleep(1)
            pass
Esempio n. 8
0
def button(x,y,w,h,ic,ac,action=None,msg=None,img=None):
	mouse = pygame.mouse.get_pos()
	click = pygame.mouse.get_pressed()

	if msg != None:
		if x+w > mouse[0] > x and y+h > mouse[1] > y:
		    round_rect(screen, (x,y,w,h),ac)

		    if click[0] == 1 and action != None:
		        action()         
		else:
		    round_rect(screen, (x,y,w,h),ic)

		write(x,y-10,w,h,msg,"comicsansms",70,white)
Esempio n. 9
0
def make_tile(val):
    tile = pygame.Surface((112, 112))
    round_rect(tile, (0, 0, 112, 112), val_to_colour(val), 4)
    tile.set_colorkey((0, 0, 0))
    text_surface = write(str(val))
    # 1 digit = 35, 0
    # 2 digits = 20, 5
    # 3 digits = 5, 10
    # 4 digits  = 0, 15
    x = 35 - (15 * (len(str(val)) - 1))
    if len(str(val)) >= 4:
        x = 0
    y = (len(str(val)) - 1) * 5
    tile.blit(text_surface, (x, y))
    return tile
Esempio n. 10
0
def doubt(surface):
    state = DOUBT
    points = list()

    points.append(((SIZEW / 2) - 5, SIZEH / 2))  #left bottom
    points.append(((SIZEW / 2) + 40, 0))  #top point
    points.append(((SIZEW / 2) + 150, (SIZEH / 2) - 50))  #oikealaita 290,100

    #left
    roundrects.round_rect(surface, [LEYPOS, EYPOS + 10, EW, EH - 30],
                          TUR,
                          rad=30)
    #right
    roundrects.round_rect(surface, [REYPOS, EYPOS, EW, EH - 20], TUR, rad=30)

    pygame.draw.polygon(surface, BLACK, points)
Esempio n. 11
0
 def draw(self):
     self.screen.blit(self.background, (0, 0))
     round_rect(self.screen, (50, 20, 400, 200), (130, 100, 255, 175), 30,
                50, pg.Color("lightslateblue"))
     round_rect(self.screen, (20, 235, 100, 200), pg.Color("red"), 10, 25)
     round_rect(self.screen, (140, 250, 175, 100), pg.Color("black"), 30, 1,
                pg.Color("green"))
     round_rect(self.screen, (335, 250, 145, 200), pg.Color("purple"), 30,
                20, (255, 255, 0, 150))
Esempio n. 12
0
 def draw(self):
     self.screen.blit(self.background, (0,0))
     round_rect(self.screen, (50,20,400,200), (130,100,255,175),
                     30, 50, pg.Color("lightslateblue"))
     round_rect(self.screen, (20,235,100,200), pg.Color("red"), 10, 25)
     round_rect(self.screen, (140,250,175,100), pg.Color("black"), 30,
                     1, pg.Color("green"))
     round_rect(self.screen, (335,250,145,200), pg.Color("purple"), 30,
                     20, (255,255,0,150))
    def render(self, surface, font, bSelected=False):
        """
        return painted rect position
        """

        if bSelected:
            colButton = self.colSelectedButton
        else:
            colButton = self.colButton

        #~ txt_surface, rect = font.render(self.txt, colTxt)
        round_rect(surface, self.pos + self.size, colButton, 11, 0)
        #~ surface.blit(txt_surface,(self.pos[0]+self.margin[0],self.pos[1]+self.margin[1]))
        renderTxtMultilineCentered(surface,
                                   self.txt, (self.pos[0], self.pos[1]),
                                   font,
                                   self.colText,
                                   nWidthTotal=self.size[0],
                                   nHeightTotal=self.size[1])
Esempio n. 14
0
 def draw_selection_item(self, job: Job, x: int, y: int) -> None:
     """Draw a button for the task selection screen"""
     round_rect(screen, (x, y, SELECTOR_WIDTH, SELECTOR_HEIGHT), BG_COLOUR, 6)
     screen.blit(self.id_font.render(job.id, 1, (ID_COLOUR)), (x + 5, y))
     screen.blit(
         self.desc_font.render(
             job.desc[:40] + '...' if len(job.desc) > 43 else job.desc,
             1,
             (DESC_COLOUR)),
         (x + 5, y + 20)
     )
     small_time = self.small_time_font.render(
         self.get_days_hours_minutes_string(job.elapsed), 1, (TIME_COLOUR))
     small_time_width = self.small_time_font.size(
         self.get_days_hours_minutes_string(job.elapsed))[0]
     screen.blit(
         small_time,
         (x + SELECTOR_WIDTH - 5 - small_time_width, y + 5),
     )
Esempio n. 15
0
def mouse():
    global mousex
    global mousey
    pygame.event.get()
    oldmousex = mousex
    oldmousey = mousey
    mousex, mousey = pygame.mouse.get_pos()
    if (mousex < 100 and mousex > 1) and (oldmousex != mousex):
        print "Left"
    elif (mousex > 240) and (oldmousex != mousex):
        print "Right"
    elif (mousex > 100 and mousex < 240) and (oldmousex != mousex):
        print "Center"
        round_rect(screen, (10, 10, 10, 10), (200, 75, 75), 5, 0)
        pygame.display.flip()
        while mousex < 240:
            time.sleep(0.05)
            pygame.event.get()
            mousex, mousey = pygame.mouse.get_pos()
        round_rect(screen, (10, 10, 10, 10), (75, 200, 75), 5, 0)
        pygame.display.flip()
Esempio n. 16
0
def status():
    global api, user_id, username, followers, network

    myfont = pygame.font.Font(pygame.font.match_font('mono'), 15)
    #myfont = pygame.font.Font(dir+"Roboto-Thin.ttf", 24)

    #followers = getTotalFollowers(api, user_id)
    #print "str: ",followers
    #print 'Number of followers:', len(followers)

    #pygame.draw.rect(screen, (0,0,0), (0,220,320,20), 0)
    #AAfilledRoundedRect(screen,(0,220,320,20),boxcolor,0.5)
    round_rect(screen, (10, 210, 300, 20), boxcolor, 10, 0)
    if network == True:
        screen.blit((myfont.render(
            username + "   Followers: " + str(len(followers)), 1, fontcolor)),
                    (20, 212))
    else:
        screen.blit(
            (myfont.render(username + "   Followers: NULL", 1, fontcolor)),
            (20, 212))
Esempio n. 17
0
    def draw(self) -> None:
        """Draw the entire logging screen"""
        screen.fill(BLACK)
        round_rect(screen, (5, 5, SELECTOR_WIDTH, SCREEN_HEIGHT * .10), BG_COLOUR, 8)
        round_rect(
            screen, (5, SCREEN_HEIGHT * .15, SELECTOR_WIDTH, SCREEN_HEIGHT * .57), BG_COLOUR, 8)
        round_rect(screen, (5, SCREEN_HEIGHT * .75, SELECTOR_WIDTH, 56), BG_COLOUR, 8)

        screen.blit(self.id_font.render(self.job.id, 1, (ID_COLOUR)), (10, 5))

        disp_time_string = self.get_days_hours_minutes_string(
            self.job.elapsed + self.time_elapsed, show_seconds=True)
        dis_time_width = self.large_time_font.size(disp_time_string)[0]
        screen.blit(
            self.large_time_font.render(
                disp_time_string,
                1,
                (TIME_COLOUR)
            ),
            (SELECTOR_WIDTH/2 - dis_time_width // 2, SCREEN_HEIGHT * .80)
        )

        # FIXME: below should be replaced with something better, hard to change (diff screen)
        max_line_len = 45 # chars
        xoffset, yoffset, spacing = 15, 40, 17
        ymax = SCREEN_HEIGHT * .53
        i, j, y = 0, 0, 0
        while i < len(self.job.desc):

            # we only wanna blit stuff one line at a time...
            last_whitesp_idx = self.job.desc[i : i + max_line_len].rfind(' ')
            line = self.job.desc[i : i + last_whitesp_idx + 1]
            y = yoffset + j * spacing

            if y >= ymax:
                line += '...'

            screen.blit(
                self.desc_font.render(
                    line,
                    1,
                    (DESC_COLOUR)),
                (xoffset, y)
            )

            if y > ymax:
                break
            j += 1
            i += last_whitesp_idx + 1
    def draw(self):
        #~ self.screen.blit(self.background, (0,0))
        #~ self.screen.fill( pg.Color("lightslategrey") )

        colBackground = (247, 247, 247)
        colLight1 = (220, 220, 220)
        colBlack = (0, 0, 0)
        colDark1 = (22, 22, 22)

        col1 = (164, 194, 244)  # fond et highlight

        if self.bAlternateColor:
            col1 = (254, 252, 221)

        fontSys = pygame.freetype.Font("../fonts/SF-UI-Display-Regular.otf",
                                       20)
        #~ fontSysSmall = pygame.freetype.Font("../fonts/SF-UI-Display-Regular.otf", 16)
        fontSysSmall = pygame.freetype.Font(
            "../fonts/SF-Compact-Text-Semibold.otf", 15)
        fontTxt = pygame.freetype.Font("../fonts/SF-UI-Display-Regular.otf",
                                       20)

        w = self.w
        h = self.h

        self.screen.fill(colBackground)

        # system
        self.screen.blit(self.imTopBanner, (0 + 260 + 2, 0 + 10))
        ycur = 10

        hour, min, sec = misctools.getTime()
        #~ hour,min = 11,28
        strTime = "%2d:%02d" % (hour, min)
        textsurface, rect = fontSysSmall.render(strTime, (0, 0, 0))
        self.screen.blit(textsurface, (10 + 20 + 4, ycur + 4))

        # title
        ycur = 28 + 10

        for i in range(3):
            y = ycur + i * 6
            pg.draw.line(self.screen, colDark1, (10 + 6 + 3, y), (30 + 6, y),
                         2)

        #~ fontSys = pg.font.SysFont('Comic Sans MS', 30)
        #~ textsurface = fontSys.render('Faiska', False, (0, 0, 0))
        #~ fontSys = pygame.freetype.SysFont('Verdana', 18)

        #~ fontSys.underline = True
        textsurface, rect = fontSys.render('Faiska', (0, 0, 0))
        self.screen.blit(textsurface,
                         (w // 2 - (rect[2] - rect[0]) // 2, ycur))
        ycur += 24

        pg.draw.line(self.screen, colLight1, (0, ycur), (w, ycur))
        ycur += 1

        rTime = pg.time.get_ticks(
        ) / 1000  #rTime in sec # the time of the game

        # screen
        # round_rect(mat,(x,y,w,h),col1,round_size,border_size)
        ycur += 20
        xmargin = 20
        ymargin = 20
        warea = w - xmargin * 2
        harea = 500

        if self.isSpeaking():
            bWritingQuestion = pg.time.get_ticks(
            ) / 1000 - self.timeStartSpeak < self.rDurationSpeak
        else:
            bWritingQuestion = False

        xbot = xmargin + warea - self.imBot.get_rect(
        ).size[0] + xmargin // 2 + 6
        ybot = ycur + harea - self.imBot.get_rect().size[1]  #+ymargin//2

        round_rect(self.screen, (xmargin, ycur, warea, harea), col1, 10, 0)
        if 0:
            self.renderRobotStd(xbot, ybot, rTime, bWritingQuestion)
        else:
            self.renderRobotObo(xbot, ybot, rTime, bWritingQuestion)

        if self.isSpeaking():
            # render question
            if self.bQuick:
                self.bQuick = False
                self.timeStartSpeak -= 5
            nEnd = int((pg.time.get_ticks() / 1000 - self.timeStartSpeak) * 20)
            txt = self.strTxtSpeak[:nEnd]
            for i in range(nEnd, len(self.strTxtSpeak)):
                if self.strTxtSpeak[i] != ' ':
                    txt += "_"
                else:
                    txt += " "
            renderTxtMultiline(self.screen,
                               txt, (xmargin * 2, ycur + ymargin - 5),
                               fontTxt,
                               colDark1,
                               nWidthMax=300)
            ycur += harea + 10

            if nEnd >= len(self.strTxtSpeak):
                self.renderUserButton(self.screen, (xmargin, ycur))

        ycur = 670

        # progression
        round_rect(self.screen, (xmargin, ycur, warea, 20), colLight1, 2, 0)
        rProgress = (self.nNumQ) / len(self.listQ)
        if rProgress > 1.: rProgress = 1.
        if rProgress > 0.1:
            round_rect(self.screen,
                       (xmargin, ycur, int(warea * rProgress), 20), col1, 2, 0)

        if rProgress == 1.:
            if self.timeBotsStartExit == 0:
                self.timeBotsStartExit = rTime
Esempio n. 19
0
def lookdown(surface):
    state = LOOKDOWN
    #left
    roundrects.round_rect(surface, [LEYPOS, EYPOS + 20, EW, EH], TUR, rad=30)
    #right
    roundrects.round_rect(surface, [REYPOS, EYPOS + 20, EW, EH], TUR, rad=30)
Esempio n. 20
0
 def __highlight_selection(self, x: int, y: int) -> None:
     """Draw the highlighting to show what job is selected"""
     round_rect(screen, (x-2, y-2, SELECTOR_WIDTH + 4, SELECTOR_HEIGHT + 4), HIGHLIGHT_COLOUR, 6)
Esempio n. 21
0
def displayPainter():
	"""
	Asynchronous function to build the display content

	@requires: globalData.showDisplay        - status of backlight
	@requires: globalData.enableDisplayUntil - given timestamp when backlight will turned off
	@requires: globalData.running            - service runs as long as this is True
	@requires: globalData.data               - data of the last alarm
	@requires: globalData.lastAlarm          - timestamp of the last processing (see alarmRICs and keepAliveRICs)
	@requires: configuration has to be set in the config.ini

	In case of an exception the function set globalData.abort to True.
	This will terminate the main program.

	@return:    nothing
	@exception: SystemExit exception in case of an error
	"""

	import sys
	import time
	import logging
	import ConfigParser
	import RPi.GPIO as GPIO
	import pygame
	from wrapline import wrapline
	from roundrects import round_rect
	import globalData

	logging.debug("displayPainter-thread called")

	try:
		# use GPIO pin numbering convention
		GPIO.setmode(GPIO.BCM)
		GPIO.setwarnings(False)
		# set up GPIO pin for output
		GPIO.setup(globalData.config.getint("Display","GPIOPinForBacklight"), GPIO.OUT)

		pygame.init()

		#screen size
		size = (globalData.config.getint("Display","displayWidth"), globalData.config.getint("Display","displayHeight"))
		screen = pygame.display.set_mode(size)

		# disable mouse cursor
		pygame.mouse.set_visible(False)

		#define fonts
		fontHeader = pygame.font.Font(None, 30)
		fontHeader.set_bold(True)
		fontHeader.set_underline(True)

		fontTime = pygame.font.Font(None, 15)

		fontRIC = pygame.font.Font(None, 30)
		fontRIC.set_bold(True)
		fontMsg = pygame.font.Font(None, 20)
		fontHistory = pygame.font.Font(None, 15)

		fontStatus = pygame.font.Font(None, 20)
		fontStatus.set_bold(True)
		fontStatusContent = pygame.font.Font(None, 20)

		fontButton = pygame.font.Font(None, 20)

		clock = pygame.time.Clock()

		# Build Lists out of config-entries
		functionCharTestAlarm = [x.strip() for x in globalData.config.get("AlarmMonitor","functionCharTestAlarm").replace(";", ",").split(",")]

		logging.debug("displayPainter-thread started")

		# Running will be set to False if main program is shutting down
		while globalData.running == True:
			# This limits the while loop to a max of 2 times per second.
			# Leave this out and we will use all CPU we can.
			clock.tick(2)

			# current time for this loop:
			curtime = int(time.time())

			if globalData.showDisplay == True:
				# Enable LCD display
				GPIO.output(globalData.config.getint("Display","GPIOPinForBacklight"), GPIO.HIGH)
				# Clear the screen and set the screen background
				screen.fill(globalData.screenBackground)
				# paint black rect, so Background looks like a boarder
				widthX = globalData.config.getint("Display","displayWidth") - 20
				widthY = globalData.config.getint("Display","displayHeight") - 20
				pygame.draw.rect(screen, pygame.Color(globalData.config.get("AlarmMonitor","colourBlack")), (10, 10, widthX, widthY))
				# header
				header = fontHeader.render("Alarm-Monitor", 1, pygame.Color(globalData.config.get("AlarmMonitor","colourRed")))
				(width, height) = fontHeader.size("Alarm-Monitor")
				x = (int(globalData.config.getint("Display","displayWidth")) - width)/2
				screen.blit(header, (x, 20))

				# show time of last alarm
				if globalData.lastAlarm > 0:
					try:
						# format last alarm
						lastAlarmString = time.strftime("%H:%M:%S", time.localtime(globalData.lastAlarm))
						# Color time:
						# red: lastAlarm more than n (delayForRed) seconds past
						if (int(globalData.lastAlarm) + globalData.config.getint("AlarmMonitor","delayForRed")) < curtime:
							timeColour = pygame.Color(globalData.config.get("AlarmMonitor","colourRed"))
						# yellow: lastAlarm more than n (delayForYellow) seconds past
						elif (int(globalData.lastAlarm) + globalData.config.getint("AlarmMonitor","delayForYellow")) < curtime:
							timeColour = pygame.Color(globalData.config.get("AlarmMonitor","colourYellow"))
						# dgrey: normal
						else:
							timeColour = pygame.Color(globalData.config.get("AlarmMonitor","colourGreen"))
						lastAlarm = fontTime.render(lastAlarmString, 1, timeColour)
						(width, height) = fontTime.size(lastAlarmString)
						x = globalData.config.getint("Display","displayWidth") - 20 - width
						screen.blit(lastAlarm, (x, 20))
					except:
						logging.debug("unknown error in lastAlarm", exc_info=True)
						pass
				## end if globalData.lastAlarm > 0

				# show remaining time before display will be turned off:
				restZeit = globalData.enableDisplayUntil - curtime +1
				zeit = fontTime.render(str(restZeit), 1, pygame.Color(globalData.config.get("AlarmMonitor","colourDimGrey")))
				screen.blit(zeit, (20, 20))

				#
				# content given by navigation:
				# default is "alarmPage"
				#
				# Startpoint for content
				if globalData.navigation == "historyPage":
					try:
						y = 50
						for data in reversed(globalData.alarmHistory):
							# Layout:
							# Date Description
							# Time Msg

							# Prepare date/time block
							dateString = time.strftime("%d.%m.%y", time.localtime(data['timestamp']))
							timeString = time.strftime("%H:%M:%S", time.localtime(data['timestamp']))
							if int(fontHistory.size(dateString)[0]) > int(fontHistory.size(timeString)[0]):
								(shifting, height) = fontHistory.size(dateString)
							else:
								(shifting, height) = fontHistory.size(timeString)
							shifting += 5

							# get colour
							if data['functionChar'] in functionCharTestAlarm:
								colour = globalData.config.get("AlarmMonitor","colourYellow")
							else:
								colour = globalData.config.get("AlarmMonitor","colourRed")

							# Paint Date/Time
							screen.blit(fontHistory.render(dateString, 1, pygame.Color(colour)), (20, y))
							screen.blit(fontHistory.render(timeString, 1, pygame.Color(colour)), (20, y + height))

							# Paint Description
							try:
								textLines = wrapline(data['description'], fontHistory, (globalData.config.getint("Display","displayWidth") - shifting - 40))
								for index, item in enumerate(textLines):
									textZeile = fontHistory.render(item, 1, pygame.Color(globalData.config.get("AlarmMonitor","colourWhite")))
									screen.blit(textZeile, (20 + shifting, y))
									y += height
							except KeyError:
								pass

							# Paint Msg
							try:
								textLines = wrapline(data['msg'].replace("*", " * "), fontHistory, (globalData.config.getint("Display","displayWidth") - shifting - 40))
								for index, item in enumerate(textLines):
									textZeile = fontHistory.render(item, 1, pygame.Color(globalData.config.get("AlarmMonitor","colourGrey")))
									screen.blit(textZeile, (20 + shifting, y))
									y += height
							except KeyError:
								pass

							# line spacing for next dataset
							y += 2

						## end for globalData.alarmHistory

					except KeyError:
						pass
				## end if globalData.navigation == "historyPage"

				elif globalData.navigation == "statusPage":
					(width, height) = fontStatusContent.size("Anzahl Test-Alarme:")
					y = 70
					x = width + 10
					# Running since:
					title = fontStatusContent.render("Gestartet:", 1, pygame.Color(globalData.config.get("AlarmMonitor","colourWhite")))
					content = fontStatusContent.render(time.strftime("%d.%m.%Y %H:%M:%S", time.localtime(globalData.startTime)), 1, pygame.Color(globalData.config.get("AlarmMonitor","colourGrey")))
					screen.blit(title,   (20,    y))
					screen.blit(content, (20 +x, y))
					y += height + 10

					# Last Alarm
					title = fontStatusContent.render("Letzte Nachricht:", 1, pygame.Color(globalData.config.get("AlarmMonitor","colourWhite")))
					if globalData.lastAlarm > 0:
						content = fontStatusContent.render(time.strftime("%d.%m.%Y %H:%M:%S", time.localtime(globalData.lastAlarm)), 1, timeColour)
					else:
						content = fontStatusContent.render("-", 1, pygame.Color(globalData.config.get("AlarmMonitor","colourGrey")))
					screen.blit(title,   (20,    y))
					screen.blit(content, (20 +x, y))
					y += height + 10

					# Number of Alarms
					title = fontStatusContent.render("Anzahl Alarme:", 1, pygame.Color(globalData.config.get("AlarmMonitor","colourWhite")))
					content = fontStatusContent.render(str(globalData.countAlarm), 1, pygame.Color(globalData.config.get("AlarmMonitor","colourGrey")))
					screen.blit(title,   (20,    y))
					screen.blit(content, (20 +x, y))
					y += height + 10

					# Number of TestAlarms
					title = fontStatusContent.render("Anzahl Test-Alarme:", 1, pygame.Color(globalData.config.get("AlarmMonitor","colourWhite")))
					content = fontStatusContent.render(str(globalData.countTestAlarm), 1, pygame.Color(globalData.config.get("AlarmMonitor","colourGrey")))
					screen.blit(title,   (20,    y))
					screen.blit(content, (20 +x, y))
					y += height + 10

					# Number of DAU-Msgs
					title = fontStatusContent.render("Anzahl DAU-Tests:", 1, pygame.Color(globalData.config.get("AlarmMonitor","colourWhite")))
					content = fontStatusContent.render(str(globalData.countKeepAlive), 1, pygame.Color(globalData.config.get("AlarmMonitor","colourGrey")))
					screen.blit(title,   (20,    y))
					screen.blit(content, (20 +x, y))
					y += height + 10

				## end if globalData.navigation == "statusPage"

				else:
					y = 50

					# Paint Date/Time
					try:
						dateTimeString = time.strftime("%d.%m.%Y %H:%M:%S", time.localtime(globalData.data['timestamp']))
						dateTimeRow = fontStatus.render(dateTimeString, 1, pygame.Color(globalData.config.get("AlarmMonitor","colourDimGrey")))
						(width, height) = fontStatus.size(dateTimeString)
						x = (int(globalData.config.getint("Display","displayWidth")) - width)/2
						screen.blit(dateTimeRow, (x, y))
						y += height + 10
					except KeyError:
						pass

					# Paint Description
					try:
						textLines = wrapline(globalData.data['description'], fontRIC, (globalData.config.getint("Display","displayWidth") - 40))
						(width, height) = fontStatus.size(globalData.data['description'])
						for index, item in enumerate(textLines):
							textRow = fontRIC.render(item, 1, pygame.Color(globalData.config.get("AlarmMonitor","colourWhite")))
							screen.blit(textRow, (20, y))
							y += height + 5
					except KeyError:
						pass

					# Paint Msg
					try:
						y += 10
						textLines = wrapline(globalData.data['msg'].replace("*", " * "), fontMsg, (globalData.config.getint("Display","displayWidth") - 40))
						(width, height) = fontStatus.size(globalData.data['msg'])
						for index, item in enumerate(textLines):
							textRow = fontMsg.render(item, 1, pygame.Color(globalData.config.get("AlarmMonitor","colourGrey")))
							screen.blit(textRow, (20, y))
							y += height
					except KeyError:
						pass
				## end if default navigation

				# paint navigation buttons
				buttonWidth = 80
				buttonHeight = 25
				buttonY = globalData.config.getint("Display","displayHeight") - buttonHeight - 2

				round_rect(screen, ( 20, buttonY, buttonWidth, buttonHeight), pygame.Color(globalData.config.get("AlarmMonitor","colourDimGrey")), 10, 1, pygame.Color(globalData.config.get("AlarmMonitor","colourGrey")))
				buttonText = fontButton.render("Verlauf", 1, pygame.Color(globalData.config.get("AlarmMonitor","colourBlack")))
				(width, height) = fontButton.size("Verlauf")
				textX = 20 + (buttonWidth - width)/2
				textY = buttonY + (buttonHeight - height)/2
				screen.blit(buttonText, (textX, textY))

				round_rect(screen, (120, buttonY, buttonWidth, buttonHeight), pygame.Color(globalData.config.get("AlarmMonitor","colourDimGrey")), 10, 1, pygame.Color(globalData.config.get("AlarmMonitor","colourGrey")))
				buttonText = fontButton.render("Status", 1, pygame.Color(globalData.config.get("AlarmMonitor","colourBlack")))
				(width, height) = fontButton.size("Status")
				textX = 120 + (buttonWidth - width)/2
				textY = buttonY + (buttonHeight - height)/2
				screen.blit(buttonText, (textX, textY))

				round_rect(screen, (220, buttonY, buttonWidth, buttonHeight), pygame.Color(globalData.config.get("AlarmMonitor","colourDimGrey")), 10, 1, pygame.Color(globalData.config.get("AlarmMonitor","colourGrey")))
				buttonText = fontButton.render("Gelesen", 1, pygame.Color(globalData.config.get("AlarmMonitor","colourBlack")))
				(width, height) = fontButton.size("Gelesen")
				textX = 220 + (buttonWidth - width)/2
				textY = buttonY + (buttonHeight - height)/2
				screen.blit(buttonText, (textX, textY))

			## end if globalData.showDisplay == True

			else:
				GPIO.output(globalData.config.getint("Display","GPIOPinForBacklight"), GPIO.LOW)

			# Update display...
			pygame.display.update()
		## end while globalData.running == True

	except:
		logging.error("unknown error in displayPainter-thread")
		logging.debug("unknown error in displayPainter-thread", exc_info=True)
		# abort main program
		globalData.abort = True
		sys.exit(1)
	finally:
		logging.debug("exit displayPainter-thread")
		GPIO.output(globalData.config.getint("Display","GPIOPinForBacklight"), GPIO.LOW)
		GPIO.cleanup()
		pygame.quit()
		exit(0)
Esempio n. 22
0
def displayPainter():
    """
	Asynchronous function to build the display content

	@requires: globalData.showDisplay        - status of backlight
	@requires: globalData.enableDisplayUntil - given timestamp when backlight will turned off
	@requires: globalData.running            - service runs as long as this is True
	@requires: globalData.data               - data of the last alarm
	@requires: globalData.lastAlarm          - timestamp of the last processing (see alarmRICs and keepAliveRICs)
	@requires: configuration has to be set in the config.ini

	In case of an exception the function set globalData.abort to True.
	This will terminate the main program.

	@return:    nothing
	@exception: SystemExit exception in case of an error
	"""

    import sys
    import time
    import logging
    import ConfigParser
    import RPi.GPIO as GPIO
    import pygame
    from wrapline import wrapline
    from roundrects import round_rect
    import globalData

    logging.debug("displayPainter-thread called")

    try:
        # use GPIO pin numbering convention
        GPIO.setmode(GPIO.BCM)
        GPIO.setwarnings(False)
        # set up GPIO pin for output
        GPIO.setup(globalData.config.getint("Display", "GPIOPinForBacklight"),
                   GPIO.OUT)

        pygame.init()

        #screen size
        size = (globalData.config.getint("Display", "displayWidth"),
                globalData.config.getint("Display", "displayHeight"))
        screen = pygame.display.set_mode(size)

        # disable mouse cursor
        pygame.mouse.set_visible(False)

        #define fonts
        fontHeader = pygame.font.Font(None, 30)
        fontHeader.set_bold(True)
        fontHeader.set_underline(True)

        fontTime = pygame.font.Font(None, 15)

        fontRIC = pygame.font.Font(None, 30)
        fontRIC.set_bold(True)
        fontMsg = pygame.font.Font(None, 20)
        fontHistory = pygame.font.Font(None, 15)

        fontStatus = pygame.font.Font(None, 20)
        fontStatus.set_bold(True)
        fontStatusContent = pygame.font.Font(None, 20)

        fontButton = pygame.font.Font(None, 20)

        clock = pygame.time.Clock()

        # Build Lists out of config-entries
        functionCharTestAlarm = [
            x.strip()
            for x in globalData.config.get("AlarmMonitor",
                                           "functionCharTestAlarm").replace(
                                               ";", ",").split(",")
        ]

        logging.debug("displayPainter-thread started")

        # Running will be set to False if main program is shutting down
        while globalData.running == True:
            # This limits the while loop to a max of 2 times per second.
            # Leave this out and we will use all CPU we can.
            clock.tick(2)

            # current time for this loop:
            curtime = int(time.time())

            if globalData.showDisplay == True:
                # Enable LCD display
                GPIO.output(
                    globalData.config.getint("Display", "GPIOPinForBacklight"),
                    GPIO.HIGH)
                # Clear the screen and set the screen background
                screen.fill(globalData.screenBackground)
                # paint black rect, so Background looks like a boarder
                widthX = globalData.config.getint("Display",
                                                  "displayWidth") - 20
                widthY = globalData.config.getint("Display",
                                                  "displayHeight") - 20
                pygame.draw.rect(
                    screen,
                    pygame.Color(
                        globalData.config.get("AlarmMonitor", "colourBlack")),
                    (10, 10, widthX, widthY))
                # header
                header = fontHeader.render(
                    "Alarm-Monitor", 1,
                    pygame.Color(
                        globalData.config.get("AlarmMonitor", "colourRed")))
                (width, height) = fontHeader.size("Alarm-Monitor")
                x = (int(globalData.config.getint("Display", "displayWidth")) -
                     width) / 2
                screen.blit(header, (x, 20))

                # show time of last alarm
                if globalData.lastAlarm > 0:
                    try:
                        # format last alarm
                        lastAlarmString = time.strftime(
                            "%H:%M:%S", time.localtime(globalData.lastAlarm))
                        # Color time:
                        # red: lastAlarm more than n (delayForRed) seconds past
                        if (int(globalData.lastAlarm) +
                                globalData.config.getint(
                                    "AlarmMonitor", "delayForRed")) < curtime:
                            timeColour = pygame.Color(
                                globalData.config.get("AlarmMonitor",
                                                      "colourRed"))
                        # yellow: lastAlarm more than n (delayForYellow) seconds past
                        elif (int(globalData.lastAlarm) +
                              globalData.config.getint(
                                  "AlarmMonitor", "delayForYellow")) < curtime:
                            timeColour = pygame.Color(
                                globalData.config.get("AlarmMonitor",
                                                      "colourYellow"))
                        # dgrey: normal
                        else:
                            timeColour = pygame.Color(
                                globalData.config.get("AlarmMonitor",
                                                      "colourGreen"))
                        lastAlarm = fontTime.render(lastAlarmString, 1,
                                                    timeColour)
                        (width, height) = fontTime.size(lastAlarmString)
                        x = globalData.config.getint(
                            "Display", "displayWidth") - 20 - width
                        screen.blit(lastAlarm, (x, 20))
                    except:
                        logging.debug("unknown error in lastAlarm",
                                      exc_info=True)
                        pass
                ## end if globalData.lastAlarm > 0

                # show remaining time before display will be turned off:
                restZeit = globalData.enableDisplayUntil - curtime + 1
                zeit = fontTime.render(
                    str(restZeit), 1,
                    pygame.Color(
                        globalData.config.get("AlarmMonitor",
                                              "colourDimGrey")))
                screen.blit(zeit, (20, 20))

                #
                # content given by navigation:
                # default is "alarmPage"
                #
                # Startpoint for content
                if globalData.navigation == "historyPage":
                    try:
                        y = 50
                        for data in reversed(globalData.alarmHistory):
                            # Layout:
                            # Date Description
                            # Time Msg

                            # Prepare date/time block
                            dateString = time.strftime(
                                "%d.%m.%y", time.localtime(data['timestamp']))
                            timeString = time.strftime(
                                "%H:%M:%S", time.localtime(data['timestamp']))
                            if int(fontHistory.size(dateString)[0]) > int(
                                    fontHistory.size(timeString)[0]):
                                (shifting,
                                 height) = fontHistory.size(dateString)
                            else:
                                (shifting,
                                 height) = fontHistory.size(timeString)
                            shifting += 5

                            # get colour
                            if data['functionChar'] in functionCharTestAlarm:
                                colour = globalData.config.get(
                                    "AlarmMonitor", "colourYellow")
                            else:
                                colour = globalData.config.get(
                                    "AlarmMonitor", "colourRed")

                            # Paint Date/Time
                            screen.blit(
                                fontHistory.render(dateString, 1,
                                                   pygame.Color(colour)),
                                (20, y))
                            screen.blit(
                                fontHistory.render(timeString, 1,
                                                   pygame.Color(colour)),
                                (20, y + height))

                            # Paint Description
                            try:
                                textLines = wrapline(
                                    data['description'], fontHistory,
                                    (globalData.config.getint(
                                        "Display", "displayWidth") - shifting -
                                     40))
                                for index, item in enumerate(textLines):
                                    textZeile = fontHistory.render(
                                        item, 1,
                                        pygame.Color(
                                            globalData.config.get(
                                                "AlarmMonitor",
                                                "colourWhite")))
                                    screen.blit(textZeile, (20 + shifting, y))
                                    y += height
                            except KeyError:
                                pass

                            # Paint Msg
                            try:
                                textLines = wrapline(
                                    data['msg'].replace("*", " * "),
                                    fontHistory, (globalData.config.getint(
                                        "Display", "displayWidth") - shifting -
                                                  40))
                                for index, item in enumerate(textLines):
                                    textZeile = fontHistory.render(
                                        item, 1,
                                        pygame.Color(
                                            globalData.config.get(
                                                "AlarmMonitor", "colourGrey")))
                                    screen.blit(textZeile, (20 + shifting, y))
                                    y += height
                            except KeyError:
                                pass

                            # line spacing for next dataset
                            y += 2

                        ## end for globalData.alarmHistory

                    except KeyError:
                        pass
                ## end if globalData.navigation == "historyPage"

                elif globalData.navigation == "statusPage":
                    (width,
                     height) = fontStatusContent.size("Anzahl Test-Alarme:")
                    y = 70
                    x = width + 10
                    # Running since:
                    title = fontStatusContent.render(
                        "Gestartet:", 1,
                        pygame.Color(
                            globalData.config.get("AlarmMonitor",
                                                  "colourWhite")))
                    content = fontStatusContent.render(
                        time.strftime("%d.%m.%Y %H:%M:%S",
                                      time.localtime(globalData.startTime)), 1,
                        pygame.Color(
                            globalData.config.get("AlarmMonitor",
                                                  "colourGrey")))
                    screen.blit(title, (20, y))
                    screen.blit(content, (20 + x, y))
                    y += height + 10

                    # Last Alarm
                    title = fontStatusContent.render(
                        "Letzte Nachricht:", 1,
                        pygame.Color(
                            globalData.config.get("AlarmMonitor",
                                                  "colourWhite")))
                    if globalData.lastAlarm > 0:
                        content = fontStatusContent.render(
                            time.strftime("%d.%m.%Y %H:%M:%S",
                                          time.localtime(
                                              globalData.lastAlarm)), 1,
                            timeColour)
                    else:
                        content = fontStatusContent.render(
                            "-", 1,
                            pygame.Color(
                                globalData.config.get("AlarmMonitor",
                                                      "colourGrey")))
                    screen.blit(title, (20, y))
                    screen.blit(content, (20 + x, y))
                    y += height + 10

                    # Number of Alarms
                    title = fontStatusContent.render(
                        "Anzahl Alarme:", 1,
                        pygame.Color(
                            globalData.config.get("AlarmMonitor",
                                                  "colourWhite")))
                    content = fontStatusContent.render(
                        str(globalData.countAlarm), 1,
                        pygame.Color(
                            globalData.config.get("AlarmMonitor",
                                                  "colourGrey")))
                    screen.blit(title, (20, y))
                    screen.blit(content, (20 + x, y))
                    y += height + 10

                    # Number of TestAlarms
                    title = fontStatusContent.render(
                        "Anzahl Test-Alarme:", 1,
                        pygame.Color(
                            globalData.config.get("AlarmMonitor",
                                                  "colourWhite")))
                    content = fontStatusContent.render(
                        str(globalData.countTestAlarm), 1,
                        pygame.Color(
                            globalData.config.get("AlarmMonitor",
                                                  "colourGrey")))
                    screen.blit(title, (20, y))
                    screen.blit(content, (20 + x, y))
                    y += height + 10

                    # Number of DAU-Msgs
                    title = fontStatusContent.render(
                        "Anzahl DAU-Tests:", 1,
                        pygame.Color(
                            globalData.config.get("AlarmMonitor",
                                                  "colourWhite")))
                    content = fontStatusContent.render(
                        str(globalData.countKeepAlive), 1,
                        pygame.Color(
                            globalData.config.get("AlarmMonitor",
                                                  "colourGrey")))
                    screen.blit(title, (20, y))
                    screen.blit(content, (20 + x, y))
                    y += height + 10

                ## end if globalData.navigation == "statusPage"

                else:
                    y = 50

                    # Paint Date/Time
                    try:
                        dateTimeString = time.strftime(
                            "%d.%m.%Y %H:%M:%S",
                            time.localtime(globalData.data['timestamp']))
                        dateTimeRow = fontStatus.render(
                            dateTimeString, 1,
                            pygame.Color(
                                globalData.config.get("AlarmMonitor",
                                                      "colourDimGrey")))
                        (width, height) = fontStatus.size(dateTimeString)
                        x = (int(
                            globalData.config.getint(
                                "Display", "displayWidth")) - width) / 2
                        screen.blit(dateTimeRow, (x, y))
                        y += height + 10
                    except KeyError:
                        pass

                    # Paint Description
                    try:
                        textLines = wrapline(
                            globalData.data['description'],
                            fontRIC, (globalData.config.getint(
                                "Display", "displayWidth") - 40))
                        (width, height) = fontStatus.size(
                            globalData.data['description'])
                        for index, item in enumerate(textLines):
                            textRow = fontRIC.render(
                                item, 1,
                                pygame.Color(
                                    globalData.config.get(
                                        "AlarmMonitor", "colourWhite")))
                            screen.blit(textRow, (20, y))
                            y += height + 5
                    except KeyError:
                        pass

                    # Paint Msg
                    try:
                        y += 10
                        textLines = wrapline(
                            globalData.data['msg'].replace("*", " * "),
                            fontMsg, (globalData.config.getint(
                                "Display", "displayWidth") - 40))
                        (width,
                         height) = fontStatus.size(globalData.data['msg'])
                        for index, item in enumerate(textLines):
                            textRow = fontMsg.render(
                                item, 1,
                                pygame.Color(
                                    globalData.config.get(
                                        "AlarmMonitor", "colourGrey")))
                            screen.blit(textRow, (20, y))
                            y += height
                    except KeyError:
                        pass
                ## end if default navigation

                # paint navigation buttons
                buttonWidth = 80
                buttonHeight = 25
                buttonY = globalData.config.getint(
                    "Display", "displayHeight") - buttonHeight - 2

                round_rect(
                    screen, (20, buttonY, buttonWidth, buttonHeight),
                    pygame.Color(
                        globalData.config.get("AlarmMonitor",
                                              "colourDimGrey")), 10, 1,
                    pygame.Color(
                        globalData.config.get("AlarmMonitor", "colourGrey")))
                buttonText = fontButton.render(
                    "Verlauf", 1,
                    pygame.Color(
                        globalData.config.get("AlarmMonitor", "colourBlack")))
                (width, height) = fontButton.size("Verlauf")
                textX = 20 + (buttonWidth - width) / 2
                textY = buttonY + (buttonHeight - height) / 2
                screen.blit(buttonText, (textX, textY))

                round_rect(
                    screen, (120, buttonY, buttonWidth, buttonHeight),
                    pygame.Color(
                        globalData.config.get("AlarmMonitor",
                                              "colourDimGrey")), 10, 1,
                    pygame.Color(
                        globalData.config.get("AlarmMonitor", "colourGrey")))
                buttonText = fontButton.render(
                    "Status", 1,
                    pygame.Color(
                        globalData.config.get("AlarmMonitor", "colourBlack")))
                (width, height) = fontButton.size("Status")
                textX = 120 + (buttonWidth - width) / 2
                textY = buttonY + (buttonHeight - height) / 2
                screen.blit(buttonText, (textX, textY))

                round_rect(
                    screen, (220, buttonY, buttonWidth, buttonHeight),
                    pygame.Color(
                        globalData.config.get("AlarmMonitor",
                                              "colourDimGrey")), 10, 1,
                    pygame.Color(
                        globalData.config.get("AlarmMonitor", "colourGrey")))
                buttonText = fontButton.render(
                    "Gelesen", 1,
                    pygame.Color(
                        globalData.config.get("AlarmMonitor", "colourBlack")))
                (width, height) = fontButton.size("Gelesen")
                textX = 220 + (buttonWidth - width) / 2
                textY = buttonY + (buttonHeight - height) / 2
                screen.blit(buttonText, (textX, textY))

            ## end if globalData.showDisplay == True

            else:
                GPIO.output(
                    globalData.config.getint("Display", "GPIOPinForBacklight"),
                    GPIO.LOW)

            # Update display...
            pygame.display.update()
        ## end while globalData.running == True

    except:
        logging.error("unknown error in displayPainter-thread")
        logging.debug("unknown error in displayPainter-thread", exc_info=True)
        # abort main program
        globalData.abort = True
        sys.exit(1)
    finally:
        logging.debug("exit displayPainter-thread")
        GPIO.output(globalData.config.getint("Display", "GPIOPinForBacklight"),
                    GPIO.LOW)
        GPIO.cleanup()
        pygame.quit()
        exit(0)
Esempio n. 23
0
def lookup(surface):
    state = LOOKUP
    #left
    roundrects.round_rect(surface, [LEYPOS, EYPOS - 40, EW, EH], TUR, rad=30)
    #right
    roundrects.round_rect(surface, [REYPOS, EYPOS - 40, EW, EH], TUR, rad=30)