Esempio n. 1
0
    def __init__(self, size_x, size_y, display_q):
        super(DisplayThread, self).__init__()
        self.display_q = display_q
        self.bus = 0
        self.device = 0
        self.x_max = 128
        self.y_max = 296
        self.size_x = size_x
        self.size_y = size_y

        self.stoprequest = threading.Event()

        self.epd = epd2in9.EPD()
        self.epd.init(self.epd.lut_full_update)
        self.image = Image.new('1', (epd2in9.EPD_HEIGHT, epd2in9.EPD_WIDTH),
                               255)
        self.font = ImageFont.load('terminus_12.pil')
        self.line_height = 16
        #self.font = ImageFont.truetype('terminus.ttf', 12)
        self.draw = ImageDraw.Draw(self.image)
        self.clear_display()
        self.clear_display()
        self.epd.init(self.epd.lut_partial_update)

        self.screen = pyte.Screen(self.size_x, self.size_y)
        self.stream = pyte.Stream(self.screen)
        self.buffer = []
        self.cursor_enabled = False
Esempio n. 2
0
def clearPartial():
    epd = epd2in9.EPD()
    epd.init(epd.lut_partial_update)

    epd.clear_frame_memory(0xFF)
    epd.display_frame()
    epd.clear_frame_memory(0xFF)
    epd.display_frame()
Esempio n. 3
0
def clear_display():
    ws = epd2in9.EPD()
    ws.init(ws.lut_full_update)
    whole_image = Image.new('1', (ws.width, ws.height), 255)
    image_width, image_height = whole_image.size
    draw = ImageDraw.Draw(whole_image)
    draw.rectangle((0, 0, image_width, image_height), fill=255)
    ws.Clear(0xFF)
Esempio n. 4
0
def displayPicture(pictureName):

    epd = epd2in9.EPD()
    epd.init(epd.lut_full_update)

    image = Image.open(pictureName)

    epd.clear_frame_memory(0xFF)
    epd.set_frame_memory(image, 0, 0)
    epd.display_frame()

    epd.delay_ms(2000)

    return
Esempio n. 5
0
def main():
    epd = epd2in9.EPD()
    epd.init(epd.lut_full_update)

    # For simplicity, the arguments are explicit numerical coordinates
    image = Image.new('1', (epd2in9.EPD_WIDTH, epd2in9.EPD_HEIGHT),
                      255)  # 255: clear the frame
    draw = ImageDraw.Draw(image)
    font = ImageFont.truetype(
        '/usr/share/fonts/truetype/freefont/FreeMonoBold.ttf', 16)
    draw.rectangle((0, 10, 128, 34), fill=0)
    draw.text((8, 12), 'Display Ready!', font=font, fill=255)
    draw.text((8, 36), 'e-Paper Demo', font=font, fill=0)
    draw.line((16, 60, 56, 60), fill=0)
    draw.line((56, 60, 56, 110), fill=0)
    draw.line((16, 110, 56, 110), fill=0)
    draw.line((16, 110, 16, 60), fill=0)
    draw.line((16, 60, 56, 110), fill=0)
    draw.line((56, 60, 16, 110), fill=0)
    draw.arc((60, 90, 120, 150), 0, 360, fill=0)
    draw.rectangle((16, 130, 56, 180), fill=0)
    draw.chord((60, 160, 120, 220), 0, 360, fill=0)

    epd.clear_frame_memory(0xFF)
    epd.set_frame_memory(image, 0, 0)
    epd.display_frame()

    epd.delay_ms(2000)

    ##
    # there are 2 memory areas embedded in the e-paper display
    # and once the display is refreshed, the memory area will be auto-toggled,
    # i.e. the next action of SetFrameMemory will set the other memory area
    # therefore you have to set the frame memory twice.
    ##
    epd.clear_frame_memory(0xFF)
    epd.display_frame()
    epd.clear_frame_memory(0xFF)
    epd.display_frame()

    # for partial update
    epd.init(epd.lut_partial_update)
    image = Image.open('source/monocolor.bmp')
    ##
    # there are 2 memory areas embedded in the e-paper display
    # and once the display is refreshed, the memory area will be auto-toggled,
    # i.e. the next action of SetFrameMemory will set the other memory area
    # therefore you have to set the frame memory twice.
    ##
    ''' 
def main():

    # prepare e-ink display
    epd = epd2in9.EPD()
    epd.init(epd.lut_full_update)
    epd.reset()

    # font definitions
    font12Sans = ImageFont.truetype(
        '/usr/share/fonts/truetype/freefont/FreeSans.ttf', 12)
    font24Sans = ImageFont.truetype(
        '/usr/share/fonts/truetype/freefont/FreeSans.ttf', 24)

    # the image to be drawn on the display (horizontal)
    image = Image.new('1', (epd2in9.EPD_HEIGHT, epd2in9.EPD_WIDTH),
                      255)  # 255: clear the frame
    draw = ImageDraw.Draw(image)

    # current date and time
    theTime = time.strftime('%H:%M')
    draw.text((10, 30), theTime, font=font24Sans, fill=0)

    theDate = time.strftime('%d.%m.%Y')
    draw.text((52, 58), theDate, font=font12Sans, fill=0)

    # horizontal line
    draw.line((0, 90, 128, 90), fill=0)

    draw.rectangle((0, 0, 10, 10), fill=0)  # upper left corner
    draw.rectangle((286, 0, 296, 10), fill=0)  # upper right corner
    draw.rectangle((0, 118, 10, 128), fill=0)  # lower left corner
    draw.rectangle((282, 118, 292, 128), fill=0)  # lower right corner

    # circles
    draw.chord((130, 10, 150, 30), 0, 360, fill=0)
    draw.chord((150, 20, 180, 50), 0, 360, fill=0)
    draw.chord((200, 30, 260, 90), 0, 360, fill=0)

    # update the display
    epd.clear_frame_memory(0xFF)
    # rotate the image by 90 degrees
    epd.set_frame_memory(image.rotate(90), 0,
                         0)  # upper left corner coordinates
    epd.display_frame()

    epd.delay_ms(2000)
Esempio n. 7
0
def main():
    epd = epd2in9.EPD()
    epd.init(epd.lut_full_update)

    # Clear display
    image = Image.new('1', (epd2in9.EPD_WIDTH, epd2in9.EPD_HEIGHT),
                      255)  # 255: clear the frame
    draw = ImageDraw.Draw(image)

    # Create new image with some text
    font = ImageFont.truetype(
        '/usr/share/fonts/truetype/freefont/FreeMonoBold.ttf', 16)

    draw.text((0, 0), 'RENI', font=font, fill=0)
    draw.text((0, 20), time.strftime('%d/%m/%Y'), font=font, fill=0)

    # Show new created image rotated by 90 degrees
    img = image  #.rotate(90,expand=True)
    ##
    # there are 2 memory areas embedded in the e-paper display
    # and once the display is refreshed, the memory area will be auto-toggled,
    # i.e. the next action of SetFrameMemory will set the other memory area
    # therefore you have to set the frame memory twice.
    ##
    epd.clear_frame_memory(0xFF)
    epd.display_frame()
    epd.clear_frame_memory(0xFF)
    epd.display_frame()

    # for partial update
    epd.init(epd.lut_partial_update)
    # img = Image.open('monocolor.bmp')
    ##
    # there are 2 memory areas embedded in the e-paper display
    # and once the display is refreshed, the memory area will be auto-toggled,
    # i.e. the next action of SetFrameMemory will set the other memory area
    # therefore you have to set the frame memory twice.
    ##
    epd.set_frame_memory(img, 0, 0)
    epd.display_frame()
    epd.set_frame_memory(img, 0, 0)
    epd.display_frame()
Esempio n. 8
0
def countDownFrom(number):
    global responseWasSent

    clearPartial()
    epd = epd2in9.EPD()

    time_image = Image.new('1', (100, 100), 255)  # 255: clear the frame
    draw = ImageDraw.Draw(time_image)
    font = ImageFont.truetype('/usr/share/fonts/truetype/freefont/FreeMonoBold.ttf', 56)
    image_width, image_height = time_image.size

    counter = number
    while (counter >= 0 and (not responseWasSent)):
        draw.rectangle((0, 0, image_width, image_height), fill = 255)
        draw.text((0, 0), '0{0}'.format(str(counter)), font = font, fill = 0)
        epd.set_frame_memory(time_image.rotate(270), 0, 120)
        epd.display_frame()

        counter = counter - 1
        time.sleep(2)
def main():

    epd = epd2in9.EPD()
    epd.init(epd.lut_full_update)
    image = Image.new('1', (epd2in9.EPD_HEIGHT, epd2in9.EPD_WIDTH), 255)
    draw = ImageDraw.Draw(image)
    for i in range(0, numberofcycles):

        draw.rectangle((0, 0, epd2in9.EPD_HEIGHT, epd2in9.EPD_WIDTH),
                       fill=COLORED)
        epd.clear_frame_memory(0xFF)
        epd.set_frame_memory(image.rotate(270, expand=True), 0, 0)
        epd.display_frame()
        time.sleep(1)

        draw.rectangle((0, 0, epd2in9.EPD_HEIGHT, epd2in9.EPD_WIDTH),
                       fill=UNCOLORED)
        epd.clear_frame_memory(0xFF)
        epd.set_frame_memory(image.rotate(270, expand=True), 0, 0)
        epd.display_frame()
        time.sleep(1)
Esempio n. 10
0
def get_epd2in9():
    return epd2in9.EPD()
Esempio n. 11
0
def trainNS(name,test,cside,start,canvas, device,font, fontT):
    print ("in the function") #to debug
    from time import time as getsecs
    from time import sleep
    #%%#####################################################################%%#
    #-------------------------------DEFINITIONS-------------------------------#
    ###########################################################################
    ##** LOGFILE **##
    print ("after import")
    logname = 'subjs/'+name+'/logs/'+name+'_test_'+test+'.csv'
    time = (datetime.datetime.now()-start).total_seconds()                                    
    date = str(datetime.datetime.now())
    with open(logname,'w') as log:
        log.write('datetime,time,event\n')                                     
        log.write(date+','+str(time)+',TestStart\n')    
    print ("after logfile")
    
    #start the video
    cam = picamera.PiCamera()
    cam.resolution = (1296,972)
    cam.framerate = 5
    cam.start_recording('subjs/'+name+'/video/'+name+'_test_'+test+'.h264')

    epd = epd2in9.EPD()
    epd.init(epd.lut_partial_update)
    image = Image.open('screenImages/W.bmp') 
    epd.set_frame_memory(image, 0, 0)
    epd.display_frame()
    #%%#####################################################################%%#
    #------------------------------STARTING PROGRAM---------------------------#
    #
    #definition of state variables
    c=0
    w=0                                                                       #
    killing = False
    Cpressed = False
    Wpressed = False

    pos = 0  #current motor position                                          #
    delivering = False                                                        #
    dropPresent = False                                                       #
    stepsnum = 33 #number of steps for a drop
    #                                                                         #
    #-------------------------------------------------------------------------#
    ###########################################################################
    
    ###################################################################
    #-|-|-|-|-|-|-|-|-PRIME SCREEN AND BUTTONS|-|-|-|-|-|-|-|-|-|-|-|-#
    #                                                                 #
    #make sure the screen is white
    W = Image.open('screenImages/W.bmp')
    B = Image.open('screenImages/B.bmp')
    if cside == 'left':
        photoCORRECT = pin.photoL
        photoWRONG = pin.photoR
    else:
        photoCORRECT = pin.photoR
        photoWRONG = pin.photoL
    epd.set_frame_memory(B, 0, 0)
    epd.display_frame()
    epd.set_frame_memory(B, 0, 0)
    epd.display_frame()        
    epd.set_frame_memory(W, 0, 0)
    epd.display_frame()
    epd.set_frame_memory(W, 0, 0)
    epd.display_frame()

    #                                                                 #
    #-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-#
    
    #%%########################################################################
    #--------------------------------MAIN LOOP--------------------------------#
    while (True):
        now = getsecs()
        #%%/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/%%#
        #-------------------------FOR CORRECT RESISTOR------------------------#
        #                                                                     #
        if not Cpressed: #if currently the correct button was not being pressed
            if GPIO.input(photoCORRECT): #but now it is
                print ("Cpressed")
                Cpressed = True #change state
                #logging                                                  #
                time = (datetime.datetime.now()-start).total_seconds()    #
                date = str(datetime.datetime.now())                       #
                with open(logname,'a') as log:
                    log.write(date+','+str(time)+',Cpressed\n')           #
                    c+=1
                    #   #   #   #   #   #   #   #   #   #   #   #   #   #     #
                    #          correct button has become pressed        #     #
                    #                                                   #     #
                    if not delivering and not dropPresent:              #     #
                        delivering = True # delivering state            #     #
                        #deliver the drop                               #     #
                        deliverer=Thread(name='Perist',target=drop.stepmove,  #
                                    args=(pin.stp,pin.clk,0,stepsnum,pos))    # 
                        deliverer.start() # deliver a drop              #     #
                        pos = drop.postrack(stepsnum,pos)               #     #
                    #                       end                         #     #                    
                    #   #   #   #   #   #   #   #   #   #   #   #   #   #     #                    
                   
        if Cpressed: #if is being pressed                                     #
           if not GPIO.input(photoCORRECT): #but then is not
                print ("Crelease")
                Cpressed=False
                #logging                                                      #
                time = (datetime.datetime.now()-start).total_seconds()        #
                date = str(datetime.datetime.now())                           #
                with open(logname,'a') as log:
                    log.write(date+','+str(time)+',Crelease\n')               #
                waitforRetract = getsecs() #start waiting for retraction      #                        
        #                                                                     #
        #---------------------------------------------------------------------#
        #/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/#
        
        
        #%%/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/%%#
        #--------------------------FOR WRONG RESISTOR-------------------------#
        #                                                                     #
        #if the wrong is pressed you need to do nothing but remove the drop if is currently present
        if not Wpressed:                                                      #
            if GPIO.input(photoWRONG):                                        #
                Wpressed=True                                                 #
                print ("Wpressed")                                            #
                time = (datetime.datetime.now()-start).total_seconds()        #
                date = str(datetime.datetime.now())                           #
                with open(logname,'a') as log:                                #
                    log.write(date+','+str(time)+',Wpressed\n')               #
                w+=1
                #   #   #   #   #   #   #   #   #   #   #   #   #   #         #
                #           wrong button has become pressed         #         #
                #                                                   #         #
                if dropPresent: #if drop is present, remove
                    retracter=Thread(name='suck',target=drop.dcmove,args=(pin.dc,3))
                    retracter.start()                                         #
                    dropPresent = False                                       #
                    #logging                                                  #
                    time = (datetime.datetime.now()-start).total_seconds()    #
                    date = str(datetime.datetime.now())                       #
                    with open(logname,'a') as log:
                        log.write(date+','+str(time)+',DropRetract\n')        #
                #                                                   #         #                    
                #                       end                         #         #
                #   #   #   #   #   #   #   #   #   #   #   #   #   #         #
        if Wpressed: #if is being pressed                                     #
            if not GPIO.input(photoWRONG): #and then is not
                Wpressed=False   #change state
                print ("Wrelease")                                        #
                #logging                                                  #
                time = (datetime.datetime.now()-start).total_seconds()    #
                date = str(datetime.datetime.now())                       #
                with open(logname,'a') as log:
                    log.write(date+','+str(time)+',Wrelease\n')           #
                    
        #                                                                     #
        #---------------------------------------------------------------------#
        #/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/#
        
        
        #%%=================================================================%%#
        #--------------------if I am delivering the drop----------------------#
        #                                                                     #        
        if delivering:                                                        #
            if not deliverer.isAlive(): #when i have finished delivering      #
                print ("delivered")
                #logging                                                      #
                time = (datetime.datetime.now()-start).total_seconds()        #
                date = str(datetime.datetime.now())                           #
                with open(logname,'a') as log:
                    log.write(date+','+str(time)+',DropDeliv\n')              #
                dropPresent = True                                            #
                delivering = False                                            #
                waitforRetract = getsecs() #start waiting for retraction      #
        #                                                                     #
        #---------------------------------------------------------------------#
        #=====================================================================#
                
        
        #%%*****************************************************************%%#
        #------------------------if the drop is present-----------------------#
        #                                                                     #
        if dropPresent:                                                       #
            now = getsecs() #now time                                         #
            nodrank = now-waitforRetract >= 30                                #
            if nodrank and not Cpressed: #if time is over                     #
                retracter=Thread(name='suck',target=drop.dcmove,              #
                                 args=(pin.dc,3))                             #
                retracter.start()                                             #
                dropPresent = False
                #logging                                                      #
                time = (datetime.datetime.now()-start).total_seconds()        #
                date = str(datetime.datetime.now())                           #
                with open(logname,'a') as log:
                    log.write(date+','+str(time)+',DropRetract\n')            #
        #                                                                     #
        #---------------------------------------------------------------------#        
        #*********************************************************************#
        #see habituation file for an explanation of the following lines. they control the turning off routine
        if not killing:
            elapsed = str(datetime.datetime.now()-start)
            elapsed = elapsed.split('.')[0]
            with canvas(device) as draw:
                draw.text((30,0), 'testing', font=fontT, fill="white")
                draw.text((23,48), str(elapsed), font=font, fill="white")
                draw.text((23,24), 'c: '+str(c)+' w: '+str(w),font=font, fill="white")
            if not GPIO.input(pin.ok):
                killing=True
                waittoclose = getsecs()
                with canvas(device) as draw:
                    draw.text((30,0), 'testing', font=fontT, fill="white")
                    draw.text((0,26), 'press again to quit', font=font, fill="white")
                    sleep(0.5)
        if killing:
            if getsecs()-waittoclose<15:
                if not GPIO.input(pin.ok):
                    time = (datetime.datetime.now()-start).total_seconds()                                    
                    date = str(datetime.datetime.now())      
                    with open(logname,'a') as log:
                        log.write(date+','+str(time)+',TestOver\n')                 
                    cam.stop_recording()
                    cam.close()
                    with canvas(device) as draw:
                        draw.text((30,0), 'testing', font=fontT, fill="white")
                        draw.text((0,26), 'cleanup...', font=font, fill="white")
                        draw.text((0,42), 'do not unplug', font=font, fill="white")
                    sleep(5)
                    break
            else:
                killing=False

    with canvas(device) as draw:
        draw.text((0,26), 'rebooting', font=font, fill="white")
        draw.text((0,42), 'do not unplug', font=font, fill="white")
    os.system("sudo reboot")
Esempio n. 12
0
def habit(name, test, start, canvas, device, font, fontT):
    from time import time as getsecs
    from time import sleep
    import picamera

    #%%#####################################################################%%#
    #-------------------------------DEFINITIONS-------------------------------#
    ###########################################################################
    ##** LOGFILE **##
    logname = 'subjs/' + name + '/logs/' + name + '_habitScreen_' + test + '.csv'
    time = (datetime.datetime.now() - start).total_seconds()
    date = str(datetime.datetime.now())
    with open(logname, 'w') as log:
        log.write('datetime,time,event\n')
        log.write(date + ',' + str(time) + ',TestStart\n')

    #make sure the back display is white
    epd = epd2in9.EPD()
    epd.init(epd.lut_full_update)
    image = Image.open('screenImages/W.bmp')
    epd.set_frame_memory(image, 0, 0)
    epd.display_frame()

    #%%#####################################################################%%#
    #------------------------------STARTING PROGRAM---------------------------#
    #                                                                         #
    #State variables
    killing = False  #
    delivering = False  #
    dropPresent = False  #
    waitfordeliver = datetime.datetime.now(
    )  #count seconds until next delivery of drop

    #record with the piCamera
    cam = picamera.PiCamera()
    cam.resolution = (1296, 972)
    cam.framerate = 5
    cam.start_recording('subjs/' + name + '/video/' + name + '_habitScreen_' +
                        test + '.h264')

    #                                                                         #
    #-------------------------------------------------------------------------#
    ###########################################################################

    #pick a random time interval to wait before giving the drop.
    timetowait = random.sample(range(45, 91), 1)[0]
    #%%########################################################################
    #--------------------------------MAIN LOOP--------------------------------#
    pos = 0
    while (True):
        #%%/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/%%#
        #-------------------------FOR DELIVERING DROP-------------------------#
        #                                                                     #
        thismoment = datetime.datetime.now()  #
        waited = thismoment - waitfordeliver  #how much have I waited?

        # if I have waited more than timetowait and there is no drop nor i am delivering one
        if waited.total_seconds() >= timetowait and (not dropPresent
                                                     or not delivering):
            delivering = True  # delivering state                              #
            #logging                                                          #
            time = (datetime.datetime.now() - start).total_seconds()  #
            date = str(datetime.datetime.now())  #
            deliverer = Thread(
                name='Perist',
                target=drop.stepmove,  #
                args=(pin.stp, pin.clk, 0, steps_in_one_drop, pos))  #
            deliverer.start(
            )  # deliver a drop                                #
            pos = drop.postrack(steps_in_one_drop, pos)
            waitfordeliver = datetime.datetime.now(
            )  #restart waiting         #
        #                                                                     #
        #/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/#

        #%%=================================================================%%#
        #--------------------if I am delivering the drop----------------------#
        #                                                                     #
        if delivering:  #
            if not deliverer.isAlive(
            ):  #when i have finished delivering      #
                print('over')
                delivering = False
                #logging                                                      #
                time = (datetime.datetime.now() - start).total_seconds()  #
                date = str(datetime.datetime.now())
                with open(logname, 'a') as log:  #
                    log.write(date + ',' + str(time) + ',DropDeliv\n')  #
                dropPresent = True  #
                waitforRetract = getsecs(
                )  #start waiting for retraction      #
        #                                                                     #
        #---------------------------------------------------------------------#
        #=====================================================================#

        #%%*****************************************************************%%#
        #------------------------if the drop is present-----------------------#
        #                                                                     #
        if dropPresent:  #
            now = getsecs(
            )  #now time                                         #
            nodrank = now - waitforRetract >= 35
            if nodrank:  #if time is over
                #turn on dc motor in a new thread
                retracter = Thread(
                    name='suck',
                    target=drop.dcmove,  #
                    args=(pin.dc, 3))  #
                retracter.start()  #
                dropPresent = False  #
                #logging                                                      #
                time = (datetime.datetime.now() - start).total_seconds()  #
                date = str(datetime.datetime.now())
                with open(logname, 'a') as log:  #
                    log.write(date + ',' + str(time) + ',DropRetract\n')  #
                timetowait = random.sample(range(45, 91), 1)[0]

                waitfordeliver = datetime.datetime.now()  #

        #                                                                     #
        #---------------------------------------------------------------------#
        #*********************************************************************#

        if not killing:  #killing keeps track of the button presses. if I am not killing the program:
            elapsed = str(datetime.datetime.now() - start)  #count time
            elapsed = elapsed.split('.')[0]
            with canvas(device) as draw:  #show on the screen elapsed time
                draw.text((0, 0),
                          name + '_habitS_' + test,
                          font=fontT,
                          fill="white")
                draw.text((23, 24), str(elapsed), font=font, fill="white")
            if not GPIO.input(
                    pin.ok):  #check if I am pressing the rotary encoder
                killing = True  #if so, it means I am killinkg
                waittoclose = getsecs(
                )  #start waiting and check if the user press again
                with canvas(device) as draw:
                    draw.text((0, 0),
                              name + '_habitS_' + test,
                              font=fontT,
                              fill="white")
                    draw.text((0, 26),
                              'press again to quit',
                              font=font,
                              fill="white")
                    sleep(0.5)
        if killing:  #if I have pressed once
            if getsecs() - waittoclose < 15:  #for 15 seconds
                if not GPIO.input(pin.ok):  #if I press again, save
                    time = (datetime.datetime.now() - start).total_seconds()
                    date = str(datetime.datetime.now())
                    with open(logname, 'a') as log:
                        log.write(date + ',' + str(time) + ',TestOver\n')
                    cam.stop_recording()
                    cam.close()
                    with canvas(device) as draw:
                        draw.text((0, 0),
                                  name + '_habitS_' + test,
                                  font=fontT,
                                  fill="white")
                        draw.text((0, 26),
                                  'cleanup...',
                                  font=font,
                                  fill="white")
                        draw.text((0, 42),
                                  'do not unplug',
                                  font=font,
                                  fill="white")
                    sleep(5)
                    break  #terminate while loop
            else:  #if 15 seconds elapse
                killing = False  #exit from killing
    with canvas(device) as draw:  #turn off
        draw.text((0, 26), 'rebooting', font=font, fill="white")
        draw.text((0, 42), 'do not unplug', font=font, fill="white")
    os.system("sudo reboot")
Esempio n. 13
0
def display():
    owrid = {
        200: 'O',  # thunderstorm with light rain
        201: 'O',  # thunderstorm with rain
        202: 'O',  # thunderstorm with heavy rain
        210: 'O',  # light thunderstorm
        211: 'O',  # thunderstorm
        212: 'O',  # heavy thunderstorm
        221: 'O',  # ragged thunderstorm
        230: 'O',  # thunderstorm with light drizzle
        231: 'O',  # thunderstorm with drizzle
        232: 'O',  # thunderstorm with heavy drizzle
        300: 'X',  # light intensity drizzle
        301: 'X',  # drizzle
        302: 'X',  # heavy intensity drizzle
        310: 'X',  # light intensity drizzle rain
        311: 'X',  # drizzle rain
        312: 'X',  # heavy intensity drizzle rain
        313: 'X',  # shower rain and drizzle
        314: 'X',  # heavy shower rain and drizzle
        321: 'X',  # shower drizzle
        500: 'Q',  # light rain
        501: 'R',  # moderate rain
        502: 'R',  # heavy intensity rain
        503: 'R',  # very heavy rain
        504: 'R',  # extreme rain
        511: 'W',  # freezing rain
        520: 'X',  # light intensity shower rain
        521: 'X',  # shower rain
        522: 'X',  # heavy intensity shower rain
        531: 'X',  # ragged shower rain
        600: 'W',  # light snow
        601: 'W',  # snow
        602: 'W',  # heavy snow
        611: 'W',  # sleet
        612: 'W',  # shower sleet
        615: 'W',  # light rain and snow
        616: 'W',  # rain and snow
        620: 'W',  # light shower snow
        621: 'W',  # shower snow
        622: 'W',  # heavy shower snow
        701: 'M',  # mist
        711: 'M',  # smoke
        721: 'M',  # haze
        731: 'M',  # sand, dust whirls
        741: 'M',  # fog
        751: 'M',  # sand
        761: 'M',  # dust
        762: 'M',  # volcanic ash
        771: 'M',  # squalls
        781: 'M',  # tornado
        800: 'B',  # clear sky	 'B'
        801: 'H',  # few clouds	 'H'
        802: 'N',  # scattered clouds
        803: 'Y',  # broken clouds
        804: 'Y'  # overcast clouds
        #    900	tornado
        #    901	tropical storm
        #    902	hurricane
        #    903	cold
        #    904	hot
        #    905	windy
        #    906	hail
        #    951	calm
        #    952	light breeze
        #    953	gentle breeze
        #    954	moderate breeze
        #    955	fresh breeze
        #    956	strong breeze
        #    957	high wind, near gale
        #    958	gale
        #    959	severe gale
        #    960	storm
        #    961	violent storm
        #    962	hurricane
    }
    owridnight = {
        800: 'C',  # clear sky	 'B'
        801: 'I'  # few clouds	 'H'
    }
    LANG = locale.getdefaultlocale()
    locale.setlocale(locale.LC_TIME, LANG)
    clear_display()
    clear_display()
    wcondition, wtemp, wpressure, whum, wwindspeed, wclouds, wtime, wsunrise, wsunset, owrtime = owr_update(
    )
    prom = prometheus.my_prometheus(promhost, promport, promdssl)
    prom.prom_query("")
    promtemp = float(prom.lasttemp)
    wfont = ImageFont.truetype(wfontfile, 48)
    wfontsmall = ImageFont.truetype(wfontsmallfile, 24)
    font = ImageFont.truetype(fontfile, 48)
    fontmedium = ImageFont.truetype(fontmediumfile, 40)
    fontvsmall = ImageFont.truetype(fontvsmallfile, 13)
    tchannel = 'unbekannt.bmp'
    tstartdate = ''
    tstarttime = ''
    ttext = ''
    wsc = epdconfig.RaspberryPi()
    ws = epd2in9.EPD()
    ws.init(ws.lut_partial_update)
    whole_image = Image.new('1', (ws.width, ws.height), 255)
    draw = ImageDraw.Draw(whole_image)
    image_width, image_height = whole_image.size
    forecast = owr_forecast()
    clearrunningtime = time.time()
    refreshrunningtime = time.time()
    while (True):
        # read new temperature after 15min
        if time.time() - refreshrunningtime > 900:
            wcondition, wtemp, wpressure, whum, wwindspeed, wclouds, wtime, wsunrise, wsunset, owrtime = owr_update(
            )
            prom.prom_query("")
            promtemp = float(prom.lasttemp)
            refreshrunningtime = time.time()
        #clear screen after 1h
        if time.time() - clearrunningtime > 3600:
            clear_display()
            ws.init(ws.lut_partial_update)
            clearrunningtime = time.time()
        # whole image blank
        draw.rectangle((0, 0, image_width, image_height), fill=255)
        # draw 3 separating lines
        draw.line([(0, 74), (196, 74)], fill=0)
        draw.line([(0, 148), (196, 148)], fill=0)
        draw.line([(0, 222), (196, 222)], fill=0)
        # draw time
        draw.text((3, 7), time.strftime('%H:%M'), font=font, fill=0)
        # draw actual weather
        # separate night only for supporting conditions
        if (799 < wcondition < 802):
            if (time.strftime('%d') == time.strftime('%d',
                                                     time.localtime(wtime))):
                if (wsunrise < time.time() < wsunset):
                    draw.text((3, 79), owrid[wcondition], font=wfont, fill=0)
                else:
                    draw.text((3, 79),
                              owridnight[wcondition],
                              font=wfont,
                              fill=0)
            else:
                draw.text((3, 79), owridnight[wcondition], font=wfont, fill=0)
        else:
            draw.text((3, 79), owrid[wcondition], font=wfont, fill=0)
        if (round(promtemp) < 0):
            draw.text((58, 85), str(round(promtemp)), font=fontmedium, fill=0)
        else:
            draw.text((70, 85), str(round(promtemp)), font=fontmedium, fill=0)
        if (-10 < wtemp < 10):
            draw.text((90, 85), '*', font=wfontsmall, fill=0)
        else:
            draw.text((108, 85), '*', font=wfontsmall, fill=0)
        draw.text((14, 131),
                  time.strftime('%H:%M - %d.%m.%y', time.localtime(wtime)),
                  font=fontvsmall,
                  fill=0)
        # check if forecast is older than 30min
        if time.time() - forecast.owrtime > 1800:
            forecast = owr_forecast()
        # draw forecast curve
        x = 3
        high = -100
        low = 100
        for i in range(0, forecast.count):
            forecast.forecast(i)
            if forecast.wtemp < low:
                low = int(round(forecast.wtemp))
            if forecast.wtemp > high:
                high = int(round(forecast.wtemp))
        scala = 60 / (high - low)
        draw.text((3, 150), str(high), font=fontvsmall, fill=0)
        draw.text((3, 210), str(low), font=fontvsmall, fill=0)
        for i in range(0, forecast.count):
            if i < forecast.count - 1:
                forecast.forecast(i)
                first = forecast.wtemp
                forecast.forecast(i + 1)
                second = forecast.wtemp
                draw.line([(x, int(round(150 + ((high - first) * scala)))),
                           (x + 3, int(round(150 +
                                             ((high - second) * scala))))],
                          fill=0)
            x = x + 3
        # vdr next timer
        try:
            timer = svdr.svdr(svdrhost, 6419, 10)
            timer.send("lstt")
            timer.get_next_timer()
            tchannel = timer.nexttimer.channel
            tstartdate = timer.nexttimer.start.strftime('%a. %d.%m.')
            tstarttime = timer.nexttimer.start.strftime('%H:%M')
            ttext = timer.nexttimer.text
            timer.close_connection
        except:
            pass
        logo = Image.open(tchannel)
        logo = logo.convert('1')
        draw.text((60, 235), tstartdate, font=fontvsmall, fill=0)
        draw.text((72, 255), tstarttime, font=fontvsmall, fill=0)
        draw.text((3, 278), ttext, font=fontvsmall, fill=0)
        # push drawing into memory and show it
        ws.display(ws.getbuffer(whole_image))
        wsc.delay_ms(10000)
Esempio n. 14
0
#!/usr/bin/python
# -*- coding:utf-8 -*-
import sys
sys.path.append(r'../lib')

import epd2in9
import epdconfig
import time
from PIL import Image, ImageDraw, ImageFont
import traceback

try:
    print("epd2in9 Demo")

    epd = epd2in9.EPD()
    print("init and Clear")
    epd.init(epd.lut_full_update)
    epd.Clear(0xFF)

    font24 = ImageFont.truetype('../lib/Font.ttc', 24)
    font18 = ImageFont.truetype('../lib/Font.ttc', 18)

    # Drawing on the Horizontal image
    print("1.Drawing on the Horizontal image...")
    Himage = Image.new('1', (epd.height, epd.width),
                       255)  # 255: clear the frame
    draw = ImageDraw.Draw(Himage)
    draw.text((10, 0), 'hello world', font=font24, fill=0)
    draw.text((10, 20), '2.9inch e-Paper', font=font24, fill=0)
    draw.text((150, 0), u'微雪电子', font=font24, fill=0)
    draw.line((20, 50, 70, 100), fill=0)
Esempio n. 15
0
def main():

    # main_img is used as screen buffer, all image composing/drawing is done in PIL,
    # the main_img is then copied to the display (drawing on the disp itself is no fun)
    # main_img = Image.new("1", (epd2in9.EPD_WIDTH, epd2in9.EPD_HEIGHT))
    # draw = ImageDraw.Draw(main_img)

    # fonts for drawing within PIL
    andale_ttf_small = ImageFont.truetype(
        "source/fonts/andale_mono/AndaleMono.ttf", 16)
    andale_ttf_large = ImageFont.truetype(
        "source/fonts/andale_mono/AndaleMono.ttf", 26)

    epd = epd2in9.EPD()
    epd.init(epd.lut_full_update)

    # For simplicity, the arguments are explicit numerical coordinates
    image = Image.new('1', (epd2in9.EPD_WIDTH, epd2in9.EPD_HEIGHT),
                      255)  # 255: clear the frame
    draw = ImageDraw.Draw(image)

    # perform initial setup of display and GPIO
    button_logic.setup_gpio(change_state_pin, trigger_pin, yellow_led,
                            blue_led, green_led)

    # announce that we're ready
    GPIO.output(green_led, True)

    # FIXME: draw to epaper display
    default.main()

    while True:
        starttime = time.time()

        state_button = GPIO.input(change_state_pin)
        trigger_button = GPIO.input(trigger_pin)

        if state_button == False:
            button_logic.change_state(yellow_led, blue_led, green_led)
            print "Button press!"
            time.sleep(0.2)

        elif trigger_button == False:
            text, pos_x, pos_y = generate_sentence(font=andale_ttf_small)

            # create binary image filled with white
            base_image = Image.new("1",
                                   size=(epd2in9.EPD_WIDTH,
                                         epd2in9.EPD_HEIGHT),
                                   color=255)

            # create the text image
            text_image = Image.new('1',
                                   (epd2in9.EPD_HEIGHT, epd2in9.EPD_WIDTH))
            # draw the text and rotate it -90 degrees so that it fits the portait orientation
            text_draw_buffer = ImageDraw.Draw(text_image)
            text_draw_buffer.text((pos_x, pos_y),
                                  text,
                                  font=andale_ttf_small,
                                  fill=255)
            text_image = text_image.rotate(270, expand=1)

            result = ImageChops.multiply(text_image, base_image)
            result.save("result.png")

            epd.clear_frame_memory(0xFF)
            epd.set_frame_memory(result, 0, 0)
            epd.display_frame()

            epd.delay_ms(2000)
Esempio n. 16
0
def main():
    epd = epd2in9.EPD()
    epd.init(epd.lut_full_update)

    bw_down = 0
    i = 0

    while bw_down < lower_limit:
        i += 1
        if print_messages:
            print("Bandwidth below limit or first iteration, Iteration %d" %
                  (i))
        if i > max_iterations:
            # reset
            GPIO.output(RELAIS_1, GPIO.LOW)
            if print_messages:
                print('kill em all')
            time.sleep(5)
            GPIO.output(RELAIS_1, GPIO.HIGH)
            time.sleep(60)
            post_request({VARIABLE: 0.0, VARIABLE_2: 2.0})
            red_LED_on(False)
            break
        if print_messages:
            print("Speedtest started")
        try:
            blue_LED_on(True)

            #SIMULATE
            # bw_down = 18780752.1644
            # bw_up = 4100042.51876
            # ping = 33.941

            #TEST
            s = speedtest.Speedtest()
            s.get_best_server()
            bw_down = s.download()
            bw_up = s.upload()
            results_dict = s.results.dict()
            ping = (results_dict['ping'])

            blue_LED_on(False)
        except:
            bw_down = 0
            bw_up = 0
            ping = 0
            blue_LED_on(False)
            if print_messages:
                print("Speedtest failed")
        current_time = time.strftime("%H:%M:%S, %d.%m.%Y")
        if print_messages:
            print("Download: %d, Upload: %d, Ping: %d" %
                  (bw_down, bw_up, ping))
        if bw_down < lower_limit:
            red_LED_on(True)
            if print_messages:
                print("try again in 10sec")
            time.sleep(10)
        else:
            red_LED_on(False)

    image = Image.new('1', (epd2in9.EPD_HEIGHT, epd2in9.EPD_WIDTH),
                      255)  # 255: clear the frame
    draw = ImageDraw.Draw(image)

    # write strings to the buffer
    font = ImageFont.truetype(
        '/home/pi/bandwidth-monitor/src/fonts/Roboto-Thin.ttf', 16)
    font2 = ImageFont.truetype(
        '/home/pi/bandwidth-monitor/src/fonts/Roboto-Black.ttf', 24)
    font3 = ImageFont.truetype(
        '/home/pi/bandwidth-monitor/src/fonts/Roboto-Light.ttf', 12)
    font4 = ImageFont.truetype(
        '/home/pi/bandwidth-monitor/src/fonts/Roboto-Thin.ttf', 10)
    font5 = ImageFont.truetype(
        '/home/pi/bandwidth-monitor/src/fonts/Verdana_Bold.ttf', 23)

    draw.rectangle((20, 6, 276, 48), fill=0)
    draw.text((26, 12), 'Bandwidth Monitor', font=font5, fill=255)

    start_y = 53
    offset_y_1 = 19
    offset_y_2 = 27
    draw.text((6, start_y), "Ping:", font=font, fill=COLORED)
    draw.text((10, start_y + offset_y_1), ('{:5.0f}'.format(ping)),
              font=font2,
              fill=COLORED)
    draw.text((76, start_y + offset_y_2), 'ms', font=font3, fill=COLORED)

    draw.text((100, start_y), "Download:", font=font, fill=COLORED)
    draw.text((100, start_y + offset_y_1),
              ('{:5.0f}'.format(bw_down / 1E6, 2)),
              font=font2,
              fill=COLORED)
    draw.text((168, start_y + offset_y_2), 'Mbps', font=font3, fill=COLORED)

    draw.text((210, start_y), "Upload:", font=font, fill=COLORED)
    draw.text((210, start_y + offset_y_1), ('{:4.0f}'.format(bw_up / 1E6, 2)),
              font=font2,
              fill=COLORED)
    draw.text((264, start_y + offset_y_2), 'Mbps', font=font3, fill=COLORED)

    current_time = time.strftime("%H:%M:%S, %d.%m.%Y")
    draw.text((6, 105), 'tested @' + current_time, font=font3, fill=COLORED)

    # display the frame
    epd.Clear(0xFF)
    #epd.set_frame_memory(image.rotate(270,expand=True), 0, 0)
    epd.display(epd.getbuffer(image.rotate(270, expand=True)))
    epd.sleep()

    payload = {
        VARIABLE_LABEL_1: round(bw_up / 1E6, 2),
        VARIABLE_LABEL_2: round(bw_down / 1E6, 2),
        VARIABLE_LABEL_3: round(ping, 2)
    }

    if print_messages:
        print("[INFO] Attemping to send data")
    post_request(payload)
    if print_messages:
        print("[INFO] finished")
Esempio n. 17
0
def main():

    epd = epd2in9.EPD()
    epd.init(epd.lut_full_update)

    # For simplicity, the arguments are explicit numerical coordinates
    image = Image.new('1', (epd2in9.EPD_WIDTH, epd2in9.EPD_HEIGHT),
                      255)  # 255: clear the frame

    db = dbconnect.getConnection()
    ##
    # there are 2 memory areas embedded in the e-paper display
    # and once the display is refreshed, the memory area will be auto-toggled,
    # i.e. the next action of SetFrameMemory will set the other memory area
    # therefore you have to set the frame memory twice.
    ##
    epd.clear_frame_memory(0xFF)
    epd.display_frame()
    epd.clear_frame_memory(0xFF)
    epd.display_frame()

    # for partial update
    epd.init(epd.lut_partial_update)
    #  image = Image.open('monocolor.bmp')
    ##
    # there are 2 memory areas embedded in the e-paper display
    # and once the display is refreshed, the memory area will be auto-toggled,
    # i.e. the next action of SetFrameMemory will set the other memory area
    # therefore you have to set the frame memory twice.
    ##

    #Image.new(mode,size,colour)  size is w,h tuple
    time_image = Image.new('1', (96 * 2, 32 * 2), 255)  # 255: clear the frame

    #Create a drawing object
    draw = ImageDraw.Draw(time_image)

    temp_image = Image.new('1', (96, 32), 255)  # 255: clear the frame
    draw_temp = ImageDraw.Draw(temp_image)

    hum_image = Image.new('1', (96, 32), 255)  # 255: clear the frame
    draw_hum = ImageDraw.Draw(hum_image)

    db_image = Image.new('1', (96, 32), 255)
    draw_db = ImageDraw.Draw(db_image)

    small_font = ImageFont.truetype(
        '/usr/share/fonts/truetype/droid/DroidSans.ttf', 32)

    #font = ImageFont.truetype('/usr/share/fonts/truetype/freefont/FreeMonoBold.ttf', 32) #font file, size
    font = ImageFont.truetype('/usr/share/fonts/truetype/droid/DroidSans.ttf',
                              64)  #font file, size

    image_width, image_height = time_image.size
    temp_width, temp_height = temp_image.size
    hum_width, hum_height = hum_image.size
    db_width, db_height = db_image.size

    readings = 0
    readingsBeforeSaving = 6 * 5  #we're waiting 10 secs, so 6 per min x 5  = 5 mins
    lastDBWrite = True

    readings = readingsBeforeSaving  #Trigger immediate db write

    while (True):
        #TIME
        # draw a rectangle to clear the image
        draw.rectangle((0, 0, image_width, image_height), fill=255)
        draw.text((0, 0), time.strftime('%H:%M'), font=font, fill=0)
        epd.set_frame_memory(time_image.rotate(270), 50, 80)

        #TEMP
        humidity, temperature = Adafruit_DHT.read_retry(
            Adafruit_DHT.AM2302, 4)  #sensor type, gpio pin
        draw_temp.rectangle((0, 0, temp_width, temp_height), fill=255)
        if humidity is not None and temperature is not None:
            draw_temp.text((0, 0),
                           '{0:0.1f}*'.format(temperature),
                           font=small_font,
                           fill=0)
        else:
            draw_temp.text((0, 0), '??', font=small_font, fill=0)
        epd.set_frame_memory(temp_image.rotate(270), 10, 10)

        #HUMIDITY
        draw_hum.rectangle((0, 0, hum_width, hum_height), fill=255)
        if humidity is not None and temperature is not None:
            draw_hum.text((0, 0),
                          '{0:0.1f}%'.format(humidity),
                          font=small_font,
                          fill=0)
        else:
            draw_hum.text((0, 0), '??', font=small_font, fill=0)
        epd.set_frame_memory(hum_image.rotate(270), 10, 200)

        if readings >= readingsBeforeSaving:
            if db is not None and db.is_connected():
                lastDBWrite = dbconnect.saveTempHumid(db, temperature,
                                                      humidity)
                readings = 0
                #clear error on display
                draw_db.rectangle((0, 0, db_width, db_height), fill=255)
                epd.set_frame_memory(db_image.rotate(270), 10, 100)
            else:
                log.error(
                    "No connection, or last write failed - attempting reconnect"
                )
                db = dbconnect.getConnection(
                )  #no db connection, so try and get one
                #display error on display
                draw_db.rectangle((0, 0, db_width, db_height), fill=255)
                draw_db.text((0, 0), 'No DB', font=small_font, fill=0)
                epd.set_frame_memory(db_image.rotate(270), 10, 100)

        epd.display_frame()
        time.sleep(10)
        readings = readings + 1
def main():
    epd = epd2in9.EPD()
    epd.init(epd.lut_partial_update)

    # For simplicity, the arguments are explicit numerical coordinates
    image = Image.new('1', (epd2in9.EPD_WIDTH, epd2in9.EPD_HEIGHT),
                      255)  # 255: clear the frame
    draw = ImageDraw.Draw(image)
    font = ImageFont.truetype(
        '/usr/share/fonts/truetype/freefont/FreeMonoBold.ttf', 24)
    epd.clear_frame_memory(0xFF)
    epd.set_frame_memory(image, 0, 0)
    epd.display_frame()

    # epd.delay_ms(1000)

    # Add following lines:
    ##
    # there are 2 memory areas embedded in the e-paper display
    # and once the display is refreshed, the memory area will be auto-toggled,
    # i.e. the next action of SetFrameMemory will set the other memory area
    # therefore you have to set the frame memory twice.
    ##
    epd.clear_frame_memory(0xFF)
    epd.display_frame()
    epd.clear_frame_memory(0xFF)
    epd.display_frame()

    # for partial update
    epd.init(epd.lut_partial_update)
    # epd.delay_ms(10000)
    image = Image.open('image1.bmp')
    imageNumber = 1
    delay = 10000
    image = image.rotate(90)
    epd.delay_ms(delay)
    epd.set_frame_memory(image, 0, 0)
    epd.display_frame()
    epd.set_frame_memory(image, 0, 0)
    epd.display_frame()
    print(imageNumber)
    # rotateAndClear()

    image = Image.open('image2.bmp')
    image = image.rotate(90)
    imageNumber = 2
    epd.set_frame_memory(image, 0, 0)
    epd.display_frame()
    epd.set_frame_memory(image, 0, 0)
    epd.display_frame()
    print(imageNumber)
    # rotateAndClear()

    while True:

        btn1_state = False
        btn2_state = False
        btn1_state = GPIO.input(16)
        btn2_state = GPIO.input(26)

        if btn1_state == True:  #False means Button NOT pressed
            print('BTN1 is pressed')
            if imageNumber == 2:
                image = Image.open('image3.bmp')
                imageNumber = 3
                delay = 10000
                image = image.rotate(90)
                epd.delay_ms(delay)
                epd.set_frame_memory(image, 0, 0)
                epd.display_frame()
                epd.set_frame_memory(image, 0, 0)
                epd.display_frame()
                print(imageNumber)
                # rotateAndClear()

                image = Image.open('image4.bmp')
                imageNumber = 4
                delay = 10000
                image = image.rotate(90)
                epd.delay_ms(delay)
                epd.set_frame_memory(image, 0, 0)
                epd.display_frame()
                epd.set_frame_memory(image, 0, 0)
                epd.display_frame()
                print(imageNumber)
                # rotateAndClear()

            elif imageNumber == 4:
                image = Image.open('image5.bmp')
                imageNumber = 5
                delay = 10000
                image = image.rotate(90)
                epd.delay_ms(delay)
                epd.set_frame_memory(image, 0, 0)
                epd.display_frame()
                epd.set_frame_memory(image, 0, 0)
                epd.display_frame()
                print(imageNumber)
                # rotateAndClear()

                image = Image.open('image6.bmp')
                imageNumber = 6
                delay = 10000
                image = image.rotate(90)
                epd.delay_ms(delay)
                epd.set_frame_memory(image, 0, 0)
                epd.display_frame()
                epd.set_frame_memory(image, 0, 0)
                epd.display_frame()
                print(imageNumber)
                # rotateAndClear()

                image = Image.open('image2.bmp')
                imageNumber = 2
                image = image.rotate(90)
                epd.set_frame_memory(image, 0, 0)
                epd.display_frame()
                epd.set_frame_memory(image, 0, 0)
                epd.display_frame()
                print(imageNumber)
                # rotateAndClear()

        if btn2_state == True and imageNumber == 2:  #False means Button NOT pressed
            print('BTN2 is pressed')
            image = Image.open('image7.bmp')
            btn2_state = False
            imageNumber = 7
            delay = 10000
            image = image.rotate(90)
            epd.delay_ms(delay)
            epd.set_frame_memory(image, 0, 0)
            epd.display_frame()
            epd.set_frame_memory(image, 0, 0)
            epd.display_frame()
            print(imageNumber)
            # rotateAndClear()

            if imageNumber == 7 and btn1_state == True:
                print('BTN1 is pressed again')
                image = Image.open('image3.bmp')
                imageNumber = 3
                delay = 10000
                image = image.rotate(90)
                epd.delay_ms(delay)
                epd.set_frame_memory(image, 0, 0)
                epd.display_frame()
                epd.set_frame_memory(image, 0, 0)
                epd.display_frame()
                print(imageNumber)
                # rotateAndClear()

                image = Image.open('image4.bmp')
                imageNumber = 4
                image = image.rotate(90)
                epd.set_frame_memory(image, 0, 0)
                epd.display_frame()
                epd.set_frame_memory(image, 0, 0)
                epd.display_frame()
                print(imageNumber)
                # rotateAndClear()
                btn1_state = False

            elif imageNumber == 7:
                image = Image.open('image8.bmp')
                imageNumber = 8
                # delay = 10000
                image = image.rotate(90)
                # epd.delay_ms(delay)
                epd.set_frame_memory(image, 0, 0)
                epd.display_frame()
                epd.set_frame_memory(image, 0, 0)
                epd.display_frame()
                print(imageNumber)
                # rotateAndClear()

                if imageNumber == 8 and btn2_state == True:
                    image = Image.open('image7.bmp')
                    imageNumber = 7
                    delay = 10000
                    image = image.rotate(90)
                    epd.delay_ms(delay)
                    epd.set_frame_memory(image, 0, 0)
                    epd.display_frame()
                    epd.set_frame_memory(image, 0, 0)
                    epd.display_frame()
                    print(imageNumber)
                    # rotateAndClear()

                elif imageNumber == 8 and btn2_state == False:
                    image = Image.open('image9.bmp')
                    imageNumber = 9
                    delay = 10000
                    image = image.rotate(90)
                    epd.delay_ms(delay)
                    epd.set_frame_memory(image, 0, 0)
                    epd.display_frame()
                    epd.set_frame_memory(image, 0, 0)
                    epd.display_frame()
                    print(imageNumber)
                    # rotateAndClear()

                    image = Image.open('image2.bmp')
                    imageNumber = 2
                    delay = 10000
                    image = image.rotate(90)
                    epd.delay_ms(delay)
                    epd.set_frame_memory(image, 0, 0)
                    epd.display_frame()
                    epd.set_frame_memory(image, 0, 0)
                    epd.display_frame()
                    print(imageNumber)
                    # rotateAndClear()

    ##
    # there are 2 memory areas embedded in the e-paper display
    # and once the display is refreshed, the memory area will be auto-toggled,
    # i.e. the next action of SetFrameMemory will set the other memory area
    # therefore you have to set the frame memory twice.
    ##
    epd.set_frame_memory(image, 0, 0)
    epd.display_frame()
    epd.set_frame_memory(image, 0, 0)
    epd.display_frame()

    time_image = Image.new('1', (96, 32), 255)  # 255: clear the frame
    draw = ImageDraw.Draw(time_image)
    font = ImageFont.truetype(
        '/usr/share/fonts/truetype/freefont/FreeMonoBold.ttf', 32)
    image_width, image_height = time_image.size