示例#1
0
    def __captureStream( self ):
        if self.__imageProcessingDone:
            # Create a memory buffer where the captured image can be placed
            stream = io.BytesIO()
            rgb = bytearray( self.__SCREEN_RESOLUTION[0] * self.__SCREEN_RESOLUTION[1] * 3 )
            yuv = bytearray( len( rgb ) / 2 )

            # Capture the image
            self.__camera.capture(
                stream,
                use_video_port=True,
                format='yuv' )

            # Move the image from the IO stream into a buffer
            stream.seek(0)
            stream.readinto( yuv )  # stream -> YUV buffer
            stream.close()

            # Convert from YUV format to RGB
            yuv2rgb.convert(
                yuv,
                rgb,
                self.__SCREEN_RESOLUTION[0],
                self.__SCREEN_RESOLUTION[1] )

            # Mangle the image
            img = pygame.image.frombuffer(
                rgb,
                self.__SCREEN_RESOLUTION,
                'RGB' )

            # Put the captured image as the base layer for the screen
            self.__screen.blit( img, ( 0, 0 ) )
 def preview(self):
     stream = io.BytesIO()
     self.cam.capture(stream, use_video_port=True, format='raw')
     stream.seek(0)
     stream.readinto(yuv)
     stream.close()
     yuv2rgb.convert(yuv, rgb, SCREEN_RESOLUTION[0],
     SCREEN_RESOLUTION[1])
     return rgb[0: (SCREEN_RESOLUTION[0] * SCREEN_RESOLUTION[1] * 3)]
示例#3
0
def showViewport():
    stream = io.BytesIO()  # Capture into in-memory stream
    camera.capture(stream, use_video_port=True, format='raw')
    stream.seek(0)
    stream.readinto(yuv)  # stream -> YUV buffer
    stream.close()
    yuv2rgb.convert(yuv, rgb, sizeData[1][0], sizeData[1][1])
    img = pygame.image.frombuffer(rgb[0:(sizeData[1][0] * sizeData[1][1] * 3)],
                                  sizeData[1], 'RGB')

    if img:
        screen.blit(img, ((320 - img.get_width()) / 2,
                          (240 - img.get_height()) / 2))
    pygame.display.update()
def stream_to_screen():
	stream = io.BytesIO()
        camera.capture(stream, use_video_port=True, format='raw')
	stream.seek(0)
	stream.readinto(yuv)
	stream.close()
	yuv2rgb.convert(yuv, rgb, size[0], size[1])
	img = pygame.image.frombuffer(rgb[0:(size[0]*size[1]*3)], size, 'RGB')
	screen.blit(img, ((width - img.get_width() ) / 2, (height - img.get_height()) / 2))

	# Overlay and draw the buttons, then update the display
	go.draw(screen)
	shutdown.draw(screen)	
	pygame.display.update()
示例#5
0
    def get_camera_image(self):
        rgb = bytearray(320 * 240 * 3)
        yuv = bytearray(int(320 * 240 * 3 / 2))

        stream = io.BytesIO()  # Capture into in-memory stream
        self.camera.capture(stream, use_video_port=True, format='raw')
        stream.seek(0)
        stream.readinto(yuv)  # stream -> YUV buffer
        stream.close()
        yuv2rgb.convert(yuv, rgb, self.SCREEN_RESOLUTION[0],
                        self.SCREEN_RESOLUTION[1])

        img = pygame.image.frombuffer(
            rgb[0:(self.SCREEN_RESOLUTION[0] * self.SCREEN_RESOLUTION[1] * 3)],
            self.SCREEN_RESOLUTION, 'RGB')
        return img
示例#6
0
def preview(screen):
    global sizeMode, camera, yuv, rgb, sizeData
    if config.recording:
        img = pygame.image.load('/home/pi/touch-flux/icons/gear.png')
        screen.blit(img, ((320 - img.get_width()) / 2,
                          (240 - img.get_height()) / 2))
        return None
    stream = io.BytesIO()  # Capture into in-memory stream
    camera.capture(stream, use_video_port=True, format='raw')
    stream.seek(0)
    stream.readinto(yuv)  # stream -> YUV buffer
    stream.close()
    yuv2rgb.convert(yuv, rgb, sizeData[sizeMode][1][0],
                    sizeData[sizeMode][1][1])
    img = pygame.image.frombuffer(
        rgb[0:(sizeData[sizeMode][1][0] * sizeData[sizeMode][1][1] * 3)],
        sizeData[sizeMode][1], 'RGB')
    #    img = pygame.transform.scale(img, (320,240))
    screen.blit(img,
                ((320 - img.get_width()) / 2, (240 - img.get_height()) / 2))
示例#7
0
def preview(screen):
    global sizeMode, camera, yuv1, rgb1, yuv2, rgb2, sizeData, stream
    stream = io.BytesIO() # Capture into in-memory stream
    camera.capture(stream, use_video_port=True, format='raw')
    stream.seek(0)
    if config.recording:
      #  yuv = bytearray(sizeData[config.mode][0][0]*sizeData[config.mode][0][1]*3/2)
      #  rgb = bytearray(sizeData[config.mode][0][0]*sizeData[config.mode][0][1]*3)
        stream.readinto(yuv1)  # stream -> YUV buffer
        yuv2rgb.convert(yuv1, rgb1, sizeData[config.mode][0][0], sizeData[config.mode][0][1])
        img = pygame.image.frombuffer(rgb1[0:(sizeData[config.mode][0][0] * sizeData[config.mode][0][1] * 3)],sizeData[config.mode][0], 'RGB')
        #os.system("convert img -resize 200X100 img")
        img = pygame.transform.scale(img, (320,240))
    else:
      #  rgb = bytearray(320 * 240 * 3)
      #  yuv = bytearray(320 * 240 * 3 / 2)
        stream.readinto(yuv2)  # stream -> YUV buffer
        yuv2rgb.convert(yuv2, rgb2, sizeData[config.mode][1][0],sizeData[config.mode][1][1])
        img = pygame.image.frombuffer(rgb2[0:(sizeData[config.mode][1][0] * sizeData[config.mode][1][1] * 3)],sizeData[config.mode][1], 'RGB')

#    stream.close()
#    if config.recording:
#    else:
    screen.blit(img,((320 - img.get_width() ) / 2,(240 - img.get_height()) / 2))
示例#8
0
文件: pic.py 项目: agherzan/piTFT
def main():
    global liveFlag 

    #this path is where we store our arrow icons
    installPath = "/usr/src/app/img/"

    # font colours
    colourWhite = (255, 255, 255)
    colourBlack = (0, 0, 0)
    colourGreen = (3, 192, 60)
    colourRed = (220, 69, 69)

    # Create an instance of the pitft class
    mytft = pitft()

    #hide the mouse from screen
    pygame.mouse.set_visible(False)

    # set up the fonts
    # choose the font
    fontpath = pygame.font.match_font('dejavusansmono')
    font = pygame.font.Font(fontpath, 10)

    #read the ENV VAR, use GE if 'STOCK' isn't there
    #companyName = os.getenv('STOCK', "GE")
    #print 'company name: '+companyName

    logo = pygame.image.load( "/usr/src/app/resin.png")
    mytft.screen.blit(logo, (0, 0))

    pygame.display.update()

    GPIO.setmode(GPIO.BCM)

    GPIO.setup(23, GPIO.IN, pull_up_down=GPIO.PUD_UP)
    GPIO.setup(22, GPIO.IN, pull_up_down=GPIO.PUD_UP)
#    GPIO.setup(27, GPIO.IN, pull_up_down=GPIO.PUD_UP)  
#    GPIO.setup(18, GPIO.IN, pull_up_down=GPIO.PUD_UP) 

 
#    GPIO.add_event_detect(18, GPIO.RISING, callback=picView)  # add rising edge detection on a channel
#    GPIO.add_event_detect(27, GPIO.RISING, callback=liveFeed)  # add rising edge detection on a channel    
    GPIO.add_event_detect(23, GPIO.RISING, callback=redB)  # add rising edge detection on a channel
    GPIO.add_event_detect(22, GPIO.RISING, callback=greenB)  # add rising edge detection on a channel


    sizeMode = 0

    sizeData = [ # Camera parameters for different size settings
     # Full res      Viewfinder  Crop window
     [(2592, 1944), (320, 240), (0.0   , 0.0   , 1.0   , 1.0   )], # Large
     [(1920, 1080), (320, 180), (0.1296, 0.2222, 0.7408, 0.5556)], # Med
     [(1440, 1080), (320, 240), (0.2222, 0.2222, 0.5556, 0.5556)]] # Small

    # Buffers for viewfinder data
    rgb = bytearray(320 * 240 * 3)
    yuv = bytearray(320 * 240 * 3 / 2)

    if os.path.isfile('update_count.txt'):
        with open('update_count.txt','rb') as f:
            updates = int(f.readline())
    else:
        updates = 0

    stripped = lambda s: "".join(i for i in s if 31 < ord(i) < 127)

    colourWhite = (255, 255, 255)
    colourBlack = (0, 0, 0)
    colourGreen = (3, 192, 60)
    colourRed = (220, 69, 69)
    colourPink = (255, 20, 147)

    textAnchorX = 10
    textAnchorY = 10
    textYoffset = 10
    listMax = 240/textYoffset

    while True:

        if liveFlag == 0:

            camera            = picamera.PiCamera()

            camera.resolution = sizeData[sizeMode][1]
            camera.crop       = (0.0, 0.0, 1.0, 1.0)

            liveFlag = 1

        elif liveFlag == 1:

            stream = io.BytesIO() # Capture into in-memory stream
            camera.capture(stream, use_video_port=True, format='raw')
            stream.seek(0)
            stream.readinto(yuv)  # stream -> YUV buffer
            stream.close()
            yuv2rgb.convert(yuv, rgb, sizeData[sizeMode][1][0], sizeData[sizeMode][1][1])
            img = pygame.image.frombuffer(rgb[0: (sizeData[sizeMode][1][0] * sizeData[sizeMode][1][1] * 3)], sizeData[sizeMode][1], 'RGB')
            if img is None or img.get_height() < 240: # Letterbox, clear background
                mytft.screen.fill(0)
            if img:
                mytft.screen.blit(img,((320 - img.get_width() ) / 2, (240 - img.get_height()) / 2))

            pygame.display.update()

        elif liveFlag == 2:
            print "taking pic"
            #camera.resolution = (1024,768)
            name = 'image.jpg'

            camera.capture(name, resize=(320, 240))
            #time.sleep(0.1)

            print "Pic to screen"
            logo = pygame.image.load(name)
            mytft.screen.blit(logo, (0, 0))

            #pygame.display.flip()
            # # refresh the screen with all the changes
            pygame.display.update()
            print "Screen updated"
            time.sleep(0.1)
            camera.resolution = sizeData[sizeMode][1]
            camera.crop       = (0.0, 0.0, 1.0, 1.0)

            liveFlag = 3


        elif liveFlag == 4:
            
            # clear the screen
            mytft.screen.fill(colourBlack)
            # set the anchor/positions for the current stock data text
            textAnchorX = 10
            textAnchorY = 10

            line = "git status"
            print line
            text_surface = font.render(line, True, colourRed)
            mytft.screen.blit(text_surface, (textAnchorX, textAnchorY))
            textAnchorY += textYoffset
            pygame.display.update()

            for line in sh.git( "status", _iter=True):
                print(line)
                line = stripped(line)

                text_surface = font.render(line, True, colourWhite)
                mytft.screen.blit(text_surface, (textAnchorX, textAnchorY))

                pygame.display.update()
                textAnchorY += textYoffset
                if textAnchorY + textYoffset > 240:
                    textAnchorY = 10
                    mytft.screen.fill(colourBlack)

                time.sleep(0.1)

            time.sleep(3)

            updates += 1
            with open('update_count.txt','wb') as f:
                f.write(str(updates))

            mytft.screen.fill(colourBlack)

            textAnchorX = 10
            textAnchorY = 10    

            line = "git add ."
            print line
            text_surface = font.render(line, True, colourRed)
            mytft.screen.blit(text_surface, (textAnchorX, textAnchorY))
            textAnchorY += textYoffset
            pygame.display.update()

            for line in sh.git.add ("image.jpg", "update_count.txt", _iter=True):
                print(line)
                line = stripped(line)

                text_surface = font.render(line, True, colourWhite)
                mytft.screen.blit(text_surface, (textAnchorX, textAnchorY))

                pygame.display.update()
                textAnchorY += textYoffset
                if textAnchorY + textYoffset > 240:
                    textAnchorY = 10
                    mytft.screen.fill(colourBlack)

                time.sleep(0.1)

            liveFlag = 5

        elif liveFlag == 6:

            mytft.screen.fill(colourBlack)

            textAnchorX = 10
            textAnchorY = 10

            line = "git commit -m "
            print line
            text_surface = font.render(line, True, colourRed)
            mytft.screen.blit(text_surface, (textAnchorX, textAnchorY))
            textAnchorY += textYoffset
            pygame.display.update()

            for line in sh.git( "commit", "-m", "Auto commit", _iter="out"):
                print(line)
                line = stripped(line)

                text_surface = font.render(line, True, colourWhite)
                mytft.screen.blit(text_surface, (textAnchorX, textAnchorY))

                pygame.display.update()
                textAnchorY += textYoffset
                if textAnchorY + textYoffset > 240:
                    textAnchorY = 10
                    mytft.screen.fill(colourBlack)
                
                time.sleep(0.1)           
                 
            liveFlag = 7

        elif liveFlag == 8:

            mytft.screen.fill(colourBlack)

            textAnchorX = 10
            textAnchorY = 10

            line = "git push resin master"
            print line
            text_surface = font.render(line, True, colourRed)
            mytft.screen.blit(text_surface, (textAnchorX, textAnchorY))
            textAnchorY += textYoffset
            pygame.display.update()

            color = colourWhite

            sc = []

            sc.append("git push resin master")

            for line in sh.git( "push", "resin", "master", "--force", _iter="err"):
                print(line)
                line = stripped(line)

                color = colourWhite                    

                sc.append(line)
                if len(sc) >= listMax :
                    sc.pop(1)

                textAnchorY = 0
                mytft.screen.fill(colourBlack)
                for idx, lines in enumerate(sc):
                    if idx == 0:
                        try:
                            text_surface = font.render(lines, True, colourRed)
                            mytft.screen.blit(text_surface, (textAnchorX, textAnchorY))
                            textAnchorY += textYoffset
                        except:
                            print "Could not render"
                    else:
                        if lines.find("Build took") >= 0 or  lines.find(">\\/7") >= 0 :
                            print "Unicorn found"
                            color = colourPink

                        text_surface = font.render(lines, True, color)
                        mytft.screen.blit(text_surface, (textAnchorX, textAnchorY))
                        textAnchorY += textYoffset

                pygame.display.update()

                time.sleep(0.1)

            liveFlag = 9

        elif liveFlag == 10:

        
            camera.close()
        
            logo = pygame.image.load( "/usr/src/app/resin.png")
            mytft.screen.blit(logo, (0, 0))

            pygame.display.update()

            liveFlag = 11               
        
        else :   
        
            time.sleep(1)
示例#9
0
文件: cam.py 项目: VitharMe/camera23
def deploy():
    # Where your .py file is located
    current_path = os.path.dirname(__file__)

    GPIO.setmode(GPIO.BCM)
    GPIO.setup(17, GPIO.IN, pull_up_down=GPIO.PUD_UP)
    GPIO.setup(22, GPIO.IN, pull_up_down=GPIO.PUD_UP)
    GPIO.setup(23, GPIO.IN, pull_up_down=GPIO.PUD_UP)
    GPIO.setup(27, GPIO.IN, pull_up_down=GPIO.PUD_UP)

    screenMode = 3
    sizeMode = 0

    sizeData = [[(1440, 1080), (320, 240), (0.2222, 0.2222, 0.5556, 0.5556)]]

    os.putenv('SDL_VIDEODRIVER', 'fbcon')
    os.putenv('SDL_FBDEV', '/dev/fb1')

    rgb = bytearray(320 * 240 * 3)
    yuv = bytearray(320 * 240 * 3 / 2)

    pygame.init()
    pitft = pigame.PiTft()
    pygame.mouse.set_visible(False)
    screen = pygame.display.set_mode((0, 0), pygame.FULLSCREEN)

    camera = picamera.PiCamera()
    atexit.register(camera.close)
    camera.resolution = sizeData[sizeMode][1]
    camera.crop = (0.0, 0.0, 1.0, 1.0)
    camera.rotation = 270
    try:
        while (True):
            pitft.update()
            event = pygame.event.poll()
            stream = io.BytesIO()
            camera.capture(stream, use_video_port=True, format='raw')
            stream.seek(0)
            stream.readinto(yuv)
            stream.close()
            yuv2rgb.convert(yuv, rgb, sizeData[sizeMode][1][0],
                            sizeData[sizeMode][1][1])
            img = pygame.image.frombuffer(
                rgb[0:(sizeData[sizeMode][1][0] * sizeData[sizeMode][1][1] *
                       3)], sizeData[sizeMode][1], 'RGB')
            if img:
                screen.blit(img, ((320 - img.get_width()) / 2,
                                  (240 - img.get_height()) / 2))
            for event in pygame.event.get():
                if (event.type is MOUSEBUTTONDOWN):
                    x, y = pygame.mouse.get_pos()
                elif (event.type is MOUSEBUTTONUP):
                    x, y = pygame.mouse.get_pos()
                    if y > 200:
                        if x < 50:
                            print("Cross")
                            subprocess.Popen(
                                ["python", "/home/pi/camera23/menu.py"])
                            exit()

#menu.deploy()
                        else:
                            print("Photo")
                            pygame.draw.rect(screen, (255, 255, 255),
                                             (0, 0, 320, 240))
                            pygame.display.update()
                            now = datetime.datetime.now()
                            image_date = now.strftime(
                                "pics/%Y-%m-%d_%H%M%S.jpg")
                            image_path = os.path.join(current_path, image_date)
                            camera.capture(image_path)
                            img = pygame.image.load(image_path)
                            screen.blit(img, (0, 0))
                            pygame.display.update()
                            sleep(1)
            img_cross = pygame.image.load('resources/cross.png')
            screen.blit(img_cross, (280, 5))
            pygame.display.update()
            sleep(0.1)
    except KeyboardInterrupt:
        pass
    finally:
        del (pitft)
示例#10
0
                    if b.selected(pos): break

        # If in viewfinder or settings modes, stop processing touchscreen
        # and refresh the display to show the live preview.  In other modes
        # (image playback, etc.), stop and refresh the screen only when
        # screenMode changes.
        if screenMode >= 3 or screenMode != screenModePrior: break

    # Refresh display
    if screenMode >= 3:  # Viewfinder or settings modes
        stream = io.BytesIO()  # Capture into in-memory stream
        camera.capture(stream, use_video_port=True, format='raw')
        stream.seek(0)
        stream.readinto(yuv)  # stream -> YUV buffer
        stream.close()
        yuv2rgb.convert(yuv, rgb, sizeData[1][0], sizeData[1][1])
        img = pygame.image.frombuffer(
            rgb[0:(sizeData[1][0] * sizeData[1][1] * 3)], sizeData[1], 'RGB')

    elif screenMode < 2:  # Playback mode or delete confirmation
        img = scaled  # Show last-loaded image
    else:  # 'No Photos' mode
        img = None  # You get nothing, good day sir

    if img is None or img.get_height() < 240:  # Letterbox, clear background
        screen.fill(0)

    if img:
        screen.blit(img, ((320 - img.get_width()) / 2,
                          (240 - img.get_height()) / 2))
示例#11
0
				if b.selected(pos): break
				
	if(screenMode == 0):
		for CS in CAM_CS:
			testCamera(CS)
		print(screenMode)
		screen.fill(0)
		time.sleep(0.1)
		
	elif(screenMode == 1):
		buttonState = wiringpi.digitalRead(triggerButton)
		if(buttonState != lastButtonState):
			if(buttonState == wiringpi.LOW):
				takePicture()
		lastButtonState = buttonState
		stream = io.BytesIO() # Capture into in-memory stream
		camera.capture(stream, use_video_port=True, format='raw')
		stream.seek(0)
		stream.readinto(yuv)  # stream -> YUV buffer
		stream.close()
		yuv2rgb.convert(yuv, rgb, SCREEN_WIDTH, SCREEN_HEIGHT)
		img = pygame.image.frombuffer(rgb[0:(SCREEN_WIDTH * SCREEN_HEIGHT * 3)],(SCREEN_WIDTH, SCREEN_HEIGHT), 'RGB')
	
		if img:
			screen.blit(img,(0,0))
			
	for i,b in enumerate(buttons[screenMode]):
		b.draw(screen)
		
	pygame.display.update()
示例#12
0
        for b in buttons[screenMode]:
          if b.selected(pos): break
    # If in viewfinder or settings modes, stop processing touchscreen
    # and refresh the display to show the live preview.  In other modes
    # (image playback, etc.), stop and refresh the screen only when
    # screenMode changes.
    if screenMode >= 3 or screenMode != screenModePrior: break

  # Refresh display
  if screenMode >= 3: # Viewfinder or settings modes
    stream = io.BytesIO() # Capture into in-memory stream
    camera.capture(stream, use_video_port=True, format='raw')
    stream.seek(0)
    stream.readinto(yuv)  # stream -> YUV buffer
    stream.close()
    yuv2rgb.convert(yuv, rgb, sizeData[sizeMode][1][0],
      sizeData[sizeMode][1][1])
    img = pygame.image.frombuffer(rgb[0:
      (sizeData[sizeMode][1][0] * sizeData[sizeMode][1][1] * 3)],
      sizeData[sizeMode][1], 'RGB')
  elif screenMode < 2: # Playback mode or delete confirmation
    img = scaled       # Show last-loaded image
  else:                # 'No Photos' mode
    img = None         # You get nothing, good day sir

  if img is None or img.get_height() < 240: # Letterbox, clear background
    screen.fill(0)
  if img:
    screen.blit(img,
      ((320 - img.get_width() ) / 2,
       (240 - img.get_height()) / 2))
示例#13
0
            break

        if event.type is MOUSEBUTTONDOWN:
            pos = pygame.mouse.get_pos()
            for b in buttons[current_screen]:
                if b.selected(pos): break

    screen.fill(0)
    if not DEBUG:
        if current_screen == 1:
            stream = io.BytesIO()  # Capture into in-memory stream
            camera.capture(stream, use_video_port=True, format='raw')
            stream.seek(0)
            stream.readinto(yuv)  # stream -> YUV buffer
            stream.close()
            yuv2rgb.convert(yuv, rgb, 320, 240)
            img = pygame.image.frombuffer(rgb[0:(320 * 240 * 3)], (320, 240),
                                          'RGB')

            screen.blit(img, (0, 0))

        if current_screen == 2:
            if last_picture_path is not None and scaled is None:
                img = pygame.image.load(last_picture_path)
                scaled = pygame.transform.scale(img, (320, 240))
            if scaled is not None:
                screen.blit(scaled, (0, 0))

    for l in labels[current_screen]:
        screen.blit(l[0], l[1])
    for v in values[current_screen]:
示例#14
0
    def display(self):
        while True:
            if self.mode == 'gallery':                        
                self.screen.blit(self.image_in_view, (0,0))
                self.screen.blit(self.left, (20, 410))
                self.screen.blit(self.right, (240, 410))
                self.screen.blit(self.home, (125, 400))
                self.screen.blit(self.delete, (5, 5))
                self.screen.blit(self.upload, (40, 5))
                if self.deleted:
                    self.screen.blit(self.deleted_image, (79, 200))
                    if time.time() - self.delete_time > 3:
                        self.deleted = False
                if self.uploading:
                    self.screen.blit(self.uploading_image, (79, 200))
                    if time.time() - self.uploading_time > 6:
                        self.uploading = False
                
            if self.mode == 'capture':
                #Get camera stream
                self.stream = io.BytesIO() # Capture into in-memory stream
                self.camera.capture(self.stream, use_video_port=True, format='raw')
                self.stream.seek(0)
                self.stream.readinto(self.yuv)  # stream -> YUV buffer
                self.stream.close()
                yuv2rgb.convert(self.yuv, self.rgb, 320, 480)
            
                #Create pygame image from screen and blit it
                img = pygame.image.frombuffer(self.rgb[0:(320 * 480 * 3)], (320, 480), 'RGB')
                self.screen.blit(img, (0,0))
            
                #Blit buttons
                self.screen.blit(self.capture, (125, 400))
                self.screen.blit(self.gallery, (20, 415))
                self.screen.blit(self.door, (240, 410))

                if self.no_files:
                    self.screen.blit(self.no_files_image, (79, 200))
                    if time.time() - self.files_time > 3:
                        self.no_files = False
            
            pygame.display.update()
            
            #Handle events
            for event in pygame.event.get():
                if event.type == pygame.MOUSEBUTTONUP:
                    if self.mode == 'gallery':
                        if event.pos[1] < 40 and event.pos[0] < 35:
                            self.deleted = True
                            self.delete_time = time.time()
                            os.remove('/home/pi/Photos/' + self.images[self.current_image])
                            self.current_image = 0
                            self.images = os.listdir('/home/pi/Photos/')
                            if len(self.images) == 0:
                                self.mode = 'capture'
                                self.no_files = True
                                self.files_time = time.time()
                            
                        if event.pos[1] < 40 and event.pos[0] > 35 and event.pos[0] < 75:
                            self.uploading = True
                            self.uploading_time = time.time()
                            cam = Popen(['/home/pi/Dropbox-Uploader/./dropbox_uploader.sh', 'upload', '/home/pi/Photos/' +
                                         self.images[self.current_image], self.images[self.current_image]])
                            
                    if event.pos[1] > 400 and event.pos[1] < 470:
                        if event.pos[0] > 125 and event.pos[0] < 195:
                            if self.mode == 'capture':
                                self.camera.capture('/home/pi/Photos/' + str(self.index) + '.jpg')
                                self.index += 1
                            if self.mode == 'gallery':
                                self.mode = 'capture'
            
                        if event.pos[0] < 70:
                            if self.mode == 'capture':
                                self.mode = 'gallery'
                                self.current_image = 0
                                self.images = os.listdir('/home/pi/Photos/')
                                if len(self.images) == 0:
                                    self.mode = 'capture'
                                    self.no_files = True
                                    self.files_time = time.time()
                                else:
                                    self.image_in_view = pygame.image.load('/home/pi/Photos/' + self.images[self.current_image])
                                
                            if self.mode == 'gallery':
                                self.current_image -= 1
                                if self.current_image == -1:
                                    self.current_image = len(self.images) - 1
                                self.image_in_view = pygame.image.load('/home/pi/Photos/' + self.images[self.current_image])
                                
                        if event.pos[0] > 255:
                            if self.mode == 'capture':
                                print('exiting...')
                                os.remove('/home/pi/index.dat')
                                new = open('/home/pi/index.dat', 'w+')
                                new.write(str(self.index))
                                new.close()
                                cam = Popen(['sudo', 'python', '/home/pi/tyos/src/main.py'])
                                pygame.quit()
                                sys.exit()


                            if self.mode == 'gallery':
                                if self.current_image == len(self.images) - 1:
                                    self.current_image = 0
                                else:
                                    self.current_image += 1
                                self.image_in_view = pygame.image.load('/home/pi/Photos/' + self.images[self.current_image])
示例#15
0
    def display(self):
        while True:
            if self.mode == 'gallery':                        
                self.screen.blit(self.image_in_view, (0,0))
                self.screen.blit(self.left, (20, 410))
                self.screen.blit(self.right, (240, 410))
                self.screen.blit(self.home, (125, 400))
                self.screen.blit(self.delete, (5, 5))
                self.screen.blit(self.upload, (40, 5))
                if self.deleted:
                    self.screen.blit(self.deleted_image, (79, 200))
                    if time.time() - self.delete_time > 3:
                        self.deleted = False
                if self.uploading:
                    self.screen.blit(self.uploading_image, (79, 200))
                    if time.time() - self.uploading_time > 6:
                        self.uploading = False
                
            if self.mode == 'capture':
                #Get camera stream
                self.stream = io.BytesIO() # Capture into in-memory stream
                self.camera.capture(self.stream, use_video_port=True, format='raw')
                self.stream.seek(0)
                self.stream.readinto(self.yuv)  # stream -> YUV buffer
                self.stream.close()
                yuv2rgb.convert(self.yuv, self.rgb, 240, 320)
            
                #Create pygame image from screen and blit it
                img = pygame.image.frombuffer(self.rgb[0:(240 * 320 * 3)], (240, 320), 'RGB')
                self.screen.blit(img, (0,0))
            
                #Blit buttons
                self.screen.blit(self.capture, (125, 400))
                self.screen.blit(self.gallery, (20, 415))
                self.screen.blit(self.door, (240, 410))

                if self.no_files:
                    self.screen.blit(self.no_files_image, (79, 200))
                    if time.time() - self.files_time > 3:
                        self.no_files = False
            
            pygame.display.update()
            
            #Handle events
            for event in pygame.event.get():
                if event.type == pygame.MOUSEBUTTONUP:
                    if self.mode == 'gallery':
                        if event.pos[1] < 40 and event.pos[0] < 35:
                            self.deleted = True
                            self.delete_time = time.time()
                            os.remove('/home/pi/Photos/' + self.images[self.current_image])
                            self.current_image = 0
                            self.images = os.listdir('/home/pi/Photos/')
                            if len(self.images) == 0:
                                self.mode = 'capture'
                                self.no_files = True
                                self.files_time = time.time()
                            
                        if event.pos[1] < 40 and event.pos[0] > 35 and event.pos[0] < 75:
                            self.uploading = True
                            self.uploading_time = time.time()
                            cam = Popen(['/home/pi/Dropbox-Uploader/./dropbox_uploader.sh', 'upload', '/home/pi/Photos/' +
                                         self.images[self.current_image], self.images[self.current_image]])
                            
                    if event.pos[1] > 400 and event.pos[1] < 470:
                        if event.pos[0] > 125 and event.pos[0] < 195:
                            if self.mode == 'capture':
                                self.camera.capture('/home/pi/Photos/' + str(self.index) + '.jpg')
                                self.index += 1
                            if self.mode == 'gallery':
                                self.mode = 'capture'
            
                        if event.pos[0] < 70:
                            if self.mode == 'capture':
                                self.mode = 'gallery'
                                self.current_image = 0
                                self.images = os.listdir('/home/pi/Photos/')
                                if len(self.images) == 0:
                                    self.mode = 'capture'
                                    self.no_files = True
                                    self.files_time = time.time()
                                else:
                                    self.image_in_view = pygame.image.load('/home/pi/Photos/' + self.images[self.current_image])
                                
                            if self.mode == 'gallery':
                                self.current_image -= 1
                                if self.current_image == -1:
                                    self.current_image = len(self.images) - 1
                                self.image_in_view = pygame.image.load('/home/pi/Photos/' + self.images[self.current_image])
                                
                        if event.pos[0] > 255:
                            if self.mode == 'capture':
                                print 'exiting...'
                                os.remove('/home/pi/index.dat')
                                new = open('/home/pi/index.dat', 'w+')
                                new.write(str(self.index))
                                new.close()
                                cam = Popen(['sudo', 'python', '/home/pi/zero-phone/main.py'])
                                pygame.quit()
                                sys.exit()


                            if self.mode == 'gallery':
                                if self.current_image == len(self.images) - 1:
                                    self.current_image = 0
                                else:
                                    self.current_image += 1
                                self.image_in_view = pygame.image.load('/home/pi/Photos/' + self.images[self.current_image])
示例#16
0
while(True):
    ev = pygame.event.get()
    for event in ev:
        if event.type == pygame.MOUSEBUTTONUP:
            (mouseX, mouseY) = pygame.mouse.get_pos()
            
            drawTargetRectSize = (mouseX - 10, mouseY - 10, 20, 20)
            drawTargetRect = 1
            
        if event.type == pygame.KEYUP:
            if event.key == pygame.K_RETURN or event.key == pygame.K_ENTER:
                if mouseX > 0 and mouseY > 0:
                    #Exit function
    
    stream = io.BytesIO() # Capture into in-memory stream
    camera.capture(stream, use_video_port=True, format='raw')
    stream.seek(0)
    stream.readinto(yuv)  # stream -> YUV buffer
    stream.close()
    
    yuv2rgb.convert(yuv, rgb, viewFinder[0], viewFinder[1])
    
    img = pygame.image.frombuffer(rgb[0:(viewFinder[0] * viewFinder[1] * 3)], (viewFinder[0], viewFinder[1]), 'RGB')
    
    screen.blit(img, ((viewFinder[0] - img.get_width() ) / 2, (viewFinder[1] - img.get_height()) / 2))
    
    if drawTargetRect == 1:
        pygame.draw.rect(screen, (255,0,0), drawTargetRectSize, 1)
    
    pygame.display.update()
示例#17
0
def main():

    PITFT_BUTTON_1 = 23
    PITFT_BUTTON_2 = 22
    PITFT_BUTTON_3 = 17
    PITFT_BUTTON_4 = 27

    running_on_pi = False

    #
    # Camera Params
    #
    sizeData = [  # Camera parameters for different size settings
        # Full res      Viewfinder  Crop window
        [(2592, 1944), (320, 240), (0.0, 0.0, 0.0, 0.0)]
    ]  # Large

    sizeMode = 0

    # Buffers for viewfinder data
    rgb = bytearray(int(ui.settings.WINDOWWIDTH * ui.settings.WINDOWHEIGHT *
                        3))
    yuv = bytearray(
        int(ui.settings.WINDOWWIDTH * ui.settings.WINDOWHEIGHT * 3 / 2))

    if (os.getenv('FRAMEBUFFER') is not None):
        print("RUNNING ON PI")
        running_on_pi = True
        # Pi Specific Settings
        os.putenv('SDL_VIDEODRIVER', 'fbcon')
        os.putenv('SDL_FBDEV', '/dev/fb1')
        os.putenv('SDL_MOUSEDEV', '/dev/input/touchscreen')
        os.putenv('SDL_MOUSEDRV', 'TSLIB')

        import RPi.GPIO as GPIO
        GPIO.setmode(GPIO.BCM)
        for k in [
                PITFT_BUTTON_1, PITFT_BUTTON_2, PITFT_BUTTON_3, PITFT_BUTTON_4
        ]:
            GPIO.setup(k, GPIO.IN, pull_up_down=GPIO.PUD_UP)

        import io
        import picamera
        import yuv2rgb

        # Init camera and set up default values
        camera = picamera.PiCamera()
        camera.resolution = sizeData[sizeMode][1]
        camera.crop = sizeData[sizeMode][2]
        # Leave raw format at default YUV, don't touch, don't set to RGB!

    global FPSCLOCK, DISPLAYSURF
    pygame.init()
    FPSCLOCK = pygame.time.Clock()

    # Screen Size
    DISPLAYSURF = pygame.display.set_mode(
        (settings.WINDOWWIDTH, settings.WINDOWHEIGHT))

    mousex = 0  # used to store x coordinate of mouse event
    mousey = 0  # used to store y coordinate of mouse event

    if (running_on_pi):
        pygame.mouse.set_visible(False)
    else:
        pygame.display.set_caption('Toulouse')

    # Initalise OS Logic State
    toulouse = ui.state.Toulouse(running_on_pi)
    toulouse.locked = False
    toulouse.load()
    toulouse.load_screen(ui.state.Page.PHOTO_CAPTURE_SCREEN)

    # Security
    passcode_attempt = []

    # Message Display
    message_id = None

    # Image Loading
    SPLASH_TIMEOUT = 1
    splash_start = None

    # Caricature Paramaters
    cusd_queue_id = None
    cusd_queue_id = "nSsRGBCj"

    # Scroll Parameters
    scroll_y_min = 0
    scroll_y = 0
    scroll_y_max = 0

    while True:

        if (toulouse.mode != ui.state.Mode.UNINITIALIZED_MODE):
            toulouse.check_messages()

        if (toulouse.locked and toulouse.page != ui.state.Page.SPLASH_SCREEN):
            toulouse.load_screen(ui.state.Page.PASSCODE_LOCK_SCREEN)

        mouseClicked = False

        if (running_on_pi):
            # Button #1 (Mocked by Q) Back
            # if (not toulouse.locked and GPIO.input(PITFT_BUTTON_1) == False):
            #   toulouse.back()

            # Button #2 (Mocked by W) Messages
            if (not toulouse.locked and GPIO.input(PITFT_BUTTON_2) == False):
                toulouse.load_screen(ui.state.Page.PHOTO_CAPTURE_SCREEN)

            # Button #3 (Mocked by E) Program Selection
            if (not toulouse.locked and GPIO.input(PITFT_BUTTON_3) == False):
                exit(0)

            # Button #4 (Mocked by R) Main Menu
            if (not toulouse.locked and GPIO.input(PITFT_BUTTON_4) == False):
                toulouse.load_screen(ui.state.Page.MAIN_MENU_SCREEN)

        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()
            elif event.type == MOUSEBUTTONDOWN:
                mousex, mousey = event.pos
                if event.button == 4:
                    scroll_y = min(scroll_y + 15, scroll_y_min)
                if event.button == 5:
                    scroll_y = max(scroll_y - 15, scroll_y_max)
                pygame.event.clear(pygame.MOUSEBUTTONDOWN)
            elif event.type == MOUSEMOTION:
                mousex, mousey = event.pos
                pygame.event.clear(pygame.MOUSEMOTION)
            elif event.type == MOUSEBUTTONUP:
                mousex, mousey = event.pos
                if (event.button != 4 and event.button != 5):
                    mouseClicked = True
                pygame.event.clear(pygame.MOUSEBUTTONUP)
            elif event.type == pygame.KEYDOWN:
                # Button #1 (Mocked by Q) Back
                if (not toulouse.locked and event.key == pygame.K_q):
                    toulouse.back()

                # Button #2 (Mocked by W) Messages
                if (not toulouse.locked and event.key == pygame.K_w):
                    toulouse.load_screen(ui.state.Page.MESSAGES_LIST_SCREEN)

                # Button #3 (Mocked by E) Program Selection
                if (not toulouse.locked and event.key == pygame.K_e):
                    toulouse.load_screen(
                        ui.state.Page.PROGRAM_SELECTION_SCREEN)

                # Button #4 (Mocked by R) Main Menu
                if (not toulouse.locked and event.key == pygame.K_r):
                    toulouse.load_screen(ui.state.Page.MAIN_MENU_SCREEN)

        # Window Tree
        if (toulouse.page == ui.state.Page.SPLASH_SCREEN):
            if (not toulouse.loaded_new_state):
                print("----> Displaying Splash Screen")
                splash_start = datetime.now() + timedelta(
                    seconds=SPLASH_TIMEOUT)
                DISPLAYSURF.fill(ui.colours.SCREEN_BG_COLOR)
                img_splash_surf = pygame.image.load(
                    '/home/pi/toulouseos/splash.png').convert_alpha()
                img_splash_rect = img_splash_surf.get_rect()
                img_splash_rect.center = (settings.WINDOWWIDTH / 2,
                                          settings.WINDOWHEIGHT / 2)
                DISPLAYSURF.blit(img_splash_surf, img_splash_rect)

                inetaddr_text_surf = ui.fonts.SF_UI_DISPLAY_HEAVY.render(
                    toulouse.inetaddr, True, ui.colours.WHITE,
                    ui.colours.BLACK)
                inetaddr_text_rect = inetaddr_text_surf.get_rect()
                inetaddr_text_rect.midtop = (settings.WINDOWWIDTH / 2,
                                             settings.WINDOWHEIGHT -
                                             settings.UI_MARGIN_TOP)
                DISPLAYSURF.blit(inetaddr_text_surf, inetaddr_text_rect)

                toulouse.load()
                toulouse.loaded_screen(ui.state.Page.SPLASH_SCREEN)

            # Timer to Passcode Lock
            if (datetime.now() > splash_start):
                toulouse.load_screen(ui.state.Page.PASSCODE_LOCK_SCREEN)
        elif (toulouse.page == ui.state.Page.PASSCODE_LOCK_SCREEN):
            if (not toulouse.loaded_new_state):
                print("----> Displaying Passcode Lock Screen")
                DISPLAYSURF.fill(ui.colours.SCREEN_BG_COLOR)  # Reset Frame

                passcode_title = "Enter Passcode"

                # Draw Buttons Once
                passcode_buttons = []
                buttonx, buttony = PASSCODE_BUTTON_XSTART, PASSCODE_BUTTON_YSTART
                for row in PASSCODE_BUTTON_STRUCTURE:
                    if len(row) == 3:
                        for column in row:
                            if column is not None:
                                passcode_buttons.append(
                                    rounded_button(DISPLAYSURF, column,
                                                   buttonx, buttony))
                            buttonx += PASSCODE_BUTTON_XSIZE + PASSCODE_BUTTON_XGAP
                        buttony += PASSCODE_BUTTON_YSIZE + PASSCODE_BUTTON_YGAP
                    elif len(row) == 1:
                        passcode_buttons.append(
                            rounded_button(DISPLAYSURF,
                                           row[0],
                                           buttonx,
                                           buttony,
                                           width=PASSCODE_BUTTON_XSIZE * 3 +
                                           PASSCODE_BUTTON_XGAP * 2))
                    buttonx = PASSCODE_BUTTON_XSTART
                toulouse.loaded_screen(ui.state.Page.PASSCODE_LOCK_SCREEN)

            # Update Passcode Entry
            if (len(passcode_attempt) > 0):
                # display only most recent digit
                passcode_title = (u"\u2022 " * (len(passcode_attempt) - 1))
                passcode_title += str(passcode_attempt[-1])
            elif (len(passcode_attempt) == 0
                  and passcode_title != "Wrong Passcode"):
                passcode_title = "Enter Passcode"

            # Render Passcode Header
            passcode_text_blackout_rect = pygame.Rect(0, 0,
                                                      settings.WINDOWWIDTH,
                                                      settings.UI_MARGIN_TOP)
            pygame.draw.rect(DISPLAYSURF, ui.colours.SCREEN_BG_COLOR,
                             passcode_text_blackout_rect)
            passcode_text_surf = ui.fonts.SF_UI_DISPLAY_HEAVY.render(
                passcode_title, True, ui.colours.WHITE, ui.colours.BLACK)
            passcode_text_rect = passcode_text_surf.get_rect()
            passcode_text_rect.center = (settings.WINDOWWIDTH / 2,
                                         settings.UI_MARGIN_TOP / 2)
            DISPLAYSURF.blit(passcode_text_surf, passcode_text_rect)

            # Button Logic
            if (mouseClicked):
                for button in passcode_buttons:
                    if button["target"].collidepoint((mousex, mousey)):
                        if (button["value"].isdigit()):
                            passcode_attempt.append(int(button["value"]))
                        elif (button["value"] == "<"):
                            passcode_attempt.pop()
                        elif (button["value"] == "clear"):
                            del passcode_attempt[:]

            # Attempt to Login
            login_attempt = toulouse.login(passcode_attempt)
            if (login_attempt == False):
                passcode_title = "Wrong Passcode"
                del passcode_attempt[:]
            elif (login_attempt == True):
                del passcode_attempt[:]
        elif (toulouse.page == ui.state.Page.MAIN_MENU_SCREEN):
            if (not toulouse.loaded_new_state):
                print("----> Displaying Main Menu Screen")
                DISPLAYSURF.fill(ui.colours.SCREEN_BG_COLOR)

                # Draw Buttons Once
                menu_buttons = []

                cancel_text_surf = ui.fonts.SF_UI_DISPLAY_HEAVY.render(
                    "Cancel", True, ui.colours.WHITE, ui.colours.BLACK)
                cancel_text_rect = cancel_text_surf.get_rect()
                cancel_text_rect.midleft = (settings.UI_MARGIN,
                                            settings.UI_MARGIN_TOP / 2)
                DISPLAYSURF.blit(cancel_text_surf, cancel_text_rect)
                menu_buttons.append({"target": cancel_text_rect, "value": 4})

                for i in range(len(ui.mainmenu.BUTTONS)):
                    menu_buttons.append(
                        ui.mainmenu.rounded_button(
                            DISPLAYSURF, ui.mainmenu.BUTTONS[i],
                            settings.UI_MARGIN,
                            settings.WINDOWHEIGHT - settings.UI_MARGIN_BOTTOM -
                            (ui.mainmenu.BUTTON_YSIZE +
                             ui.mainmenu.BUTTON_YGAP) * (i + 1)))

                toulouse.loaded_screen(ui.state.Page.MAIN_MENU_SCREEN)

            # Button Logic
            if (mouseClicked):
                for button in menu_buttons:
                    if button["target"].collidepoint((mousex, mousey)):
                        if (button["value"] == ui.mainmenu.BUTTON_SHUTDOWN):
                            toulouse.shutdown()
                        if (button["value"] == ui.mainmenu.BUTTON_RESTART):
                            toulouse.restart()
                        if (button["value"] == ui.mainmenu.BUTTON_LOCK):
                            toulouse.lock()
                        if (button["value"] == ui.mainmenu.BUTTON_CANCEL):
                            toulouse.back()
        elif (toulouse.page == ui.state.Page.MANUAL_JOG_CARTESIAN_SCREEN):
            if (not toulouse.loaded_new_state):
                print("----> Displaying Manual Jog (Cartesian) Screen")

                toulouse.loaded_screen(
                    ui.state.Page.MANUAL_JOG_CARTESIAN_SCREEN)

            DISPLAYSURF.fill(ui.colours.SCREEN_BG_COLOR)

            axis_buttons = []

            axis_buttons.append(
                ui.utilities.Header(DISPLAYSURF, toulouse, "Cartesian Jog",
                                    ui.colours.WHITE))

            for i in range(len(ui.jog.AXIS_CARTESIAN)):
                axis_buttons.extend(
                    ui.jog.axis_controller(
                        DISPLAYSURF, toulouse, ui.jog.AXIS_CARTESIAN[i],
                        settings.UI_MARGIN_TOP +
                        (ui.jog.CONTROLLER_YSIZE + ui.jog.CONTROLLER_YGAP) *
                        i))

            if (mouseClicked):
                for button in axis_buttons:
                    if button["target"].collidepoint((mousex, mousey)):
                        if button["value"] == ui.utilities.BUTTON_HEADER:
                            toulouse.load_screen(
                                ui.state.Page.MANUAL_JOG_JOINT_SCREEN)
                            break
                        curr_value = getattr(toulouse, button["action"], 0.00)
                        if button["value"] == ui.jog.BUTTON_EDIT:
                            pass
                        elif button["value"] == ui.jog.BUTTON_ADD:
                            setattr(toulouse, button["action"],
                                    curr_value + button["change"])
                        elif button["value"] == ui.jog.BUTTON_SUBTRACT:
                            setattr(toulouse, button["action"],
                                    curr_value - button["change"])
        elif (toulouse.page == ui.state.Page.MANUAL_JOG_JOINT_SCREEN):
            if (not toulouse.loaded_new_state):
                print("----> Displaying Manual Jog (Joint Angles) Screen")
                toulouse.loaded_screen(ui.state.Page.MANUAL_JOG_JOINT_SCREEN)

            DISPLAYSURF.fill(ui.colours.SCREEN_BG_COLOR)
            axis_buttons = []

            axis_buttons.append(
                ui.utilities.Header(DISPLAYSURF, toulouse, "Joint Jog",
                                    ui.colours.WHITE))

            for i in range(len(ui.jog.AXIS_JOINT)):
                axis_buttons.extend(
                    ui.jog.axis_controller(
                        DISPLAYSURF, toulouse, ui.jog.AXIS_JOINT[i],
                        settings.UI_MARGIN_TOP +
                        (ui.jog.CONTROLLER_YSIZE + ui.jog.CONTROLLER_YGAP) *
                        i))

            if (mouseClicked):
                for button in axis_buttons:
                    if button["target"].collidepoint((mousex, mousey)):
                        if button["value"] == ui.utilities.BUTTON_HEADER:
                            toulouse.load_screen(
                                ui.state.Page.MANUAL_JOG_CARTESIAN_SCREEN)
                            break
                        curr_value = getattr(toulouse, button["action"], 0.00)
                        if button["value"] == ui.jog.BUTTON_EDIT:
                            pass
                        elif button["value"] == ui.jog.BUTTON_ADD:
                            setattr(toulouse, button["action"],
                                    curr_value + button["change"])
                        elif button["value"] == ui.jog.BUTTON_SUBTRACT:
                            setattr(toulouse, button["action"],
                                    curr_value - button["change"])
        elif (toulouse.page == ui.state.Page.PROGRAM_SELECTION_SCREEN):
            if (not toulouse.loaded_new_state):
                print("----> Displaying Program Selection Screen")
                loaded_new_state = 1
                DISPLAYSURF.fill(ui.colours.SCREEN_BG_COLOR)

                # Draw Buttons Once
                program_buttons = []

                ui.utilities.Header(DISPLAYSURF, toulouse, "Programs",
                                    ui.colours.PHOSPHORIC_LIGHT_COLOR)

                for i in range(len(ui.program.BUTTONS)):
                    program_buttons.append(
                        ui.program.rounded_button(
                            DISPLAYSURF, ui.program.BUTTONS[i],
                            settings.UI_MARGIN, settings.UI_MARGIN_TOP +
                            (ui.program.BUTTON_YSIZE + ui.program.BUTTON_YGAP)
                            * i))
                toulouse.loaded_screen(ui.state.Page.PROGRAM_SELECTION_SCREEN)

            # Button Logic
            if (mouseClicked):
                for button in program_buttons:
                    if button["target"].collidepoint((mousex, mousey)):
                        if (button["value"] == ui.program.BUTTON_CARICATURE):
                            toulouse.load_screen(
                                ui.state.Page.PHOTO_CAPTURE_SCREEN)
                        if (button["value"] == ui.program.BUTTON_CURVES):
                            toulouse.load_screen(
                                ui.state.Page.CURVES_SELECTION_SCREEN)
        elif (toulouse.page == ui.state.Page.PHOTO_CAPTURE_SCREEN):
            if (not toulouse.loaded_new_state):
                print("----> Displaying Photo Capture Screen")
                BUTTON_PHOTO_CAPTURE = 1
                BUTTON_CUSD_CLEAR = 2
                toulouse.loaded_screen(ui.state.Page.PHOTO_CAPTURE_SCREEN)

            photo_capture_buttons = []
            # Refresh display
            stream = io.BytesIO()  # Capture into in-memory stream
            camera.capture(stream, use_video_port=True, format='raw')
            stream.seek(0)
            stream.readinto(yuv)  # stream -> YUV buffer
            stream.close()
            yuv2rgb.convert(yuv, rgb, sizeData[sizeMode][1][0],
                            sizeData[sizeMode][1][1])
            img = pygame.image.frombuffer(
                rgb[0:(sizeData[sizeMode][1][0] * sizeData[sizeMode][1][1] *
                       3)], sizeData[sizeMode][1], 'RGB')

            DISPLAYSURF.blit(
                img, ((ui.settings.WINDOWWIDTH - img.get_width()) / 2,
                      (ui.settings.WINDOWHEIGHT - img.get_height()) / 2))

            ui.utilities.Header(DISPLAYSURF,
                                toulouse,
                                "Programs",
                                transparency=True)

            ui.utilities.TransparentRect(
                DISPLAYSURF,
                (0, ui.settings.WINDOWHEIGHT - ui.settings.UI_MARGIN_BOTTOM -
                 56 - ui.settings.UI_MARGIN, ui.settings.WINDOWWIDTH,
                 56 + ui.settings.UI_MARGIN + ui.settings.UI_MARGIN_BOTTOM),
                ui.colours.SCREEN_BG_COLOR)
            button_circ = [
                ui.settings.WINDOWWIDTH / 2,
                ui.settings.WINDOWHEIGHT - ui.settings.UI_MARGIN_BOTTOM - 28,
                56
            ]
            camera_capture = ui.utilities.FilledCircle(DISPLAYSURF,
                                                       button_circ,
                                                       ui.colours.WHITE)
            photo_capture_buttons.append({
                "target": camera_capture,
                "value": BUTTON_PHOTO_CAPTURE
            })
            button_circ[2] = 42
            ui.utilities.FilledCircle(DISPLAYSURF, button_circ,
                                      ui.colours.SCREEN_BG_COLOR)
            button_circ[2] = 38
            ui.utilities.FilledCircle(DISPLAYSURF, button_circ,
                                      ui.colours.WHITE)

            if (cusd_queue_id is not None):
                queue_id_text_surf = ui.fonts.OCRA.render(
                    "CUSD:{id}".format(id=cusd_queue_id), True,
                    ui.colours.WARNING_ORANGE)
                queue_id_text_rect = queue_id_text_surf.get_rect()
                queue_id_text_rect.bottomleft = (settings.UI_MARGIN_LEFT,
                                                 ui.settings.WINDOWHEIGHT -
                                                 ui.settings.UI_MARGIN_BOTTOM)
                DISPLAYSURF.blit(queue_id_text_surf, queue_id_text_rect)
                photo_capture_buttons.append({
                    "target": queue_id_text_rect,
                    "value": BUTTON_CUSD_CLEAR
                })

            if (running_on_pi):
                # Button #1 (Mocked by Q) Back
                if (not toulouse.locked
                        and GPIO.input(PITFT_BUTTON_1) == False):
                    toulouse.process_caricature(camera)

            # Button Logic
            # if (mouseClicked):
            #   for button in photo_capture_buttons:
            #     if button["target"].collidepoint((mousex, mousey)):
            #       if (button["value"] == BUTTON_PHOTO_CAPTURE):
            #         filename = toulouse.get_photos_filename()
            #         print("Taking Picture", filename)
            #         try:
            #           camera.capture(filename, use_video_port=False, format='jpeg', thumbnail=None)
            #           # Set image file ownership to pi user, mode to 644
            #           os.chmod(filename, stat.S_IRUSR | stat.S_IWUSR | stat.S_IRGRP | stat.S_IROTH)
            #         finally:
            #           # Convert to Curves File
            #           # python process.py image1.jpg output1 no
            #       if (button["value"] == BUTTON_CUSD_CLEAR):
            #         cusd_queue_id = None
        elif (toulouse.page == ui.state.Page.CURVES_SELECTION_SCREEN):
            if (not toulouse.loaded_new_state):
                print("----> Displaying Curves Selection Screen")
                # Create Sorted List of Files
                files = toulouse.curve_files()

                # Set Maximum Scroll Y Max
                scroll_y = 0  # reset scroll
                scroll_y_max = -(ui.curvesselection.BUTTON_YSIZE +
                                 ui.curvesselection.BUTTON_YGAP) * len(files)
                scroll_y_max += settings.WINDOWHEIGHT - settings.UI_MARGIN_TOP
                toulouse.loaded_screen(ui.state.Page.CURVES_SELECTION_SCREEN)

            DISPLAYSURF.fill(ui.colours.SCREEN_BG_COLOR)

            files_buttons = []
            for i in range(len(files)):
                files_buttons.append(
                    ui.curvesselection.rounded_button(
                        DISPLAYSURF, files[i], settings.UI_MARGIN,
                        settings.UI_MARGIN_TOP + scroll_y +
                        (ui.curvesselection.BUTTON_YSIZE +
                         ui.curvesselection.BUTTON_YGAP) * i))

            ui.utilities.Header(DISPLAYSURF, toulouse, "Programs",
                                ui.colours.PHOSPHORIC_LIGHT_COLOR)

            # Button Logic
            if (mouseClicked):
                for button in files_buttons:
                    if button["target"].collidepoint((mousex, mousey)):
                        if (button["value"] == ui.curvesselection.BUTTON_FILE):
                            print("      Starting Processing on Curves File:",
                                  button["action"])
                            toulouse.load_program(button["action"])
                            toulouse.load_screen(ui.state.Page.HOME_SCREEN)
        elif (toulouse.page == ui.state.Page.MESSAGES_LIST_SCREEN):
            if (not toulouse.loaded_new_state):
                print("----> Displaying Message List Screen")
                scroll_y = 0  # reset scroll
                toulouse.loaded_screen(ui.state.Page.MESSAGES_LIST_SCREEN)

            DISPLAYSURF.fill(ui.colours.SCREEN_BG_COLOR)

            # Draw Buttons Once
            messages_buttons = []

            if (len(toulouse.messages) > 0):
                # Set Maximum Scroll Y Max
                scroll_y_max = -(ui.messages.BUTTON_YSIZE +
                                 ui.messages.BUTTON_YGAP) * len(
                                     toulouse.messages)
                scroll_y_max += settings.WINDOWHEIGHT - settings.UI_MARGIN_TOP
                scroll_y_max = scroll_y_max if scroll_y_max < 0 else 0

                message_len = len(toulouse.messages)
                for i in range(message_len):
                    toulouse.messages[i]["id"] = i
                    messages_buttons.append(
                        ui.messages.rounded_button(
                            DISPLAYSURF, toulouse.messages[-(i + 1)],
                            settings.UI_MARGIN, settings.UI_MARGIN_TOP +
                            scroll_y + (ui.messages.BUTTON_YSIZE +
                                        ui.messages.BUTTON_YGAP) * (i)))

            ui.utilities.Header(DISPLAYSURF, toulouse, "Messages")
            if (mouseClicked):
                for button in messages_buttons:
                    if button["target"].collidepoint((mousex, mousey)):
                        if button["value"] == ui.messages.BUTTON_LIST:
                            message_id = button["action"]
                            toulouse.load_screen(ui.state.Page.MESSAGE_SCREEN)
        elif (toulouse.page == ui.state.Page.MESSAGE_SCREEN):
            if (not toulouse.loaded_new_state):
                print("----> Displaying Message Screen")
                DISPLAYSURF.fill(ui.colours.SCREEN_BG_COLOR)
                messages_buttons = ui.messages.message_display(
                    DISPLAYSURF, toulouse, toulouse.messages[message_id])
                toulouse.loaded_screen(ui.state.Page.MESSAGE_SCREEN)

            # Button Logic
            if (mouseClicked):
                for button in messages_buttons:
                    if button["target"].collidepoint((mousex, mousey)):
                        if (button["value"] == ui.messages.BUTTON_ACKNOWLEDGE):
                            toulouse.mark_read(message_id)
                            toulouse.load_screen(
                                ui.state.Page.MESSAGES_LIST_SCREEN)
                        elif (button["value"] == ui.messages.BUTTON_CLEAR):
                            toulouse.load_screen(
                                ui.state.Page.MESSAGES_LIST_SCREEN)
        elif (toulouse.page == ui.state.Page.HOME_AXES_SCREEN):
            if (not toulouse.loaded_new_state):
                print("----> Displaying Home Axes Screen")
                homeaxes_buttons = ui.homeaxes.message_display(
                    DISPLAYSURF, toulouse)
                toulouse.loaded_screen(ui.state.Page.HOME_AXES_SCREEN)

            # Button Logic
            if (mouseClicked):
                for button in homeaxes_buttons:
                    if button["target"].collidepoint((mousex, mousey)):
                        if (button["value"] == ui.homeaxes.BUTTON_ACKNOWLEDGE):
                            toulouse.home_axes()
        else:  # Display Home Screen
            if (toulouse.mode == ui.state.Mode.NO_MODE_CHOSEN):
                toulouse.load_screen(ui.state.Page.HOME_AXES_SCREEN)
            if (not toulouse.loaded_new_state):
                print("----> Displaying Home Screen")
                toulouse.loaded_screen(ui.state.Page.HOME_SCREEN)

            DISPLAYSURF.fill(ui.colours.SCREEN_BG_COLOR)

            # Draw Buttons Once
            ui.utilities.Header(DISPLAYSURF, toulouse, "")

            for i in range(len(ui.home.GLANCES)):
                ui.home.glance(
                    DISPLAYSURF, toulouse, ui.home.GLANCES[i],
                    settings.UI_MARGIN_TOP +
                    (ui.home.GLANCE_YSIZE + ui.home.GLANCE_YGAP) * i)

        # Redraw the screen and wait a clock tick.
        pygame.display.update()
        FPSCLOCK.tick(ui.settings.FPS)
示例#18
0
def main(settings = None, boss = True, updater = None, camera_wrapper = None):

    pitft = True
    
    if pitft:
        os.putenv('SDL_VIDEODRIVER', 'fbcon')
        os.putenv('SDL_FBDEV'      , '/dev/fb1')

    def fps(surface):
        milliseconds = clock.tick(fpslimit)        
        pygame_utils.txt(surface, (utils.screen['resolution'][0] - 30, utils.screen['margin']), str(round(clock.get_fps())))
        
    log('[GUI] initing pygame')
    #pygame init
    pygame.init()    

    log('[GUI] inited pygame')
    pygame.mouse.set_visible(False)    
    
    # screen resolution: http://www.purdyelectronics.com/pdf/AND-TFT-25PA.pdf
    #screenSize = (234,160)
    captureSize =   (320,240)
    #captureSize =   (160,120)
    fpslimit    =   24
    # screenSize  =   (pygame.display.Info().current_w,pygame.display.Info().current_h)
    # screenSize  = (((screenSize[0] + 31) // 32) * 32,((screenSize[1] + 15) // 16) * 16,)
    screenSize = utils.screen['resolution']
    
    clock = time.Clock()

    if camera_wrapper == None: 
        log('[error] no camera object')

    # settin up camera   
    camera_wrapper.camera.resolution = captureSize
    camera_wrapper.camera.rotation   = 180
    
    if not pitft:
        camera_wrapper.camera.start_preview()
    
    # Buffers for viewfinder data
    rgb = bytearray(320 * 240 * 3)
    yuv = bytearray(320 * 240 * 3 / 2)
    screen = pygame.display.set_mode((0,0), pygame.FULLSCREEN)
    
    state_stack = []    
         
    
    
    #screen = pygame.display.set_mode(screenSize,0)
    
    
    overlay_renderer = None
    overlay_renderer2 = None
    
    # menu = Menu(root_options)
    
    overlaySize =  (((screenSize[0] + 31) // 32) * 32,((screenSize[1] + 15) // 16) * 16,)
    # overlaySize =  (128,((screenSize[1] + 16) // 16) * 16,)
    
#    log('screenSize ',screenSize, (((screenSize[0] + 31) // 32) * 32, ((screenSize[1] + 15) // 16) * 16,))
        
    
    # GUI State handler
    main_state = MainState.MainState(state_stack, updater, camera_wrapper)
    
    thread.start_new_thread(pygame_utils.watch_trigger, ())
    
    preview = True
    splash = None
    
    while True:
        
        stream = io.BytesIO()        
        camera_wrapper.camera.capture(stream, use_video_port=True, format='raw')
        stream.seek(0)
        stream.readinto(yuv)  # stream -> YUV buffer
        stream.close()
        yuv2rgb.convert(yuv, rgb, captureSize[0], captureSize[1])
        
        if preview:
            img = pygame.image.frombuffer(rgb[0:
                (captureSize[0]* captureSize[1] * 3)],
                captureSize, 'RGB')
        
        # surface_top = pygame.Surface(overlaySize, 0, 24)
        
        screen.blit(img,
            ((320 - img.get_width() ) / 2,
            (240 - img.get_height()) / 2))

        pygame_utils.splash(screen)

        for event in pygame.event.get():             
            if event.type == pygame.QUIT or event.type == pygame.KEYDOWN:
                screen.blit(pygame_utils.shutdown_img, (0,0) )
                pygame.display.update()                        
                camera_wrapper.camera.stop()
                pygame.quit()
                sys.exit()
            if event.type == pygame_utils.TAKE_PICTURE:
                screen.blit(pygame_utils.capturing_img, (0,0) )
                pygame.display.update()                                    
                camera_wrapper.make_photos()                
                updater.sync_camera_settings()
                
            state_stack[0].event(event)
            # if event.type == pygame_utils.CHANGE_DISPLAY_SETTINGS:
                # if event.command == 'alpha':
                #     overlay_renderer.alpha = event.value
                # if event.command == 'readd':
                #     camera_wrapper.camera.remove_overlay(overlay_renderer)
                #     overlaySize = event.screenSize
                #     surface_top = pygame.Surface(overlaySize, 0, 24)                    
                #     overlay_renderer = camera_wrapper.camera.add_overlay(surface_top.get_buffer().raw, layer = 3, size = overlaySize, alpha = 64);
                    
        fps(screen)
        
        state_stack[0].draw(screen)
                           
        if pitft:
            pygame.display.update()
        
        else:
            # if not overlay_renderer:
            #     overlay_renderer = camera_wrapper.camera.add_overlay(surface_top.get_buffer().raw, layer = 3, size = overlaySize, alpha = 0);            
            # else:     
            #     try:    
            #         if overlay_renderer.alpha > 0:                       
            #             overlay_renderer.update(surface_top.get_buffer().raw)
            #     except:
            #         pass
            pass
示例#19
0
      pic_num_file = open('pic_num.txt', 'w')
      pic_num_file.write(str(int(pic_num) + 1))
      pic_num_file.close()
      print 'Took picture ' + pic_num + '.jpg'
      os.remove('pic.txt')
      
   except Exception, f:
      pass

print 'Server Ready'
try:
   while(True):
      take_picture()
      connection, address = serversocket.accept()
      stream = io.BytesIO() # Capture into in-memory stream
      camera.capture(stream, use_video_port=True, format='raw')
      stream.seek(0)
      stream.readinto(yuv)  # stream -> YUV buffer
      stream.close()
      yuv2rgb.convert(yuv, rgb, 480,320)

      connection.sendall(rgb[0:(480 * 320 * 3)])
      time.sleep(0.1)
      connection.close()
except:
   print 'Closing'
   camera.close()
finally:
   print 'closing'
   camera.close()